Google 地图地理编码:"google is not defined"

Google Maps geocoding : "google is not defined"

我在尝试加载此代码时遇到问题,我不明白为什么它不起作用...

<script type="text/javascript">
    $(document).ready(function()
    {
        var geocoder = new google.maps.Geocoder();
        $(".textarea-autosize").autosize();

        geocoder.geocode({
            address: '{$order->address_delivery["address1"]},{$order->address_delivery["postecode"]},{$order->address_delivery["city"]}'
            }, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK)
            {
                var delivery_map = new google.maps.Map(document.getElementById('map-canvas'), {
                    zoom: 10,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    center: results[0].geometry.location
                });
                var delivery_marker = new google.maps.Marker({
                    map: delivery_map,
                    position: results[0].geometry.location,
                    url: 'http://maps.google.com?q={$order->address_delivery["address1"]},{$order->address_delivery["postcode"]},{$order->address_delivery["city"]}'
                });
                google.maps.event.addListener(delivery_marker, 'click', function() {
                    window.open(delivery_marker.url);
                });
            }
        });
    });

    // Fix wrong maps center when map is hidden
    $('#tabAddresses').click(function(){
        x = delivery_map.getZoom();
        c = delivery_map.getCenter();
        google.maps.event.trigger(delivery_map, 'resize');
        delivery_map.setZoom(x);
        delivery_map.setCenter(c);

    });
</script>

错误发生在var geocoder = new google.maps.Geocoder();

然后我尝试加载以下脚本:<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

我收到另一个错误:

'Uncaught TypeError: Cannot read property 'offsetWidth' of null'

有没有人知道为什么它不起作用?

Google 地图在您尝试调用时未加载。你应该使用这个:

HTML:

<script src="https://maps.googleapis.com/maps/api/js?sensor=false&callback=initMap" async defer></script>

JS:

function initMap() {
    // Google maps are now initialized.
}

您需要将 async and defer 属性包含到您的脚本中 - 这将确保网站的其余部分继续加载而不是等待脚本加载(这很方便,因为它很大) . 其次,调用脚本时传递 "callback" 参数。这是加载脚本时应执行的函数的名称。通过这种方式,您可以确保仅在地图实际加载并出现在 window.

中时才初始化地图

只需将此脚本添加到您的 html 文件中:

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

如果您想测试 google 地理编码 api 或查看一些代码,请查看此 link。 Google Geocoding Service API Source