2010-10-19 116 views

回答

0

你必須保持你添加到地圖中的數組標記的軌道。您需要添加一個bounds_changed事件偵聽器,並使用一個函數來搜索該數組,並檢查標記座標是否位於地圖邊界內。例如:

<html> 
    <head> 
     <script type="text/javascript" src= "http://maps.google.com/maps/api/js?sensor=false"> 
     </script> 
     <script> 

      var map; 
      markers = []; 
      function initialize(){ 
       geocoder = new google.maps.Geocoder(); 
       var latlng = new google.maps.LatLng(-34.397, 150.644); 
       var myOptions = { 
        zoom: 8, 
        center: latlng, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
       } 
       map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

       //if creating multiple markers you would do marker creation and storage in a loop 
       var marker1 = new google.maps.Marker({ 
        map: map, 
        position: latlng, 
        title: "Marker 1" 
       }); 
       var marker2 = new google.maps.Marker({ 
        map: map, 
        position: new google.maps.LatLng(-34.2, 150.644), 
        title: "Marker 2" 
       }); 
       //save your marker to an array to keep track of your markers - i am assuming all markers are initially visible 
       markers.push({ 
        visible: true, 
        marker: marker1 
       }) 
       markers.push({ 
        visible: true, 
        marker: marker2 
       }) 

       //watch for zoom change event 
       google.maps.event.addListener(map, 'bounds_changed', function(){ 
        checkBounds() 

       }) 

      } 

      function checkBounds(){ 

       //get bounds for a new zoom level 
       bounds = map.getBounds(); 
       //loop through markers array to check if they are still in bounds (visible) 
       for (i = 0; i < markers.length; i++) { 
        m = markers[i].marker 
        if (bounds.contains(m.position)) { 
         //do something here for markers that are visible 
         markers[i].visible = true; 
        } 
        else { 
         //do something here for markers that are not visible 
         markers[i].visible = false; 
        } 
       } 
      } 

      //this is just to show which markers are visible and which ones are not 
      function show(){ 
       htmlVisible = "" 
       htmlHidden = "" 
       for (i = 0; i < markers.length; i++) { 
        m = markers[i].marker 
        if (markers[i].visible) { 

         htmlVisible += m.title + "\n"; 
        } 
        else { 
         htmlHidden += m.title + "\n"; 
        } 

       } 
       alert("Visible markers:\n" + htmlVisible + "\n" + "Markers out of bounds:\n" + htmlHidden) 
      } 
     </script> 
    </head> 
    <body onload="initialize()"> 
     <div id="map_canvas" style="width: 320px; height: 480px;"> 
     </div> 
     <input type=button onclick="show()" value="List visible/out of bounds markers"> 
    </body> 
</html> 
相關問題