代码之家  ›  专栏  ›  技术社区  ›  fbuchinger

如何用AJAX内容填充Google地图信息窗口?

  •  2
  • fbuchinger  · 技术社区  · 16 年前

    我想用动态内容填充google地图标记的infowindow。当用户单击一个标记时,应该触发一个AJAX调用,从服务器获取相应的内容。

    如何使用googlemaps2api实现这一点?

    ( extinfowindow 提供了这样的功能,但它是一个外部的、不推荐使用的附加组件。我更喜欢“纯”的googlemapsapi方法)。

    2 回复  |  直到 16 年前
        1
  •  2
  •   Björn    16 年前

    也许像下面这样。我不确定事件侦听器是如何连接的,但是如果它像googlemapsv3那样工作,它就连接到标记本身,您可以使用“this”引用来访问单击的标记。

    更新的答案。未经测试的代码-但它应该可以工作。为infowindow的内容设置一个ID,并使用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);
    
        2
  •  0
  •   fbuchinger    16 年前

    document.getElementById() 一旦AJAX响应到达。这是可行的,但不会调整infowindow的大小以适应AJAX内容==>“泡沫”溢出了。

    这在一开始有点奇怪,但最后发现.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
       });
    }
    
    推荐文章