【问题标题】:Google maps API returning null zip code (used to work)谷歌地图 API 返回空邮政编码(用于工作)
【发布时间】:2014-01-24 15:08:26
【问题描述】:

我已经使用以下代码一段时间了,发现它已停止工作并引发错误。警报显示为空。地图 API 是否已更改?我已经加载 https://maps.googleapis.com/maps/api/js?sensor=falsehttps://maps.gstatic.com/intl/en_us/mapfiles/api-3/15/5/main.js

function geo(){
     if(navigator.geolocation) {
        var fallback = setTimeout(function() { fail('10 seconds expired'); }, 10000);
        navigator.geolocation.getCurrentPosition(
            function (pos) {
                clearTimeout(fallback);
                console.log('pos', pos);
                var point = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
                new google.maps.Geocoder().geocode({'latLng': point}, function (res, status) {
                    if(status == google.maps.GeocoderStatus.OK && typeof res[0] !== 'undefined') {
                        var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
alert(zip);
                        var homecity;
                        var homezip;

                        if((zip[1]>21201)&&(zip[1]<21298)) {
                              //document.getElementById('geo').innerHTML = "Baltimore "+zip[1];
                              homecity = "Baltimore";
                              homezip = zip[1];
                              //$("._res").html(homecity+" "+homezip);
                              window.location.href = "?city="+homecity+"&zip="+homezip;
                        }
                        if((zip[1]>20001)&&(zip[1]<20886)) {
                              //document.getElementById('geo').innerHTML = "Baltimore "+zip[1];
                              homecity = "D.C.";
                              homezip = zip[1];
                              //$("._res").html(homecity+" "+homezip);
                              window.location.href = "?city="+homecity+"&zip="+homezip;
                        }
                        if((zip[1]>19019)&&(zip[1]<19255)) {
                              //document.getElementById('geo').innerHTML = "Baltimore "+zip[1];
                              homecity = "Philadephia";
                              homezip = zip[1];
                              //$("._res").html(homecity+" "+homezip);
                              window.location.href = "?city="+homecity+"&zip="+homezip;
                        }


                    } 
                });
            }, function(err) {
                fail(err.message+" WTF");
            }
        );
    }

【问题讨论】:

  • 您正在使用哪个浏览器?请参阅:thisthat
  • 我在最新的公共 Chrome 上

标签: javascript google-maps geolocation


【解决方案1】:

简单修复,只需将 res 中的 0 改为 1:

            var zip = res[1].formatted_address.match(/,\s\w{2}\s(\d{5})/);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    相关资源
    最近更新 更多