Google地理位置状态始终为空

时间:2012-07-28 16:21:06

标签: javascript google-maps-api-3 geocode google-geocoder

我是地理代码的新手。我从用户找到lat和long的邮政编码,并将其与一组JSON中存在纬度和经度的附近位置进行比较。所以我必须遍历每个事件进行比较。地理编码状态始终为空,因此我无法获得用户输入的zipcode的lat和long。

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

这是我的Js功能。

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;
    };

在行 geocoder.geocode({'地址':zip},功能(结果,状态)之后,它会直接跳到 for循环

1 个答案:

答案 0 :(得分:4)

geocoder.geocode asyncronously ,所以您需要等待,直到它的响应将从谷歌的服务器传递,然后才使用相应的数据。将你的循环置于回调中:

  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  
相关问题