Getting Longitude and Latitude from Google Maps

No Gravatar

I’ve recently needed to get longitude and latitude coordinates for several locations. I first went about it by getting the values from http://www.geonames.org/. This was difficult because it requires you convert degrees, minutes and seconds to the wgs84 format. This is no treat.

After some googling I discovered that it’s pretty simple to make a Google map with a pin on it which tells you the coordinates of the pin in the wgs84 format.

Here’s the code:

HTML

<p id="coords"></p>
<div id="map_canvas" style="height: 600px"></div>

Javascript

 
function gogmap() {
 
	var map,
		marker, 
		point = new GLatLng(52.482780222078205, -102.65625); // default position
 
	var posChange = function() {
		point = marker.getLatLng();
		document.getElementById('coords').innerHTML = "lat: " + point.lat() + "<br>lng: " + point.lng();
	};
 
	map = new GMap2(document.getElementById("map_canvas"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GNavLabelControl());
	map.setCenter(point, 4);
 
	marker = new GMarker(point, {draggable: true});
 
	GEvent.addListener(marker, "dragend", posChange);
 
	map.addOverlay(marker);		
 
	posChange();
}
 
gogmap();

Live Example

When you drag the pin to a new location the longitude and latitude below will update.


Leave a Reply