geocoder.geocode函数不起作用

时间:2014-07-26 22:01:40

标签: javascript jquery google-maps

您好我想对用户输入的位置进行地理编码。

但似乎geocoder.geocode函数不起作用

这是JavaScript的一部分

$('#inputButtonGeocode').click(function () {
var sAddress = document.getElementById('inputTextAddress').value;
geocoder.geocode({
    'address': sAddress
}, 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);
    }
});

这应该是一个简单的问题,但我找不到问题

他是JSFiddle链接http://jsfiddle.net/x69chen/u2gP3/7/

请有人帮助我,谢谢你

2 个答案:

答案 0 :(得分:2)

嗯,有一些事情。它看起来并不像您的初始化函数一直在运行,因此您的地理编码器对象永远不会被创建。此API也与google maps embed(iframe)API不兼容。   您可以在this示例中看到他们正在创建地理编码器,然后使用以下内容创建地图以创建地图:

map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

他们将地图分配给名为map的变量。然后他们使用该变量传递给标记的创建,以便将该标记放在右侧地图上。

var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });

另外不要忘记加载实际的谷歌地图API。 jquery插件使您能够处理地图中的事件,但它实际上并没有加载api。 Here是异步加载API的示例。你也可以像任何其他脚本一样加载它,简单易用,见here

答案 1 :(得分:0)

您必须引用正确的window对象。您的JavaScript与iframe位于不同的页面上。您可以使用var theWindow = frames[number].contentWindow || frames[number].contentDocument;。当然,您需要CORS访问权限。我不会使用iframe。此外,我没有看到您的initialize()函数被调用。 new google.maps.Map();在其他地方吗?您可以使用Google Maps API将地图直接加载到您选择的元素中,而无需使用iframe。您必须使用Map创建new google.maps.Map()对象的底线。它看起来像:

var g = google.maps;
var map = new g.Map($('#map'), {zoom:8, center:new g.LatLng(43.472285,-80.544858)});

当然,您可以向MapOpitons对象添加和更改属性。只有在制作地图后,您才有权创建new g.Marker()。注意:我将google.maps缩短为g以避免重复输入。