Google Maps API 3 - 地理编码无法正常工作

时间:2013-08-08 14:50:06

标签: php javascript google-maps google-maps-api-3

这是我当前的代码(我觉得问题出在我的codeAddress函数中):

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>`
<script>
    var geocoder;
    var map;
    function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    }

    function codeAddress() {
    var address = document.getElementById("address").text;
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
        } else {
        alert("Geocode was not successful for the following reason: " + status);
        }
    });
    }

    google.maps.event.addDomListener(window, 'load', codeAddress);
    google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas" style="width: 100%; height: 320px;" ></div>
<div id="address">92867</div>

我想要做的是当页面加载时,地址将通过PHP填充。我希望codeAddress与填充的地址一起运行。如何调整此脚本以使用指定地址的正确代码替换此var latlng = new google.maps.LatLng(-34.397, 150.644);

1 个答案:

答案 0 :(得分:3)

  1. 删除
    google.maps.event.addDomListener(window, 'load', codeAddress);
    并添加:
    codeAddress()
    initialize()的末尾,以确保在codeAddress();执行时创建地图

  2. 将该行替换为
    var address = document.getElementById("address").text;
    var address = document.getElementById("address").firstChild.data;
    &lt; div /&gt;
没有文字属性