javascript - Google map 地理编码无法正常工作(无标记)

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

我有一个网页可以查找纬度、经度并获取该位置的标记。我使用谷歌地图。

我的网页从用户输入中获取2个地址,地址1和地址2,并调用codeAddress()

<div id="panel">
  <input id="address1" type="textbox" value="">
  <input id="address2" type="textbox" value="">
  <input type="button" value="find!" onclick="codeAddress()">
</div>

这是我的 JavaScript 代码:

var map;
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;

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

function codeAddress() {
    var gc = google.maps.Geocoder();
    gc.geocode({
        'address': address1
    }, function (res1, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            gc.geocode({
                'address': address2
            }, function (res2, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    new google.maps.Marker({
                        position: res1[0].geometry.location,
                        map: map
                    });
                    new google.maps.Marker({
                        position: res2[0].geometry.location,
                        map: map
                    });
                }
            });
        }
    });
}

当我点击查找按钮时,我没有得到标记。有谁可以帮助我吗?

最佳答案

修改 codeAddress 函数,如下所示:

function codeAddress() {
    var gc = new google.maps.Geocoder(); // notice new keyword
    initialize(); // Calling initialize. If you skip it, maps aren't loading
    gc.geocode({
        'address': address1
    }, function(res1, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            gc.geocode({
                'address': address2
            }, function(res2, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    new google.maps.Marker({
                        position: res1[0].geometry.location,
                        map: map
                    });
                    new google.maps.Marker({
                        position: res2[0].geometry.location,
                        map: map
                    });
                }
            });
        }
    });

确保两个输入都有一些测试值。

演示:http://jsfiddle.net/lotusgodkk/GCu2D/213/

关于javascript - Google map 地理编码无法正常工作(无标记),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473872/

相关文章:

javascript - 如果 infoWindowContent 中的字段为空,则 Google map 标记不会显示

google-maps - map 初始化后是否可以更改 Google map 样式?

javascript 多重过滤器或条件代码优化

javascript - 将两个或多个数据绑定(bind)到 VueJ 中的表单输入

html - iframe 谷歌地图不会在 chrome 中打印

r - 海洋纬度经度点距海岸的距离

javascript - 当选中其他行中的选项时禁用同级按钮

javascript - JS string.split() 不删除分隔符

javascript - 选择 JavaScript 数组中的最后一个元素

javascript - 一页上的多个 map - ColdFusion