2010-06-22 59 views
2

我想用動態內容填充我的谷歌地圖標記的infowindow。當用戶點擊一個標記時,應該觸發一個AJAX調用,從服務器獲取相應的內容。如何使用AJAX內容填充Google Maps Infowindow?

同時應該打開infowindow並顯示預加載消息。一旦AJAX響應到達,它應該替換預加載消息。

我該如何使用Google Maps 2 API來完成此操作?

extinfowindow提供了這樣的功能,但它是一個外部和不贊成使用的附加組件,我更喜歡「純粹的」Google Maps API方法)。

+0

嗯僅僅指剛的想法,不知道它的工作原理 ......如果你能夠click事件綁定到標記(這是可能的,我認爲),你可以告訴JS這標誌這是。 刪除標記。做ajax請求並創建一個新的,在相同的位置,相同的處理,並給出相應的ajax結果。 – helle 2010-06-22 14:29:20

+0

更新了我的回答 – 2010-06-22 15:49:05

+0

@Björn:不錯的努力,但infoWindow維度不適應注入DOM的內容==>大部分內容都在泡泡之外呈現。嗯...也許我使用滾動條 – fbuchinger 2010-06-22 16:25:03

回答

0

我終於通過細化Björn的回答來解決了這個問題。他的做法是在infowindow中使用content div,並在AJAX響應到達時用document.getElementById()進行更新。這可以工作,但不會調整infowindow以適應AJAX內容==>「泡泡」溢出。

我的最終解決方案是通過計算內容div的大小來解決這個問題,然後我使用infoWindow.reset() - 方法來指定新維度。

這在開始時有點古怪,但最後發現.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 
    }); 
} 
2

也許像下面這樣。我不確定事件監聽器是如何附加的 - 但是如果它在Google Maps v3中正常工作,它會附加到標記本身,您可以使用「this」引用來獲取點擊標記。

已更新的答案。未經測試的代碼 - 但它應該工作。將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); 
+0

抱歉,這不是我問題的主要部分。使用標記ID觸發AJAX請求很容易,真正的困難是將ajax響應填充到infowindow中,並在響應到達之前在infowindow中顯示加載消息。 – fbuchinger 2010-06-22 15:07:53

相關問題