0

我试图让谷歌地图地理编码器从一个地址返回一个 LatLng,然后用该 LatLng 在中心初始化地图。

我已经看到一些关于这个主题的问题,建议应该首先用任意中心初始化地图,然后再重新设置,但这似乎很浪费。

下面的代码可以正常工作,直到我将全局 lat 和 lon 更改为零。然后使用地址调用 geocder 并返回 LatLng。然后我得到的只是一个空白窗口,并且永远不会触发初始化函数中的警报。

有人可以解释为什么在我走初始化 0,0 然后居中的路线之前这不起作用吗?

谢谢

var lat = 37.425593;
var lon = -122.075915;
var address = '1600 Amphitheatre Pky, Mountain View, CA';
var LatLon = new google.maps.LatLng(0, 0);

function initialize() {

    alert("2. "+LatLon);

    var mapOptions = {
        center: LatLon,
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var marker = new google.maps.Marker({
        position: LatLon,
        map: map
    });

}

if (lat == 0 && lon == 0) {
    alert('address = '+address);
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                LatLon = results[0].geometry.location;
                alert("1. "+LatLon);
                google.maps.event.addDomListener(window, 'load', initialize);
            } else {
                alert("No results found");
            }
        } else {
            alert("Geocoder failed: " + status);
        }
    });
} else {
    alert('lat/lon = '+lat+' '+lon);
    LatLon = new google.maps.LatLng(lat, lon);
    alert("1. "+LatLon);
    google.maps.event.addDomListener(window, 'load', initialize);
}
4

1 回答 1

0

地理编码器是异步的。您还没有将代码放在上下文中,但是返回坐标所需的时间一定意味着窗口加载事件已经触发,当坐标从服务器返回时,因此初始化函数永远不会运行。如果您使用 onload 事件启动地理编码操作,或者如果您直接调用初始化并将代码放在页面底部,则它将起作用,直到页面完全呈现(并且地图具有大小) )。

<script type="text/javascript">
var address = '1600 Amphitheatre Pky, Mountain View, CA';
var LatLon = new google.maps.LatLng(0, 0);

function initialize(LatLon) {
    var mapOptions = {
        center: LatLon,
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var marker = new google.maps.Marker({
        position: LatLon,
        map: map
    });

}

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
               var LatLon = results[0].geometry.location;
               initialize(LatLon);
            } else {
                alert("No results found");
            }
        } else {
            alert("Geocoder failed: " + status);
        }
    });
</script> 
</body>

工作示例

于 2013-09-22T05:01:56.227 回答