我想用动态内容填充我的谷歌地图标记的信息窗口。当用户单击标记时,应触发AJAX调用,以从服务器获取相应的内容。
同时应打开infowindow并显示预加载消息。一旦AJAX响应到来,它应该替换预加载消息。
如何使用Google Maps 2 API完成此操作?
(extinfowindow提供了这样的功能,但它是一个外部且已弃用的插件。我更喜欢“纯粹的”Google Maps API方法。
答案 0 :(得分:2)
可能类似以下内容。我不确定事件监听器是如何附加的 - 但如果它在Google Maps v3中有效,它会附加到标记本身,您可以使用'this'-reference来获取点击的标记。
更新了答案。未经测试的代码 - 但它应该工作。将ID设置为infowindow的内容并使用DOM模型进行更新。
function ajax_me() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
this.openInfoWindow('<div id="current-info-window">Loading...</div>');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('current-info-window').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "backend.php", true);
xmlhttp.send();
}
...
marker = new GMarker(...);
GEvent.addListener(marker, 'click', ajax_me);
答案 1 :(得分:0)
我终于通过改进Björn的答案来解决了这个问题。他的方法是在infowindow中使用内容div,并在AJAX响应到达后用document.getElementById()
更新它。这有效,但不会调整infowindow以适应AJAX内容==&gt; “泡沫”溢出。
我的最终解决方案通过在填充AJAX内容时计算内容div的维度来解决这个问题。然后我使用infoWindow.reset() - Method来指定新维度。
这在开始时有点古怪,但最后证明.reset()还需要标记位置来正确渲染调整大小的infowindow。请注意,我正在使用jQuery作为DOM的东西。
marker = new GMarker (...);
GEvent.addListener(marker,'click', loadPOIDescription);
function loadPOIDescription (){
var marker = this;
marker.openInfoWindow('<div id="marker-info">Loading POI Description...</div>');
$.get("backend.php", function(data){
var $contentDiv = $("#marker-info");
$contentDiv.html(data);
//the magic happens here
var position = marker.getLatLng();
var infoWindow = map.getInfoWindow(); //map is my global GMaps2 object
// set the infowindow size to the dimensions of the content div
var infoWindowSize = new GSize($contentDiv.width(), $contentDiv.height());
//apply the modifications
infoWindow.reset(position, null, infoWindowSize, null, null); //reset the infowindow
});
}