Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

javascript - Can't initiate the google.maps.Geocoder

I don't understand why but i'm getting this error when I try to initialize the 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")
                }
            }
        }
    )
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 $.ajax with dataType: "script" used here), it appears parts of the maps API are not yet available in the success/done callbacks.

$(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).

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.

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 jsFiddle that 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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...