javascript 无法启动 google.maps.Geocoder

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6398342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:32:20  来源:igfitidea点击:

Can't initiate the google.maps.Geocoder

javascriptgoogle-mapsundefined

提问by iva123

I don't understand why but i'm getting this error when I try to initialize the google.maps.Geocoder.

我不明白为什么,但是当我尝试初始化 google.maps.Geocoder 时出现此错误。

Here is the error:

这是错误:

Uncaught TypeError: undefined is not a function

And the code :

和代码:

function updateMapPosition(map){
    var geocoder = new google.maps.Geocoder(); //crashes here !!
    var position = geocoder.geocode( {'address':$('#id_address').val()},
        function(results,status){
            if(status == google.maps.GeocoderStatus.OK){
                if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                    map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({map:map, position:results[0].geometry.location});
                }
                else{
                    alert("hop")
                }
            }
        }
    )
}

回答by patridge

Since you appear to be using something like jQuery, you may have the same issue I had where jQuery considers the script loading complete before Google Maps is actually completely "assembled". Using jQuery's $.getScript(equivalent to $.ajaxwith dataType: "script"used here), it appears parts of the maps API are not yet available in the success/donecallbacks.

由于您似乎在使用 jQuery 之类的东西,因此您可能遇到了与我在 Google 地图实际上完全“组装”之前 jQuery 认为脚本加载已完成的问题相同的问题。使用jQuery的$.getScript(相当于$.ajaxdataType: "script"这里使用),它出现的地图API部分尚未公布在success/done回调。

$(function() {
    var doSomethingMapRelatedInvolvingJQuery = function(geocoder, map) { ... };

    $.ajax({
        url: "https://maps.googleapis.com/maps/api/js?v=3&sensor=false",
        dataType: "script"
    }).done(function() {
        var geocoder = new google.maps.Geocoder(), // ERROR!
            activityMap = new google.maps.Map($("#map_canvas")[0], {
                center: new google.maps.LatLng(0, 0),
                zoom: 0,
                mapTypeId: google.maps.MapTypeId.SATELLITE
            });

        doSomethingMapRelatedInvolvingJQuery(geocoder, map);
    });
});

For some reason, even though jQuery is saying the script has been executed already by executing the callbacks, parts of the Google Maps API are not yet available (possibly additional asynchronous stuff by Google after the first file executes).

出于某种原因,即使 jQuery 说已经通过执行回调执行了脚本,但部分 Google Maps API 尚不可用(可能是 Google 在第一个文件执行后提供的其他异步内容)。

The only solution I could find was to declare a global variable name to hold a function that Google Maps would be responsible for calling when it was completely ready. You can give it that control by adding the callback={yourfunctionname}querystring parameter to the URL (e.g., https://maps.googleapis.com/maps/api/js?v=3&callback=googleMapsCallback&sensor=false). It's not the prettiest solution, but it works.

我能找到的唯一解决方案是声明一个全局变量名来保存一个函数,当它完全准备好时,谷歌地图将负责调用。您可以通过将callback={yourfunctionname}查询字符串参数添加到 URL(例如,https://maps.googleapis.com/maps/api/js?v=3&callback=googleMapsCallback&sensor=false)来赋予它控制权。这不是最漂亮的解决方案,但它有效。

var googleMapsCallback;
$(function() {
    var doSomethingMapRelatedInvolvingJQuery= function(geocoder, map) { ... };

    googleMapsCallback = function() {
        var geocoder = new google.maps.Geocoder(), // Works when google makes the call.
            activityMap = new google.maps.Map($("#map_canvas")[0], {
                center: new google.maps.LatLng(0, 0),
                zoom: 0,
                mapTypeId: google.maps.MapTypeId.SATELLITE
            });

        doSomethingMapRelatedInvolvingJQuery(geocoder, map);
    };
    $.ajax({
        url: "https://maps.googleapis.com/maps/api/js?v=3&callback=googleMapsCallback&sensor=false",
        dataType: "script"
    });
});

EDIT:

编辑:

I put together a proof-of-concept jsFiddlethat pulls all that ugliness into a jQuery-extended method that allows for Deferred-chaining. Here's a quick example of how it can be used:

我整理了一个概念验证 jsFiddle,它将所有这些丑陋的东西整合到一个 jQuery 扩展的方法中,该方法允许延迟链接。这是一个如何使用它的快速示例:

$.loadGoogleMaps().done(function () {
    var geocoder = new google.maps.Geocoder();
    // ... do stuff with your geocoder here ...
});

回答by Juan Boyce

If you use the Google AJAX API Loader to load the Google Maps API you must explicitly specify whether your app uses a sensor, otherwise you won't get the Geocoder object.

如果您使用 Google AJAX API Loader 加载 Google Maps API,您必须明确指定您的应用程序是否使用传感器,否则您将无法获得 Geocoder 对象。

google.load('maps','3.6',{other_params:'sensor=false'});

回答by Kyle

Looks to me like Geocoderisn't defined, hence the error that Undefined is not a function. However, google.mapsis defined or you would have gotten an error that it wasn't defined before Geocoderwas resolved.

在我看来Geocoder没有定义,因此错误是Undefined is not a function. 但是,google.maps已定义,否则您会收到一个错误,说明它在Geocoder解决之前未定义。

You'll need to check how you're loading the Map API because it doesn't seem to have been loaded correctly.

您需要检查您是如何加载 Map API 的,因为它似乎没有正确加载。

回答by okeen

I solved my problem, it was because of a bad href url in the script tag for the Maps library:

我解决了我的问题,这是因为 Maps 库的脚本标记中的 href url 错误:

<script src="http://maps.google.com/maps/api/js?v=3.6&sensor=false&key=XXXX" ....