代码之家  ›  专栏  ›  技术社区  ›  yesh

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

  •  0
  • yesh  · 技术社区  · 13 年前

    我是地理编码的新手。我从用户那里得到了邮政编码,找到了纬度和经度,并将其与附近的一组位置进行了比较,这些位置的纬度和经度都存在于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},函数(结果,状态) 它直接跳到 for循环

    1 回复  |  直到 13 年前
        1
  •  4
  •   Engineer    13 年前

    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