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?

1 Answer 1

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">
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.