【问题标题】:Google Maps V3 InfoWindow ignores latLng positionGoogle Maps V3 InfoWindow 忽略 latLng 位置
【发布时间】:2013-11-08 18:33:55
【问题描述】:

我的地图没有标记。在地图上单击时,它会弹出一个信息窗口,其中纬度/经度以十进制显示为 5 dp,以度分秒为单位。打开的窗口总是在响应新的点击之前关闭。位置由 position: latLng 指定,但信息窗口始终位于左上角。我已经花了几天的时间,我觉得我错过了一些东西。下面是代码 sn-p。有什么想法吗?

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; 
    });    
});

【问题讨论】:

  • 删除第二个参数效果很好。非常感谢莫勒博士。

标签: google-maps google-maps-api-3 infowindow


【解决方案1】:

这段代码有几个问题。 infowindow 的open 方法的第二个参数必须是核心API 中的MVCObject,只有Marker 类可以用作锚点。您不需要每次都将 infowindow 变量设置为 null 并创建一个新的 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);
}

【讨论】:

  • Bryan - 一个非常有用的建议,我将从中学习。我也会调整我的代码。
【解决方案2】:

infoWindow.open() 的第二个(可选)参数应该是公开位置属性的 MVCObject

回调中的this 参数引用google.maps.Map-Instance(map),它是一个MVCObject,但没有position-属性。

infoWindow.open(map,this); 中删除第二个参数。

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 2012-01-06
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2012-09-06
    相关资源
    最近更新 更多