首页 > 解决方案 > ReferenceError:谷歌未定义/地理编码API

问题描述

我试图创建地理编码功能(地理编码API),它不断返回google is not defined,我已经根据这个答案更改了链接,但它没有用:(它在geocoder = new google.maps.Geocoder();

JS:

geocoder = new google.maps.Geocoder();

function address() {
    //In this case it gets the address from an element on the page, but obviously you  could just pass it to the method instead
    for (i = 0; i < index.length; i++) {
        var address = index[i].Origin;
        console.log(address)
        geocoder.geocode({
            'address': address
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }
}

关联:

<script src="https://maps.google.com/maps/api/js?key=AIzaSyCNpeRgwCQoHIlLn-X8TIB9SnO8iLPt808&callback=initMap"
async defer></script>

抱歉,如果问题重复,我几乎尝试了所有东西(也在堆栈之外),是的,没有任何变化。

标签: javascriptjsongoogle-maps-api-3geocodinggoogle-geocoding-api

解决方案


将任何依赖于 API 的代码(以 开头google.maps.)放在initMap函数中或同步加载 API(从脚本 URL中删除async defer和)&callback=initMap


推荐阅读