2016-11-21 12 views
-1

チェックボックスをオンにすると、マップと融合レイヤーを同時にGoogleマップに表示できますか?GoogleマップAPI表示マーカーと融合レイヤーをまとめて

これは私がこれまで行ってきたことですが、チェックボックスをクリックすると何も表示されません。 initMap()の機能の中にvar markervar layerを入れたときだけ表示されます。しかし、ではない、私はあなたのコードの問題は、あなたは、Googleがこのライン上(asyncdeferタグを気付か)非同期的にマッピングロードしていることを、あるチェックボックス

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

を実装したい場合:

<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); 
      } 
    }) 
}); 
関連する問題