Google Maps API function does not return results in time

眉间皱痕 提交于 2019-12-13 10:22:27

问题


So I have an array of objects with the following properties: Address, Latitude, Longitude, and Title

 poi("139 Main St", 0, 0, "Farmer's Market" ),
 poi("18 N Hopkins Ave", 37.4455, -143.7728, "YMCA" ),
 poi("42 Universe St", 37.4855, -143.8781, "Original Pizza #32" )

Now, the first object does not have anything set for latitude and longitude, so I was hoping to use Google's Geocode API to fill in the missing data. I included the API script link with my API key, which is working fine.

I then created a for loop that goes through the array and finds any object with missing data. It's supposed to go through and replace any empty cells with the correct information. However, though the information is retrieved, it does so after the loop is completed. I can console out the correct information, but only after the function returns empty data.

for (i=0; i < poiArray.length; i++ ) {
    var curr = poiArray[i];

    if ( !curr.lat || !curr.long ) {

        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'address': curr.address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                cur.lat = results[0].geometry.location.k;
                cur.long = results[0].geometry.location.B;
            } else {
                console.log('failed to include ' + curr.title);
                poiArray.splice(i--, 1);    
            }

       });  

    }

}

I've tried timeout and nesting functions, but nothing seems to work. Any suggestions?


Let me mention a bit more weirdness: if I console after if (status == google.maps.GeocoderStatus.OK) { the variable i in my for loop, I get the last number of my array... every time. And the loop only seems to update the last item in my array if I console my poiArray after the asynchronous data from Google has loaded.


回答1:


you can solve your issue with function closure. Also, you shouldn't use undocumented properties of the Google Maps Javascript API v3 (.k, .B), they will change with updates of the API and break your code.

var geocoder = new google.maps.Geocoder();
function geocodeAddress(curr, i) {
  geocoder.geocode( { 'address': curr.address }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
       cur.lat = results[0].geometry.location.lat();
       cur.long = results[0].geometry.location.lng();
    } else {
       console.log('failed to include ' + curr.title);
       poiArray.splice(i--, 1);    
    }
  });  
}
for (i=0; i < poiArray.length; i++ ) {
    var curr = poiArray[i];
    if ( !curr.lat || !curr.long ) {
        geocodeAddress(curr, i);
    }
}


来源:https://stackoverflow.com/questions/24894023/google-maps-api-function-does-not-return-results-in-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!