10

I want map coordinates as mouse over effect in OpenLayers. I am using the following code. However it is showing pixel coordinates:

    map.events.register("mousemove", map, function(e) {      
      var position = e.map.x + e.xy.y;
      OpenLayers.Util.getElement("tooltip").innerHTML = position 
    });
  • wow 7k views and only 4 up votes? – Below the Radar Feb 19 '14 at 16:18
11

you can convert pixels to lat/long with the help of getLonLatFromPixel() function.

See also openlayers FAQ.

|improve this answer|||||
11

To add to simo's answer... here's an example:

map.events.register("mousemove", map, function (e) {
    var position = e.map.getLonLatFromViewPortPx(e.xy);
    OpenLayers.Util.getElement("tooltip").innerHTML = "<label>Latitude: " + position.lat + "</label><br/><label>Longitude: " + position.lon + "</label>";
});

You may need to transform from Mercator to Geographic as i did... if so:

var position = e.map.getLonLatFromViewPortPx(e.xy).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
|improve this answer|||||
5

As of Openlayers 2.12 the following approach works for accessing the coordinates from hovering:

map.events.register("mousemove", map, function (e) {            
var point = map.getLonLatFromPixel( this.events.getMousePosition(e) )     
    console.log(point.lon, point.lat)
});
|improve this answer|||||
1

In Openlayers 2.13, you can do it like:

map.addControl(
    new OpenLayers.Control.MousePosition({
        prefix: 'Coords: ',
        separator: ' | ',
        numDigits: 2,
        emptyString: 'Mouse not over map'
    })
);
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.