在函数外使用变量是行不通的

using variable outside function wont work

本文关键字:行不通 变量 函数      更新时间:2023-09-26

我想在其他函数中提醒curlat变量,以便我可以在Google地图中使用它特性。但是我不能让它工作。

var getLocation = {
    init: function () {
        var curlat = "";
        function onSuccess(position) {
            curLat = position.coords.latitude;
        };   
        function onError(error) {
            alert('code: ' + error.code + ''n' + 'message: ' + error.message + ''n');
        }
        navigator.geolocation.getCurrentPosition(onSuccess, onError);
    }
}
var map = {
    init: function () {
        alert(curLat); // alert the cordinate here
        //Google maps API initialisation
        var element = document.getElementById("map");
        //Define the properties of the OSM map to be displayed 
        var map = new google.maps.Map(element, {
            center: new google.maps.LatLng(57, 21),
            zoom: 11,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            mapTypeControl: false,
            streetViewControl: false
        });
        //Define OSM map type pointing at the OpenStreetMap tile server         
        map.mapTypes.set("OSM", new google.maps.ImageMapType({
            getTileUrl: function (coord, zoom) {
                return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
            },
            tileSize: new google.maps.Size(256, 256),
            name: "OpenStreetMap",
            maxZoom: 18
        }));
    }
}

首先,javascript是区分大小写的,所以curlat应该是curLat

第二,将变量放到函数之外:
var curLat = "" ;
var getLocation = {       ...

同样,正如其他人正确指出的那样。您应该延迟map的初始化,直到curLat被设置。也许您可以从success处理程序调用.map.init