Joeblackdev
Joeblackdev

Reputation: 7327

How to geocode in google maps v3

I've been looking through version 3 of the google maps api, and I have put together a small script to geocode an address. The problem is that I want to see If i can extract the lat lng without having to 'split()' the result.

function getLatLng() {
  var geocoder = new google.maps.Geocoder();
  var query = "12 henry street, dublin 1, dublin, ireland";
  var address = query;   
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var latLng = results[0].geometry.location;
      alert('Geocode succesful ' + latLng);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });  
}

I want to get the lat and the lng from the var latLng. Can this be done without calling latLng.split(',');?

Thanks so much for your help

Upvotes: 1

Views: 4374

Answers (2)

Newbie
Newbie

Reputation: 1714

You can use this:

var lat= results[0].geometry.location.lat();                     
var lng= results[0].geometry.location.lng();                     
alert(lat);  
alert(lng);

Upvotes: 1

Andrew Leach
Andrew Leach

Reputation: 12973

Never use internal variables exposed by the API. They can and do change from release to release. Always use documented methods.

results[0].geometry.location is a LatLng object, so use the relevant methods:

var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();

Upvotes: 9

Related Questions