2016-11-21 68 views
-1

點擊複選框時,是否可能在谷歌地圖上同時顯示標記和融合圖層?谷歌地圖API顯示標記和融合圖層一起

這是我迄今爲止,但它沒有顯示任何東西,當我點擊複選框。它只顯示當我把var markervar layer裏面initMap()功能。但不是當我想實現一個複選框

function initMap() { 
    var myLatLng = {lat: 38.5816, lng: -121.4944}; 

    return new google.maps.Map(document.getElementById('map'), { 
      zoom: 4, 
      center: myLatLng 
    }); 
} 

var map = initMap(); 


$(document).ready(function() { 
    // If city is clicked 
    $(".city-marker").click(function() { 

     if(this.checked == true) { 
      var marker = new google.maps.Marker({ 
       position: {lat: 38.5816, lng: -121.4944}, 
       map: map 
      }); 
     } 
    }) 

    // If county is clicked 
    $(".county-border").click(function() { 
     if(this.checked == true) { 
       var layer = new google.maps.FusionTablesLayer({ 
        query: { 
          select: '05000US06001', 
          from: '196LqydLhOq1Wl9612hNhcGoh4vUmRjTaiFvDhA', 
          where: "'County Name' = 'San Francisco'" 
          } 
       }); 
       layer.setMap(map); 
      } 
    }) 
}) 

https://jsfiddle.net/tuyenle/j2rc2zvu/2/

回答

2

與您的代碼的問題是,對正在加載谷歌異步映射(注意asyncdefer標籤)在這條線:

<script async defer 
src="https://maps.googleapis.com/maps/api/js?key=...&callback=initMap"> 
</script> 

所以只有在它被加載後,您才能創建地圖並添加標記/融合層。當它的加載它會調用initMap功能(通知callback=initMap中的鏈接),因此添加標記時,你應該檢查是否存在地圖對象,可能的解決方案人們可能是這樣的:

var map = null; 
function initMap() { //is called when google maps api is loaded 
    var myLatLng = {lat: 38.5816, lng: -121.4944}; 

    map = new google.maps.Map(document.getElementById('map'), { 
      zoom: 4, 
      center: myLatLng 
    }); 
} 

$(document).ready(function() { 
    // If city is clicked 
    $(".city-marker").click(function() { 
     if(map == null){ //at this point the Google maps api is still not loaded, you can maybe display a loading bar or disable the checkboxes unit it is. Anyway, this will almost never happen if user is not on very very slow internet connection. 
      console.log("Google maps not loaded yet"); 
      return; 
     } 
     if(this.checked == true) { 
      var marker = new google.maps.Marker({ 
       position: {lat: 38.5816, lng: -121.4944}, 
       map: map 
      }); 
     } 
    }); 

    // If county is clicked 
    $(".county-border").click(function() { 
     if(map == null){ 
      console.log("Google maps not loaded yet"); 
      return; 
     } 
     if(this.checked == true) { 
       var layer = new google.maps.FusionTablesLayer({ 
        query: { 
          select: '05000US06001', 
          from: '196LqydLhOq1Wl9612hNhcGoh4vUmRjTaiFvDhA', 
          where: "'County Name' = 'San Francisco'" 
          } 
       }); 
       layer.setMap(map); 
      } 
    }) 
});