In My Geocoder Geocode Callback, How Do I Determine Which Request The Result Corresponds To?
I'm looping through about 60 addresses to get them geocoded for use on a Google Map. My callback (below) seems to work well for collecting the locations, but I need to know how to
Solution 1:
In JavaScript you can use Immediately-invoked function expression that will create a function scope also known as closure. You should change your function to something similar to
geocode() {
var lv_location;
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address' : this.address}, (function(originalAddress){
returnfunction(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// what data in results can be used to relate the location to the address?//You can use the originalAddress variable here to relate result to request
lv_location = results[0].geometry.location;
}
markerCounter++;
if (markerCounter >= 60) finishSurnames();
};
})(this.address));
}
}
Have a look at my example, it geocodes 3 addresses and print in console result and corresponding request string
var addresses = [
'av Diagonal 197, Barcelona',
'av Lucas Vega 53, San Cristobal de La Laguna',
'Metrologichna 14, Kiev'
];
functioninitMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
var geocoder = new google.maps.Geocoder();
addresses.forEach( function(address) {
geocode(geocoder, address);
});
}
functiongeocode(geocoder, address) {
geocoder.geocode({'address': address}, (function(originalAddress) {
returnfunction(results, status) {
if (status === 'OK') {
console.log("Search: " + originalAddress + "->" + results[0].geometry.location.toString());
} else {
console.log("Search: " + originalAddress + "->" + status);
}
};
})(address));
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<divid="map"></div><scriptasyncdefersrc="https://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap"></script>
I hope this helps!
Post a Comment for "In My Geocoder Geocode Callback, How Do I Determine Which Request The Result Corresponds To?"