Javascript 使用变量外部函数是行不通的
我想在另一个函数中提醒curlat变量,以便在google地图中使用它 特色。但是我不能让它工作Javascript 使用变量外部函数是行不通的,javascript,google-maps,Javascript,Google Maps,我想在另一个函数中提醒curlat变量,以便在google地图中使用它 特色。但是我不能让它工作 var getLocation = { init: function () { var curlat = ""; function onSuccess(position) { curLat = position.coords.latitude; }; function onError(error
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
。您需要编辑该代码并正确设置其格式。现在完全看不懂。你可能必须读一下:我不确定这会有多大帮助getCurrentPosition
是异步的,因此它取决于何时调用map.init()
。这一点很好。在手机概览中没有提到这一点。更新了一点答案。再次在桌面上时将再次检查。