【问题标题】:Google geocode status always emptyGoogle 地理编码状态始终为空
【发布时间】:2012-07-28 16:21:06
【问题描述】:

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

<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) 之后直接跳到 for 循环

【问题讨论】:

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


    【解决方案1】:

    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  
    

    【讨论】:

    • 向 go​​ogle map api ?address=ZIP&sensor=false 发出 ajax 请求并解析 JSON 并获取 zip 有什么区别或优势。
    • 由于SOP,你不能对google服务进行Ajax请求。所以使用google的javascript API(如google.maps.Geocodergoogle.maps.DistanceService等)服务的唯一方法,内部使用JSONP
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多