1

I am attempting to Geocode a physical address using the Google Maps API in a Meteor template.

This is the function I am using to run the geocoder:

codeAddress = function(address, callback) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      callback(results[0].geometry.location);
    } else {
      callback(0);
    }
  });
}

Using a static address for testing purposes, this is the function I am using to call codeAddress():

codeAddress("3100 East Fletcher Avenue, Tampa, FL, United States", function(result) {
  console.log(result);
});

Here is the Problem

The console output returns nothing for the Lat and Long:

Console Output

But the response from the Google Maps API does, in fact, contain the needed information:

HTTP Response

I know that the API is asynchronous but I don't know enough about Meteor to figure out how to retrieve the data after it has been returned by the API.

cbronson
  • 366
  • 1
  • 9
  • Are you accessing the `lat`/`lng` attributes at the root node? Based on the [Geocode Response](https://developers.google.com/maps/documentation/geocoding/intro#JSON) you can access it on the `results[].geometry.location`. – adjuremods Dec 29 '15 at 00:14
  • Thanks for the reply. The codeAddress function accesses the attributes directly from the location node. (See line 7 in the first code snippet) – cbronson Dec 29 '15 at 00:27
  • Ha! I didn't see that on the first take. i can't find anything wrong with the code as you're accessing it correctly (and is similar to the Geocoding service sample from the official documentation). Have you seen [this inquiry](http://stackoverflow.com/questions/5245915/how-do-i-return-a-longitude-and-latitude-from-google-maps-javascript-geocoder)? It seems (somewhat) similar – adjuremods Dec 29 '15 at 00:40

1 Answers1

1

There is nothing wrong with the provided codeAddress function, the reason why lat/lng values of results[0].geometry.location object are not printed in the console is because results[0].geometry.location of LatLng type which in turn does not expose lat and lng properties.

To print value representation of LatLng class you could utilize the following functions:

  • toString() - Converts to string representation.
  • toUrlValue(precision?:number) - Returns a string of the form "lat,lng" for this LatLng. We round the lat/lng values to 6 decimal places by default.
  • lat() or lng() - Returns the latitude or longitude in degrees

Example

codeAddress("3100 East Fletcher Avenue, Tampa, FL, United States", function (result) {
    console.log(result.toString());
  });
Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193