我正在编写用于地理定位的javascript代码。我不明白为什么它不拾取全局声明的变量的值。
我如何正确传递"lat和"lng"变量?我错过了什么?
var lat; //Works if I set value manually
var lng;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showPosition(position) {
lat = position.coords.latitude; //Doesn't pick up this value
lng = position.coords.longitude; //Doesn't pick up this value
document.getElementById('demo').innerHTML = lat; //Value is correct
document.getElementById('demo2').innerHTML = lng; //Value is correct
}
var map;
var marker;
var myLatlng = new google.maps.LatLng(lat,lng); //Works if I add value manually
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize(){
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("myMapSearch"), mapOptions);
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({'latLng': myLatlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
navigator.geolocation.getCurrentPosition
是异步的。在数据可用之前,你传递给它的函数不会被调用,与此同时JS的其余部分正常运行。
处理回调函数中的数据,而不是在发送地理定位数据请求后立即处理。