Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding coordinates of a point in OpenLayers

Tags:

gis

openlayers

How can one get the coordinates of a particular point on a map in OpenLayers?

like image 534
cuser Avatar asked Jan 29 '10 08:01

cuser


People also ask

How do I get coordinates on OpenLayers?

Calling the useGeographic function in the 'ol/proj' module makes it so the map view uses geographic coordinates (even if the view projection is not geographic).


2 Answers

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
} 
like image 53
mloskot Avatar answered Sep 21 '22 09:09

mloskot


<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.

like image 44
MINDoSOFT Avatar answered Sep 22 '22 09:09

MINDoSOFT