7

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

closed as off-topic by PolyGeo Nov 3 '18 at 21:39

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "When seeking help to debug/write/improve code always provide the desired behavior, a specific problem/error and the shortest code (as formatted text, not pictures) needed to reproduce it in the question body. Providing a clear problem statement and a code attempt helps others to help you." – PolyGeo
If this question can be reworded to fit the rules in the help center, please edit the question.

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)

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);
  • 2
    Could you add some explanation? – Stefan Nov 3 '18 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)
            }
});    
  • 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 '14 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.