由于ZERO_RESULTS,Geocoder失败了

时间:2017-05-03 08:20:42

标签: javascript google-maps geocoding

我是javascript的新手并且一直停留在地理编码,我正在尝试获取当前位置并使用地理编码获取其placeid,如果我将数字传递给lat lang它可以正常工作,否则它会因为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">

1 个答案:

答案 0 :(得分:4)

首先,代码中有一些混乱,但我会尝试提供帮助。

navigator.geolocation.getCurrentPosition是一个异步函数,在创建另一个地理编码请求之前,必须等待此函数结束。

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

geocoder.geocode({
    'location' : latlng
}

应位于getCurrentPosition回调中。

另外看一下reverseGeocoding API:

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