0

我在做什麼錯?我基本上試圖彈出一個信息窗口,一個非常簡單的,點擊標記..標記顯示正常,但標記點擊事件沒有被回覆..我很確定InfoWindow代碼不在正確的位置。對於correspoding標記的地址被送入的jQuery每個..無法彈出InfoWindow單擊標記谷歌地圖

var geocoder; 
var map;  
geocoder = new google.maps.Geocoder(); 
var latlng = new google.maps.LatLng(39.88445,-86.11084); 
var myOptions = { 
    zoom: 10, 
    center: latlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
}; 
map = new google.maps.Map(document.getElementById("map_canvas"), 
    myOptions); 


$('span.Address .ms-rtestate-field').each(function(index) { 
    var addy = $(this).text(); 
    geocoder.geocode({ 'address': addy}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      map.setCenter(results[0].geometry.location); 
      var marker = new google.maps.Marker({ 
      map: map, 
      position: results[0].geometry.location, 
      title:addy 
     }); 
     }else { 
      alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 


    // Creating an InfoWindow   
    var infowindow = new google.maps.InfoWindow({ 
    content: 'Hello world' 
    }); 

    // Adding a click event to the marker 
    google.maps.event.addListener(marker, 'click', function() { 
    return function(){ 
    // Opening the InfoWindow 
    infowindow.open(map, marker); 
    } 
    }); 

}); 

回答

1

你只需要在信息窗口的一個實例,然後更改使用setContent()方法onclick事件中的內容。此外,您應該將事件處理程序放入地理編碼回調函數中,以確保在地理編碼器完成時它已連接。

試試這個:

// Creating an InfoWindow   
var infowindow = new google.maps.InfoWindow({}); 

$('span.Address .ms-rtestate-field').each(function(index) { 
    var addy = $(this).text(); 
    geocoder.geocode({ 'address': addy}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      map.setCenter(results[0].geometry.location); 

      var marker = new google.maps.Marker({ 
       map: map, 
       position: results[0].geometry.location, 
       title:addy 
      }); 

      // Adding a click event to the marker 
      google.maps.event.addListener(marker, 'click', function() { 
       infowindow.setContent("Hello World!"); 
       infowindow.open(map, this); 
      }); 

     }else { 
      alert("Geocode was not successful for the following reason: " 
        + status); 
     } 
    }); 

}); 
+0

太謝謝你了。這做到了!我是jQuery和Google Map API的新手。你是我今天的英雄! :) – AJSwift

+0

因爲我是初學者,總是對'this'這個關鍵字感到困惑,你能解釋一下'this'的用法嗎?當前剛剛有onclick事件的標記對象?此外,爲了讓我的腳不僅僅是溼的,我現在想將窗口的內容設置爲標記地址,並且還將「get Direction」鏈接指向google.com地圖頁面? – AJSwift

+0

「this」關鍵字是指當前範圍內的對象,在本例中它是循環中的當前標記,因爲您將偵聽器附加到該標記上,也可以像這樣編寫代碼並仍然有效:'infowindow.open(map ,marker);'這裏更好地解釋'this':http://www.quirksmode.org/js/this.html –