I don't "get" callback functions very well. I am trying to build a section of my web page which shows the nearest stores for a customer's address. There are fields on the page that will have the logged in customer's address. When the user goes to the page, I want my code to grab their address, get that latitude and longitude coordinates, and then center the map based on their address. However, there is a short delay while the geocoder retus their coordinates, by which point the call to create the map has already happened. I know there should by a callback for this async operation, but I can't figure out how to structure it.
Here is the code:
var geocoder;
var map;
var lat = 0;
var long = 0;
function GetLatLongFromPage(callback) {
console.log("GetLatLongFromPage");
geocoder = new google.maps.Geocoder();
// Build address from user info
var address = document.getElementById('<%=AddressControl.FindControl("txtAddress1").ClientID %>').value;
address += " " + document.getElementById('<%=AddressControl.FindControl("txtAddress2").ClientID %>').value;
address += " " + document.getElementById('<%=AddressControl.FindControl("txtCity").ClientID %>').value;
address += " " + document.getElementById('<%=AddressControl.FindControl("ddlState").ClientID %>').value;
address += " " + document.getElementById('<%=AddressControl.FindControl("txtZip").ClientID %>').value;
lat = 0;
long = 0;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log("1: " + lat);
lat = results[0].geometry.location.lat();
console.log("2: " + lat);
console.log("3: " + long);
long = results[0].geometry.location.lng();
console.log("4: " + long);
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
initMap();
}
function initMap() {
console.log("initMap");
geocoder = new google.maps.Geocoder();
console.log("5: " + lat);
console.log("6: " + long);
var latlng = new google.maps.LatLng(myLat, myLong);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
<script src="https://maps.googleapis.com/maps/api/js?key=MyAPIKey&callback=GetLatLongFromPage" async defer></script>
And this is what appears in the console, showing the execution is not happening as I want it:
GetLatLongFromPage
cart.aspx:1048 initMap
cart.aspx:1051 5: 0
cart.aspx:1052 6: 0
cart.aspx:1033 1: 0
cart.aspx:1035 2: 37.4223652
cart.aspx:1036 3: 0
cart.aspx:1038 4: -122.08418599999999
