2012-05-29 105 views
1

我正在開發帶有Google地圖應用程序的網頁。目前,我有一個功能搜索欄和地圖,顯示三個KML/KMZ圖層。我需要能夠在每個圖層之間切換,可以顯示其中一個,其中兩個或全部三個。 Google地球中有類似的功能,但我需要在Google地圖中使用它。我怎樣才能做到這一點?如何在Google地圖api v3中切換KML/KMZ圖層

這裏是我的地圖和搜索欄代碼:

<script type="text/javascript"> 
    var geocoder; 
    var map; 
    var marker; 
    function initialize() { 
    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng (40.43, -74.00); 
    var myOptions = { 
     zoom: 5, 
     center: latlng, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
     } 
     map = new google.maps.Map(document.getElementById("map_canvas"), 
     myOptions); 
     marker = new google.maps.Marker({map:map}); 

    var ctaLayer = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/NY_Radar_data.kmz'); 
     ctaLayer.setMap(map); 
    var ctaLayer = new google.maps.KmlLayer('http://www.nyc.gov/html/dot/downloads/misc/cityracks.kml'); 
     ctaLayer.setMap(map); 
    var ctaLayer = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/OKX_Radar_data%20(1).kmz'); 
     ctaLayer.setMap(map); 
     } 
    function codeAddress() { 
     var address = document.getElementById ("address").value; 
     geocoder.geocode ({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      map.setCenter(results [0].geometry.location); 
      marker.setPosition(results [0].geometry.location); 
      map.setZoom(14); 
      } 
     else { 
      alert("Geocode was not successful for the following reason: " + status); 
       } 
    }); 
          } 
</script> 

回答

10

它只是setMap(null)隱藏一個,setMap(map)顯現。我保持全局數組變量layers,跟蹤哪個層的切換:

var layers = []; 
layers[0] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/NY_Radar_data.kmz', 
{preserveViewport: true}); 
     layers[1] = new google.maps.KmlLayer('http://www.nyc.gov/html/dot/downloads/misc/cityracks.kml', 
{preserveViewport: true}); 
     layers[2] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/OKX_Radar_data%20(1).kmz', 
{preserveViewport: true}); 

的preserveViewport,用於從選項時所述層切換跳來跳去停止地圖。

這裏的功能切換:

function toggleLayer(i) { 
    if(layers[i].getMap() === null) { 
    layers[i].setMap(map); 
    } 
    else { 
    layers[i].setMap(null); 
    } 
} 

注意它的使用全局變量。最後是HTML,你可以使用複選框或按鈕,甚至一個單選按鈕,通過首先設置一個活動層,並在收音機集更新時啓用正確的一個。

Large weather <input type="checkbox" id="layer0" onclick="toggleLayer(0)" checked> 
<input type="button" id="layer1" onclick="toggleLayer(1)" value="Racks"> 
Small weather <input type="checkbox" id="layer2" onclick="toggleLayer(2)" checked> 

整個演示是在這裏,在地圖的左上角控制:http://jsbin.com/irahef/edit#preview

+0

非常感謝您Heiter,這是非常有幫助的。還有什麼其他輸入類型? – Gavin

+0

並且您是否只是製作該網頁?這很容易理解和使用。 – Gavin

+0

這裏是一個頁面http://html.mcwebber.net/customize.html,你可以搜索「表單輸入」。我錯過的另一種是'