How do I get mouse coordinates after a SelectFeature, which returns the feature by itself?
5 Answers
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
);
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)
-
1To decrease resource consumption, use debounce/throttle techniques benalman.com/projects/jquery-throttle-debounce-plugin Nov 12, 2014 at 23:07
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
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 notmap coordinates
. What your answer telling is to get map coordinates.– SurajJul 1, 2014 at 10:49
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: