-2

I'm trying to get the latitude of a city using this function:

function get_lat(city) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    "address": city
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
      var location = results[0].geometry.location;
      return location.lat();
    } else {

    }
  });
}

This function (example: get_lat("Amsterdam") always returns undefined). The geocoder itself does work: adding console.log(location.lat())before the return line outputs the correct latitude.

Does anyone know what I am doing wrong?

Update:

How would I use the latitude in the map?

 get_lat('Amsterdam', function(lat) {
$scope.map = {center: {latitude: lat, longitude: -99.6680 }, zoom: 4 };
});

doesn't work on first visit (it's in an Ionic app). After refreshing it does work.

binoculars
  • 2,226
  • 5
  • 33
  • 61

1 Answers1

1

You are returning from an anonymous function(results, status) inside get_lat, not from get_lat.

Since you are retrieving the latitude in a callback from google, what you can do is add a second parameter (another callback function) to get_latthat returns the latitude once you retrieve it from google's services:

function get_lat(city, callback) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    "address": city
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
      var location = results[0].geometry.location;
      callback(location.lat()); // return lat
    } else {
      callback(SOME_ERROR_VALUE); // return error
    }
  });
}

And you would use it like:

get_lat('Amsterdam', function(lat)) {
    console.log('here is my lat: ' + lat);
});
nem035
  • 34,790
  • 6
  • 87
  • 99
  • You guys rock! Thanks! – binoculars Dec 24 '15 at 16:17
  • @binoculars no problem, glad to help :) – nem035 Dec 24 '15 at 16:19
  • I've encountered a new problem :) . Eventually, I want the coordinates here: `$scope.map = {center: {latitude: ..., longitude: ... }, zoom: 4 };` I've tried wrapping the `get_lat function around it (see update above), but that breaks my maps (but the map re-appears after refresh... pretty weird). Any thoughts? – binoculars Dec 24 '15 at 16:26
  • @binoculars well, i'm not that familiar with angular so you might need to ask a new question but I believe most likely you are not properly reacting to the asynchronous callback from `get_lat`. Meaning some of your code executes **synchronously** and **not after** the callback. [Check out this question](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) for many ways of dealing with this. Also make sure that updating the latitude within `scope.map`, updates the DOM as well. – nem035 Dec 24 '15 at 16:31