Search code examples
javascriptgoogle-maps-api-3google-geocoder

How to get a javascript lat/lng variable out of a Google Map API function


I need to get the Lat/Lng from a Postcode, so I'm using Google Map/Geocode API.

I can't get the lat/lng variable out of the function running within the Geocode script. The code I'm using is below:

<input id="address" type="textbox" value="">
<script type="text/javascript">
var lat;
var lng;
function addressurls(address) {
var address = document.getElementById("address").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function postcodesearch(results, status) 
{   
  if (status == google.maps.GeocoderStatus.OK) 
  {
    var lat = results[0].geometry.location.lat();
    var lng = results[0].geometry.location.lng();
  }
  else {
    alert("Error");
  }
  return lat;
  return lng;
});
var laturl = "&lat=";
var lonurl = "&lon=";
var postcode = document.getElementById("address").value;
var addressurl = "/distributors-search?address=" + postcode + laturl + lat+ lonurl + lng;
parent.location=addressurl;
}
</script>
<input type="button" value="Encode" onclick="addressurls('address'), parent.location=addressurl">

Does anyone know how to fix it?


Solution

  • Geocoding is asynchronous, you need to use the returned data in the callback function

    <input id="address" type="textbox" value="">
    <script type="text/javascript">
    var lat;
    var lng;
    function addressurls(address) {
    var address = document.getElementById("address").value;
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': address}, function postcodesearch(results, status) 
    {   
      if (status == google.maps.GeocoderStatus.OK) 
      {
        var lat = results[0].geometry.location.lat();
        var lng = results[0].geometry.location.lng();
        var laturl = "&lat=";
        var lonurl = "&lon=";
        var postcode = document.getElementById("address").value;
        var addressurl = "/distributors-search?address=" + postcode + laturl + lat+ lonurl + lng;
        parent.location=addressurl;
      }
      else {
        alert("Error");
      }
    });
    
    }
    </script>
    <input type="button" value="Encode" onclick="addressurls('address'), parent.location=addressurl">