MouseOver & Coordinates

Martin Weinelt mweinelt at PLANIGLOBE.COM
Thu Mar 10 06:42:50 EST 2005


On Thursday 10 March 2005 11:07, Stefan Schwarzer wrote:
> Hi,
>
> I would like to display the coordinates in a corner of the map, when a
> user moves the mouse over it. Is there any Javascript (or Java) code
> out there that would do this?
>
> Thanks for any suggestions.
>
> Stef

Stefan,

you need to know the pixel size of your map image in map units (DD, meters,..).
using MapScript you can pass this value along with every new map generated
as a (hidden) value and set a javascript object or variable to this value.
With mapserver CGI you must calculate this value by image size and map extent
yourself.

Next you define an eventhandler for the mouseover event of your map image,
for instance:

function MapElmOverHndl(e) {
  var imgOrig = theMap.getorig();
  var posx = ((e.offsetX * theMap.getcsz())+imgOrig[0]);
  var posy = (((400-e.offsetY) * theMap.getcsz())+imgOrig[1]));
  Dspl.innerHTML=posx+' '+posy;
}

'theMap.getorig()':  returns minx, miny (mapunits) of the current image
'theMap.getcsz()': returns the cellsize (pixelsize) in mapunits
'400' is the image height in pixels
'Dspl' is a document element like <p>, <td>, <div> or some such.

Once you got the handler you add this event handler to your map image.
If your map image got an id of - say - 'myMap':

for DOM-Browsers you type:
document.getElementById('myMap').addEventListener("mousemove",MapElmOverHndl , false)

for IE6 you type:
document.all['myMap''].attachEvent("onmousemover", MapElmOverHndl);

A cross browser solution could look similar to:
var d= document;
if (!d.getElementById && d.all) d.getElementById = new Function('id', 'return d.all[id]');

function X_addEventListener(elm, evt, lstnr, useCapture) {
  (! elm.addEventListener && d.all)? elm.attachEvent('on'+evt, lstnr) : elm.addEventListener(evt, lstnr, useCapture);
}

Now you add the listener by:
myMapElm= d.getElementById('myMap');
X_addEventListener(myMapElm ,"mousemove", MapElmOverHndl, false);

Cheers, Martin



More information about the mapserver-users mailing list