Google Maps V3 InfoWindow会忽略latLng位置

Rob*_*cas 4 google-maps infowindow google-maps-api-3

我的地图没有标记.为了响应地图上的点击,它会弹出一个带有Lat/long的信息窗口,显示为十进制到5 dp和以度为单位的秒数.在响应新的点击之前,打开的窗口始终处于关闭状态.位置由position:latLng指定,但infowindow始终位于左上角.我花了好几天时间,我觉得我错过了什么.下面的代码片段.有任何想法吗?

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; 
    });    
});
Run Code Online (Sandbox Code Playgroud)

Bry*_*ver 5

您有这个代码的几个问题.infowindow open方法的第二个参数必须是MVCObject Core API中的一个,只有Marker该类可以用作锚.您不需要将infowindow变量设置为null并且每次都创建一个新的infowindow对象.您只需要一个infowindow然后更改其内容和位置.这样,一次只显示一个信息窗口.

这是一个工作示例的小提琴: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);
}
Run Code Online (Sandbox Code Playgroud)