【问题标题】:Geocoder failed due to ZERO_RESULTS由于 ZERO_RESULTS,地理编码器失败
【发布时间】:2017-05-03 08:20:42
【问题描述】:

我是 javascript 新手,一直停留在地理编码上,我正在尝试获取当前位置并使用地理编码获取其 placeid,如果我将数字传递给纬度,它可以正常工作,否则它会发出警报地理编码器由于 ZERO_RESULTS 失败,下面的代码运行良好

var currentLatitude= 23.2147721;
var currentLongitude =72.6446714;
    function initialize() {
        var geocoder = new google.maps.Geocoder;

        var latlng = {
            lat : currentLatitude,
            lng : currentLongitude

        };
        console.log("Geocoder" + latlng);
        geocoder.geocode({
            'location' : latlng
        }, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    console.log(results[1].place_id);
                } else {
                    window.alert('No results found');
                }
            } else {
                window.alert('Geocoder failed due to: ' + status);
                q
            }
        });
    };

下面的代码显示错误。

var currentLatitude,currentLongitude; 
 if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position){
        currentLatitude = parseFloat(position.coords.latitude);
        currentLongitude = parseFloat(position.coords.longitude);

            console.log("Latitude:"+currentLatitude+"Longitude:"+currentLongitude);

        });
    } else { 
        console.log("Geolocation is not supported by this browser.");
    }

function initialize() {
        var geocoder = new google.maps.Geocoder;

        var latlng = {
            lat : currentLatitude,
            lng :currentLongitude

        };
        console.log("Geocoder" + latlng);
        geocoder.geocode({
            'location' : latlng
        }, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    console.log(results[1].place_id);
                } else {
                    window.alert('No results found');
                }
            } else {
                window.alert('Geocoder failed due to: ' + status);

            }
        });
    };

我使用的src是

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOURKEYHERE&callback=initialize">

【问题讨论】:

  • 任何帮助表示赞赏

标签: javascript google-maps geocoding


【解决方案1】:

首先,您的代码有问题,不过我会尽力提供帮助。

navigator.geolocation.getCurrentPosition 是一个异步函数,您必须等待该函数结束才能创建另一个地理编码请求。

页面加载后谁负责调用初始化函数?我很确定这部分:

geocoder.geocode({
    'location' : latlng
}

应该在getCurrentPosition 回调中。

另外看看reverseGeocoding API:

https://developers.google.com/maps/documentation/javascript/geocoding#ReverseGeocoding

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2012-09-15
    • 2018-01-29
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多