无法获得变量值

时间:2014-07-31 14:46:14

标签: javascript google-maps global-variables

我正在处理这个地理位置的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);

1 个答案:

答案 0 :(得分:2)

navigator.geolocation.getCurrentPosition是异步的。传递给它的函数在数据可用之前不会被调用,同时JS的其余部分正常运行。

执行回调函数中的数据,而不是在发送地理位置数据请求后立即执行操作。