如何在 google 地图中一切就绪时触发 Button Click?

How to trigger Button Click when everything is ready in google maps?

我有一个 google 地图设置,其中加载了 geojson 图层。 geojson 包含许多多边形特征。

我想通过点击页面中的特定按钮来触发这些功能,我已经通过参考这个帖子成功地做到了:

现在,我想做的是每当我打开页面时,页面都会触发特定的按钮点击。或者说,每当文档准备就绪时,触发按钮(即触发功能点击)。

我做错了什么导致我无法触发按钮点击就绪功能?

这是我所做的:

$(document).ready(function(){
 $('#btnFirstLetter').click();
});

function initialize() {
  // Create a simple map.
  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 4,
    center: {lat: -28, lng: 137.883}
  });
map.data.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json');
  // Load a GeoJSON from the same server as our demo.
  
  google.maps.event.addListener(map.data,'addfeature',function(e){
      if(e.feature.getGeometry().getType()==='Polygon'){
          var bounds=new google.maps.LatLngBounds();
          
          e.feature.getGeometry().getArray().forEach(function(path){
          
             path.getArray().forEach(function(latLng){bounds.extend(latLng);})
          
          });
          e.feature.setProperty('bounds',bounds);
          
          new google.maps.Rectangle({map:map,bounds:bounds,clickable:false})
        
        }
  });
  
  $('#btnFirstLetter').click(function(){
   var firstLetter = 'G';
    
    map.data.forEach(function(feature){
     if (firstLetter == feature.getProperty('letter')){
       google.maps.event.trigger(map.data, 'click', {'feature': feature}); 
      }     
    });
  });
  
  google.maps.event.addListener(map.data,'click',function(e){
   var bounds=e.feature.getProperty('bounds');
    if(bounds){
      map.fitBounds(bounds);
    }
  })
  
  
  
}

google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
        height: 90%;
        margin: 0px;
        padding: 0px
      }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<div id="map-canvas"></div>
<button id="btnFirstLetter">
First Letter
</button>

或者这是我的 jsfiddle:https://jsfiddle.net/iam47/1Lxj2wf7/7/

不同的浏览器对 DOMContentLoaded 事件或 $(document).ready() 函数做出不同的响应,您可以简单地为点击调用添加一个 sligth 超时..

$(document).ready(function(){
   setTimeout(function(){
       $('#btnFirstLetter').click();
  }, 500);

});

尝试将超时减少到您可以接受的值

设置超时的危险在于,您会创建一个竞争条件,这可能会导致不良结果,尤其是当您从外部源调用数据时(慢速网络和 geoJSON 数据需要 501 毫秒才能到达?真倒霉。 ..)

虽然 loadGeoJson 确实提供了数据到达后的回调选项,但您真正想要的是在数据呈现后触发点击...

google.maps.event.addListener(map.data,'addfeature',function(e){
  if(e.feature.getGeometry().getType()==='Polygon'){
      var bounds=new google.maps.LatLngBounds();
      e.feature.getGeometry().getArray().forEach(function(path){
         path.getArray().forEach(function(latLng){bounds.extend(latLng);})
      });
      e.feature.setProperty('bounds',bounds);
      new google.maps.Rectangle({map:map,bounds:bounds,clickable:false})
    }
    $('#btnFirstLetter').click();
});