谷歌地图V3信息窗口忽略latLng位置

4

我的地图没有标记。在点击地图后,它会弹出一个信息窗口,显示十进制小数点后5位和度分秒的经纬度。在响应新的点击之前,始终关闭打开的窗口。位置由position: latLng指定,但是信息窗口总是在左上角。我花了几天时间研究这个问题,感觉我漏掉了什么东西。下面是代码片段。有任何想法吗?

google.maps.event.addListener(map, 'click', function (event) {
    var lat = event.latLng.lat(),
        lng = event.latLng.lng(),
        latLng = event.latLng,
        strHtml;
    //
    // strHtml build code omitted but succesfully uses lat and lng to produce
    // e.g. Latitude : 51.72229 N (51° 43' 20'' N)
    //      Longitude : 1.45827 E (1° 27' 30'' E)
    //
    // If an infowindow is open, then close it
    if (openedInfoWindow != null) openedInfoWindow.close();
    // latLng monitored to check it is there before use in infowindow
    alert(latLng); // returns correct values which position then ignores!
    var infoWindow = new google.maps.InfoWindow({
        position: latLng, 
        content: strHtml,
        maxWidth: 420
    });
    // Open infoWindow
    infoWindow.open(map,this);
    // Remember the opened window
    openedInfoWindow = infoWindow;
    // Close it if X box clicked
    google.maps.event.addListener(infoWindow, 'closeclick', function() {
    openedInfoWindow = null; 
    });    
});

去掉第二个参数完美地解决了问题。非常感谢Molle博士。 - Robin Lucas
2个回答

5
您的代码存在几个问题。infowindow的open方法的第二个参数必须是一个MVCObject,而在Core API中只有Marker类可以用作锚点。您不需要每次将infowindow变量设置为null并创建新的infowindow对象。您只需要一个infowindow,然后更改其内容和位置。这样一次只会显示一个infowindow。
下面是一个工作示例的fiddle链接:http://jsfiddle.net/bryan_weaver/z3Cdg/ 相关代码:
google.maps.event.addListener(map, 'click', function (evt) {
       var content = "<div class='infowindow'>";
       content += "Latitude: " + evt.latLng.lat() + "<br/>";
       content += "Longitude: " + evt.latLng.lng() + "</div>";
       HandleInfoWindow(evt.latLng, content);
});

function HandleInfoWindow(latLng, content) {
    infoWindow.setContent(content);
    infoWindow.setPosition(latLng);
    infoWindow.open(map);
}

Bryan - 这是一个非常有用的建议,我会学习并调整我的代码。 - Robin Lucas

4
< p > infoWindow.open()方法的第二个(可选)参数应该是一个暴露出position属性的MVCObject对象。 < /p> < p > 回调函数中的this参数指向一个google.maps.Map实例(即map),它是一个MVCObject对象,但没有position属性。 < /p> < p > 从infoWindow.open(map,this);语句中删除第二个参数。 < /p>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接