问题
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 relate them to the address objects I'm looping through. I can't find anything in the geocode response that tells me which of my requests it 'came from.'
Is there a way to do that?
This is my function:
geocode() {
var lv_location;
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address' : this.address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// what data in results can be used to relate the location to the address?
lv_location = results[0].geometry.location;
}
markerCounter++;
if (markerCounter >= 60) finishSurnames();
});
}
回答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){
return function(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'
];
function initMap() {
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);
});
}
function geocode(geocoder, address) {
geocoder.geocode({'address': address}, (function(originalAddress) {
return function(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;
}
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap">
</script>
I hope this helps!
来源:https://stackoverflow.com/questions/47600136/in-my-geocoder-geocode-callback-how-do-i-determine-which-request-the-result-cor