谷歌地理编码状态始终为空

Google geocode status always empty

本文关键字:状态 编码 谷歌      更新时间:2024-04-23

我是地理编码的新手。我从用户那里得到了邮政编码,找到了纬度和经度,并将其与JSON中存在的一组附近位置进行了比较。所以我必须循环浏览每个事件进行比较。地理编码状态总是空的,因此我无法获得用户输入的邮政编码的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({'address':zip},function(results,status)之后,它直接跳到循环的

geocoder.geocode异步工作,因此您需要等到它的响应从谷歌的服务器发出,然后才使用响应的数据。将您的循环放入回调:

  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