Volodymyr Osypov blog

May 9, 2008

Map coordinates using JavaScript

Filed under: JavaScript — Tags: , , — admin @ 10:41 am

Nowadays we have Google Maps with API, that helps us to creat great web applications with maps, but what if our city isn't well detailed in Google Maps? Then we need to create something ours. Or we have a picture and need to determine the coordinates of mouse click.

I want to show you just simple example with the map. When user clicks on it - a little flag displays in this point. We need map.gif (picture with map) and pointer.gif (little picture with flag).

First we create just HTML page with map, yet invisible flag and div's to display X and Y coordinates:

<html>
<head>
<title>Map</title>
</head>
<body>
<br />
Click on the map! :)
<br /><br />
&nbsp;&nbsp;&nbsp;&nbsp;
<img id="mapid" src="map.gif" border=0 onClick="ShowCoords(event)" alt="Map" />
<img id="pointer" src="pointer.png" width="30" height="30" style="visibility:hidden; z-index:2;position:relative;">
<br />

<br />
x: <div id="divx" style="display: inline;"></div>
<br />
y: <div id="divy" style="display: inline;"></div>
</body>
</html>

As you see, when we click on the map picture ShowCoords(event) function runs. So let's programm this function in <head> ... </head> section:

JAVASCRIPT:
  1. function ShowCoords(event) {
  2. // The are differencies in getting coordinates in different browsers.
  3. if (event.offsetX) { // this is for IE. We get the coordinates on picture immidiately
  4. var x=event.offsetX;
  5. var y=event.offsetY;
  6. }
  7. else { // this is other browsers: we get global page coordinates and have to minus picture's (left,top)
  8. var x=event.pageX-document.getElementById('mapid').offsetLeft;
  9. var y=event.pageY-document.getElementById('mapid').offsetTop;
  10. }
  11. // now we output x and y coordinates under the map picture
  12. document.getElementById('divx').innerHTML=x;
  13. document.getElementById('divy').innerHTML=y;
  14.  
  15. // and put the pointer to the correct place (where we clicked)
  16. document.getElementById('pointer').style.left=x - document.getElementById('mapid').width - (document.getElementById('pointer').width / 2);
  17. document.getElementById('pointer').style.top=y - document.getElementById('mapid').height + 5;
  18.  
  19. // make our flag visible
  20. document.getElementById('pointer').style.visibility='visible';
  21.  
  22. }

Here is it. You can see demo here: http://www.aurorascorpio.com/files/map/

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress