Map coordinates using JavaScript
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 />
<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:
-
function ShowCoords(event) {
-
// The are differencies in getting coordinates in different browsers.
-
if (event.offsetX) { // this is for IE. We get the coordinates on picture immidiately
-
var x=event.offsetX;
-
var y=event.offsetY;
-
}
-
else { // this is other browsers: we get global page coordinates and have to minus picture's (left,top)
-
var x=event.pageX-document.getElementById('mapid').offsetLeft;
-
var y=event.pageY-document.getElementById('mapid').offsetTop;
-
}
-
// now we output x and y coordinates under the map picture
-
document.getElementById('divx').innerHTML=x;
-
document.getElementById('divy').innerHTML=y;
-
-
// and put the pointer to the correct place (where we clicked)
-
document.getElementById('pointer').style.left=x - document.getElementById('mapid').width - (document.getElementById('pointer').width / 2);
-
document.getElementById('pointer').style.top=y - document.getElementById('mapid').height + 5;
-
-
// make our flag visible
-
document.getElementById('pointer').style.visibility='visible';
-
-
}
Here is it. You can see demo here: http://www.aurorascorpio.com/files/map/