2011-07-07 64 views
1

我想每次點擊標記時都要在特定標記上打開infoWindow。但每一次它都停留在原來最後一次的相同位置。這裏是我的代碼Google Maps API v3:InfoWindow不在正確的位置

var infowindow = new google.maps.InfoWindow(
    { 
     size: new google.maps.Size(150,20) 
    }); 
    var markersArray = []; 
    var countMarker = 0; 


    function initialize() {  
     geocoder = new google.maps.Geocoder(); 
     var myLocation = new google.maps.LatLng(52.13206069538749, -106.63635849952698); 
     var mapOptions = { 
      zoom: 12, 
      center: myLocation, 
      mapTypeControl: true, 
      navigationControl: true, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 
     map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions); 
     google.maps.event.addListener(map, 'click', function(event) { 

      addMarker(event.latLng); 
      infowindow.setPosition(marker.getPosition()); 
      infowindow.setContent(event.latLng.toString()); 

      infowindow.open(map,marker); 

      // showing latitude and longitude in infowindow 


      if (flag == 1){ 
       document.getElementById("latbox").value=event.latLng.lat(); 
       document.getElementById("lngbox").value=event.latLng.lng(); 
       flag++; 
      } 
      else{ 
       var current_lat = event.latLng.lat().toString(); 
       var current_lng = event.latLng.lng().toString(); 
       insRow(current_lat, current_lng, marker.id); 
      } 
      google.maps.event.addListener(marker, 'click', function() { 
       // addMarker(event.latLng); 
       // infowindow.setPosition(event.latLng); 
       infowindow.setPosition(marker.getPosition()); 
       infowindow.setContent(event.latLng.toString()); 
       //infowindow.open(map,event.latLng); 
      }); 
     }); 
     //document.write("3"); 
     google.maps.event.trigger(marker, 'click');  
    }  
function addMarker(location) { 
     countMarker++; 
     marker = new google.maps.Marker({ 
      position: location, 
      map: map, 
      id: countMarker 
     }); 
     markersArray.push(marker);    
     //alert(marker.id); 
    } 

誰能幫助我在這方面嗎?

回答

4

試試這個:

  google.maps.event.addListener(marker, "click", function (event) { 
       infoWindow.setContent(this.position); 
       infoWindow.open(map, this); 
       }); 

而且,我也不在你所定義的可變標記的代碼中看到。

你可能想改變addMarker(event.latLng);添加到

var marker = addMarker(event.latLng); 

,改變函數返回的標記對象:

function addMarker(location) { 
    countMarker++; 
    var marker = new google.maps.Marker({ 
       position: location,      
       map: map,      
       id: countMarker     
     }); 

    markersArray.push(marker);       
    return marker; 
} 
+0

太謝謝你了。這工作得很好!但我保留了以下幾行 - 「infowindow.setContent(event.latLng.toString()); infowindow.open(map,marker);' – Pow

相關問題