Google geocode status always empty

天涯浪子 提交于 2019-12-11 18:47:16

问题


I am new to geocode. I am getting the zip code from the user finding the lat and long and comparing it with a set of nearby locations who latitude and longitude are present in a JSON. So I have to loop through each event to compare. The geocode status is always empty and hence I am not able to get the lat and long for the zipcode which the user has entered.

<script src="http://maps.google.com/maps/api/js?sensor=false"></script>

This is my Js function.

self.find_events = function find_events(zip, eventId) {
        var data = LAH.events.events_data,
        matches_found = 0;
        var today = new Date();
        var zip = zip || null;
        var eventId = eventId || null;
        geocoder = new google.maps.Geocoder();
        if(geocoder){       
        geocoder.geocode( { 'address': zip }, function(results, status) { // status is empty
        if (status == google.maps.GeocoderStatus.OK) {
        var userLat = results[0].geometry.location.lat();
        var userLng = results[0].geometry.location.lng();
        userLatLng = results[0].geometry.location;
        }
        });//end geocode        
        } 
        for (var i = data.length-1; i--;) { 
            if (eventId === null) {
                var eventEnd = data[i].endDate;
                var calc_dis = calculateDistance(userLat, userLng, parseFloat(data[i].lat), parseFloat(data[i].lng));
                if ((zip == 'all' || calc_dis === true) && today < eventEnd) {
                    display_event(data[i]);
                    matches_found += 1;
                }               
            }
            else {
                // eventId is valid, only display what we found in the query string
                if (data[i].eventId === parseInt(eventId, 10)) {
                    display_event(data[i]); 
                    matches_found += 1;
                }
            }

        }       
        matches_found ? display_table() : display_no_results();     
        return matches_found;
    };

After the line geocoder.geocode( { 'address': zip }, function(results, status) it skips directly to the for loop.


回答1:


geocoder.geocode works asyncronously, so you need to wait untill its response will be delivered from google's servers,and only then use reponded data.Put your loop inside of callback:

  geocoder.geocode( { 'address': zip }, function(results, status) { // status is empty
    if (status == google.maps.GeocoderStatus.OK) {
       var userLat = results[0].geometry.location.lat();
       var userLng = results[0].geometry.location.lng();
       userLatLng = results[0].geometry.location;
       for (var i = data.length-1; i--;) { 
          //loop body
       }
    }       
  });//end geocode  


来源:https://stackoverflow.com/questions/11702679/google-geocode-status-always-empty

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