Retrieve Coordinates from Google Maps on Click

Technical Level: Beginner

Problem: Retrieve the coordinates from a click event on html/javascript google maps.

Required Tools:

Solution:Very simple solution, a Google map click event passes the coordinate as a parameter. I Use JQuery in my implementation of this map because I intend to make AJAX calls. If you are not familiar with JQuery, then the following codes can be substituted in the as follows:

[codesyntax lang=”javascript” lines=”normal”] $(“#SomeIDOfATextBox”).val(“Some value”); //Can be replaced by: document.getElementById(‘SomeIDOfATextBox’).value = “Some value”; [/codesyntax]

Below is the javascript used to setup the map and grab the coordinates:

[codesyntax lang=”javascript” lines=”normal”] var map; function initialize() {

if (GBrowserIsCompatible()) //a check to make sure the browser is compatible for GEmaps. { map = new GMap2(document.getElementById(“map_canvas”)); //assign the div to map var map.setCenter(new GLatLng(18, -77.4), 13); //centering the location map.setUIToDefault(); //setting the default location to the center.

//The GE event for clicking the map. GEvent.addListener(map, ‘click’, function(overlay, point) { map.clearOverlays(); //clearing the previous marker var lati = point.lat(); //Function to extract latitude var longi = point.lng(); //Function to extract longitude var marker = new GMarker(new GLatLng(lati, longi), { draggable: false }); //Setting the marker to clicked location map.addOverlay(marker); //adding the marker to the map //JQuery function to assign the lat and long to the values of textboxes. $(‘#LatTxt’).val(lati); $(‘#LonTxt’).val(longi); }); }

//This JQuery Function operates almost the same as the onload function, except more earlier $(function() { initialize();//call to initialize the map. } [/codesyntax]

[codesyntax lang=”html4strict” lines=”normal”]

<div id="map_canvas" style="width: 600px; height: 400px;">
</div>
<label>
Latitude
<input id="LatTxt" disabled="disabled" type="text" />
</label>
<label>
Longitude
<input id="LonTxt" disabled="disabled" type="text" />
</label>

[/codesyntax]

Below is a screenshot of my extended version (I’ll show how to get Geo-coded locations in a next post):

PS. Google Geo-Code service sucks for Jamaica. I’m now seeking alternative data sets.