2

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?

Wouter J
  • 41,455
  • 15
  • 107
  • 112
trysmudford
  • 578
  • 4
  • 16

1 Answers1

3

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">
geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • 2
    There is no need here to redefine lat and lng, also, address is being reassigned. You are also calling document.getElementById("address").value twice and assinging to different objects – Ben Taliadoros Aug 22 '13 at 16:32