0

I am using the code below (entire html code posted) to return the latitude longitude from address but my problem is the way I am calling the function otherwise dealing with latitude longitude. The function returns null but if I display the contents inside the function (please search for "alert(results[0].geometry.location);// works fine here" I receive the right values,

what is wrong with my javascript code that the getLatLng function returns null?

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Geocoding service</title>
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
      #panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -180px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 8,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeAddress() {
  var address = document.getElementById('address').value;
  alert (getLatLng(address));
}

var getLatLng = function(stAddress){

  return geocoder.geocode( { 'address': stAddress}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      alert(results[0].geometry.location);// works fine here
      return results[0].geometry.location;
    } else {
      return -1;
    }
  });

}


google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="panel">
      <input id="address" type="textbox" value="Vancouver downtown">
      <input type="button" value="Geocode" onclick="codeAddress()">
    </div>
    <div id="map-canvas"></div>
  </body>
</html>
Cœur
  • 37,241
  • 25
  • 195
  • 267
C graphics
  • 7,308
  • 19
  • 83
  • 134
  • possible duplicate of [How do I return a variable from Google Maps JavaScript geocoder callback?](http://stackoverflow.com/questions/2993563/how-do-i-return-a-variable-from-google-maps-javascript-geocoder-callback) – Anto Jurković Apr 20 '14 at 20:57

2 Answers2

1

You are returning the results to the geocode, not to the outside function - getLatLng. Look up callback functions and the geocoder and it will make more sense. I had this trouble last week and I finally understood it

tcatchy
  • 849
  • 1
  • 7
  • 17
  • Could you be more specific and make some suggestions with the code please? – C graphics Apr 20 '14 at 18:14
  • 1
    Geocoder is its own function, so returning a value within it does not alter any values in getLatLng. Best to look at https://developers.google.com/maps/documentation/javascript/geocoding It really helped me – tcatchy Apr 20 '14 at 18:24
1

The problem here is, that you are dealing with asynchronous code but you are expecting it to behave like synchronous code. Which means that geocoder.geocode is an asynchronous method and by invoking it your executing flow continues to next lines without waiting the results. Later on, geocoder.geocode will fire a callback when it is done processing your request.

Therefore, the moment you call getLatLng and try to see the results, it doesn't even have them yet. However, when it does - the code inside the block is ready to be executed:

geocoder.geocode( { 'address': stAddress}, function(results, status) {

   // When processing done, this part is executed, yey!    

});

As an example, you could pass an anonymous function inside your getLatLng method and let it show the returned value when geocoder.geocode has finished executing.

Rather than this:

alert (getLatLng(address));

You do this:

getLatLng(address, function(value) {

   alert("ok: " + value);

});

And your method is something like this:

var getLatLng = function(stAddress, cb){

  geocoder.geocode( { 'address': stAddress}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      return cb(results[0].geometry.location);
    } else {
      return cb(-1);
    }
  });

}

See that anonymous function is named as a cb (shorthand to callback) inside the function.

After you run it, you should see the alert when the geocode method has done it's magic. Hopefully this all makes more sense now. Cheers.

Here is Js Fiddle example

Mauno Vähä
  • 9,688
  • 3
  • 33
  • 54