由于 ZERO_RESULTS,地理编码器失败

Geocoder failed due to ZERO_RESULTS

我是 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">

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

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

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

geocoder.geocode({
    'location' : latlng
}

应该在 getCurrentPosition 回调中。

另外看看reverseGeocoding API :

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