非常奇怪的 Javascript 范围问题 [英] Very strange Javascript scoping issue

查看:52
本文介绍了非常奇怪的 Javascript 范围问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下变量 my_cords 在进入谷歌地图功能时未定义,谁能理解为什么并可能给我一个解决方法?我已经在顶部定义了它并将它设置在一个回调函数中,我之前见过它处理全局变量..

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();

});

推荐答案

.geocode 是一个异步调用.

尝试在函数中使用回调.

Try using callbacks in the function.

例如:

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);
}

这篇关于非常奇怪的 Javascript 范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆