How can one get the coordinates of a particular point on a map in OpenLayers?
Asked
Active
Viewed 1.5k times
11
-
Do you mean getting the coordinates of the point where the user clicked? Or showing the coordinates of the cursor when moving it over the map? – amercader Jan 29 '10 at 10:01
-
yes, but I want to get all the coordinates of the previously marked points on the same map. Is it possible? I'm implementing a crime mapping system. For that I need that functionality. thanks. – cuser Feb 03 '10 at 14:48
-
What you mean as "previously marked points"? I think you need to be more specific and describe complete user's interaction flow, otherwise it will be difficult to help you. – mloskot Feb 03 '10 at 17:43
2 Answers
33
Handle click event on map Click handler. Here is one of many sample codes you can find in OpenLayers mailing list archives:
map.events.register('click', map, handleMapClick);
function handleMapClick(e)
{
var lonlat = map.getLonLatFromViewPortPx(e.xy);
// use lonlat
// If you are using OpenStreetMap (etc) tiles and want to convert back
// to gps coords add the following line :-
// lonlat.transform( map.projection,map.displayProjection);
// Longitude = lonlat.lon
// Latitude = lonlat.lat
}

mloskot
- 37,086
- 11
- 109
- 136
5
<html>
<head>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
function init(){
map = new OpenLayers.Map('map');
base_layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );
map.addLayer(base_layer);
map.zoomToMaxExtent();
map.events.register('click', map, handleMapClick);
}
function handleMapClick(evt)
{
var lonlat = map.getLonLatFromViewPortPx(evt.xy);
// use lonlat
alert(lonlat);
}
</script>
</head>
<body onload="init()">
Hello Map.<br />
<div id="map"></div>
</body>
</html>
@mloskot Your answer is great you had a mistake with the evt variable.
Just added the html markup to make it a working page.

MINDoSOFT
- 53
- 1
- 6