7

How do I get mouse coordinates after a SelectFeature, which returns the feature by itself?

0

5 Answers 5

3

When you init the map add this control:

mapMousePosition = new OpenLayers.Control.MousePosition({
        displayProjection: new OpenLayers.Projection(displayProjection)
});

In your handler get lonLat like this:

 var lonLat = map.getLonLatFromPixel(
      new OpenLayers.Pixel(
         mapMousePosition.lastXy.x,
         mapMousePosition.lastXy.y
);
2

my strategy (very resource intensive) is to listen to mousemove and constantly saving x and y values in global variables.

var mouseLat, mouseLon;
function init(){
  ...
  map.events.register("mousemove", map, function(e) {
    var position = this.events.getMousePosition(e);
    var lonlat = map.getLonLatFromPixel(position);
    var lonlatTransf = lonlat.transform(map.getProjectionObject(), proj4326);
    mouseLat = lonlatTransf.lat;
    mouseLon = lonlatTransf.lon;
    OpenLayers.Util.getElement("coords").innerHTML = "Lat: "+ mouseLat+" | Lon: "+mouseLon;
  });
  ...
}

when the feature is selected, i access these values from inside onFeatureSelect(event)

1
2

Try this for version 4 or higher:

var mouse_position = new ol.control.MousePosition({
  coordinateFormat: ol.coordinate.createStringXY(4),
  projection: 'EPSG:4326'
});
map.addControl(mouse_position);
1
  • 2
    Could you add some explanation? Nov 3, 2018 at 13:32
2

You can get it with these ways:

feature.geometry.getBounds().getCenterLonLat()

or

map.events.register("click", map, function(e) { 
    var latlon = map.getLonLatFromViewPortPx(e.xy) ;
    alert(lonlat)
});

or

new OpenLayers.Control.SelectFeature(layer,{
    hover:true,
    eventListeners:{
      onSelect:function(e){
        alert(e.feature.geometry)
    }
});

or

layer.events.on({
            "featureselected": function(e) {       
            alert(e)
            }
});    
1
  • Aragon, I think he is asking for mouse coordinates (mostly to display Popup) and not map coordinates. What your answer telling is to get map coordinates.
    – Suraj
    Jul 1, 2014 at 10:49
1

As an addition to the answer of @LaurentiuTurcu I set up a jsfiddle which demonstrates how to show the popup at the last mousePosition when you select a feature:

http://jsfiddle.net/expedio/2asrpnm8/

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