开发者

Google maps API works when I break then continue, doesn't otherwise

开发者 https://www.devze.com 2023-04-04 06:15 出处:网络
This code works when I break any time after pos is defined, then continue. But when I run it normally it doesn\'t display anything.What am I doing wrong?

This code works when I break any time after pos is defined, then continue. But when I run it normally it doesn't display anything. What am I doing wrong?

function initialize() {

    var pos;

    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {

            pos = new google.maps.LatLng(position.coords.latitude,
                                             position.coords.longitude);
        }, function() {
               handleNoGeolocation(true);
           });
    }
    else { // Browser doesn't support geolocation
        handleNoGeolocation(false);
    }

    var myOptions = {
        zoom: 7,
        center: pos,
        开发者_StackOverflowmapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"), 
                                      myOptions);

}


getCurrentPosition(f, ...) is asynchronous, meaning that the callback f is called later after successful completion of the request. But at this time the local variable pos in the function initialize() is no longer in scope.

You can solve the problem by defining pos in the global window scope. This should work and pos will get assigned by the callback. However, you do not know when this assignment happens. The best way to handle this problem, is to do something with pos directly in the callback, e.g. write it into a text field or store it in the database, etc.


Interesting. Are you getting errors? Can you share? You might also want to use console.log() for debugging and wrap try/catch blocks around that. I think you might have some issues in some of the older browsers.


Maybe the API call takes a little bit of time and when it breaks it gets that little bit of time to retrieve whatever data it needs, so it is able to display it? This is merely speculation but you could try putting a delay in there to see what happens.

0

精彩评论

暂无评论...
验证码 换一张
取 消