Very strange Javascript scoping issue

北慕城南 提交于 2019-12-11 14:56:02

问题


The following variable my_cords is undefined when it gets to the google maps function, can anyone understand why and possible give me a work around? I have defined it right at the top and set it inside a callback function, which I have seen work on global variables before..

$(document).ready(function () {

var my_cords;
var map;

function getCareHome() {

    geocoder = new google.maps.Geocoder();

    //var address = document.getElementById("address").value;

    var address = "address here";

    geocoder.geocode( { 'address': address}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

            my_cords = results[0].geometry.location;

        } else {

            alert("Sorry we couldn't locate the carehome on the map: " + status);
            return false;

        }

    });



    var myOptions = {
        zoom: 7,
        center: my_cords,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

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

}

getCareHome();

});

回答1:


.geocode is an asynchronous call.

Try using callbacks in the function.

For example:

geocoder.geocode( { 'address': address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

        createMap(results[0].geometry.location);

    } else {

        alert("Sorry we couldn't locate the carehome on the map: " + status);
        return false;

    }

});

var createMap = function(my_cords)  {
     var myOptions = {
        zoom: 7,
        center: my_cords,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

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



回答2:


geocoder.geocode is an asynchronous function. The anonymous function that sets my_cords won't run until some event (probably the arrival of an HTTP response) fires.

Move the code that depends on it running to inside that function.




回答3:


Because geocode runs asynchronously, your code using my_cords later (setting up myOptions) will see the value of my_cords before the completion callback from geocode runs — and so myOptions.center will be undefined.

If you need my_cords when setting up the myOptions, you'll have to move that code into the callback on geocode.



来源:https://stackoverflow.com/questions/11035855/very-strange-javascript-scoping-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!