我是 JavaScript 新手,我试图制作一个简单的 GoogleMaps
,它以我当前的位置为中心,但我发现在保存纬度和经度以将 map 居中时出现问题。
这是我采用的代码:
function initialize() {
var latitudeCenter;
var longitudeCenter;
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(position){
console.log(position.coords.latitude, position.coords.longitude);
latitudeCenter = position.coords.latitude;
longitudeCenter = position.coords.longitude;
}
function onError(error){
alert('Error en GPS: ' + error);
}
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latitudeCenter, longitudeCenter)
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
console.log('latitud: ' + latitudeCenter + ' longitud: ' + longitudeCenter);
}
在第一个控制台日志中,我可以读取当前位置和纬度,因此该方法工作正常,但是当我尝试将其保存在 centerLatitude 和 centerLongitude 中时,它不起作用,它显示未定义。
感谢您的帮助
最佳答案
因此,函数 onSuccess
和 onError
是异步的,因此您不会立即得到答案。因此,您将实际的 map 初始化代码放入 onSuccess
function initialize() {
var latitudeCenter;
var longitudeCenter;
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(position){
console.log(position.coords.latitude, position.coords.longitude);
latitudeCenter = position.coords.latitude;
longitudeCenter = position.coords.longitude;
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latitudeCenter, longitudeCenter)
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
}
function onError(error){
alert('Error en GPS: ' + error);
}
console.log('latitud: ' + latitudeCenter + ' longitud: ' + longitudeCenter);
}
关于javascript - 如何在javascript中的函数之外保存变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26022727/