Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get Latitude And Longitude Javascript Function
/* Get the latitude and longitude from address:
Author : Bastin Robins J
*/
// Add the link to webpage
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
//Function to covert address to Latitude and Longitude
var getLocation = function(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
console.log(latitude, longitude);
}
});
}
//Call the function with address as parameter
getLocation('New York');
@sachintaware
Copy link

How can this be modified to get more precise results? This currently does not give me the closest result to what I get when I check it on maps.google.com explicitly.

@Barath-prakash
Copy link

Try using this instead:

var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
It's bit hard to navigate Google's api but here is the relevant documentation.

One thing I had trouble finding was how to go in the other direction. From coordinates to an address. Here is the code I neded upp using. Please not that I also use jquery.

$.each(results[0].address_components, function(){
$("#CreateDialog").find('input[name="'+ this.types+'"]').attr('value', this.long_name);
});
What I'm doing is to loop through all the returned address_components and test if their types match any input element names I have in a form. And if they do I set the value of the element to the address_components value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment