How to ensure that google map is loaded?

白昼怎懂夜的黑 提交于 2019-12-11 10:43:39

问题


I have to make screenshot of google maps using phantomjs. I dynamically pass few markers to web page that is being executed by phantom, draw them on map and then I call map.fitBounds(bounds) to make sure map will cover all markers. The problem is that I have to know when map (all tiles?) is loaded so I can make a screenshot. I know how to communicate from page executed by phantom to rendering script, but I don't know how to ensure that map is loaded. Here is my code:

      map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: 0.0, lng: 0.0 },
        zoom: 8
      })

      showMarkers = function (markers) {
        markers = markers || []
        var bounds = new google.maps.LatLngBounds()
        for (var i = 0; i < markers.length; ++i) {
          var marker = new google.maps.Marker({
            position: markers[i].position,
            map: map,
            title: 'Hello World!'
          })
          bounds.extend(marker.getPosition())
        }
        map.fitBounds(bounds)

        // for now I set 1 sec timeout, but it is not always enough and I capture gray map with markers (no tiles loaded)
        setTimeout(function () {
          console.log('mapReady')
        }, 1000)
      }

回答1:


As @Timur suggested 'idle' event is what I needed, however I had to add some extra code to make it work properly in PhantomJs:

        var fitBoundsExecuted = false
        google.maps.event.addListener(map, 'idle', function () {
          if (!fitBoundsExecuted) { return }
          fitBoundsExecuted = false
          setTimeout(function () {
            console.log('mapReady')
          }, 1)
        })
        map.fitBounds(bounds)
        fitBoundsExecuted = true


来源:https://stackoverflow.com/questions/35741534/how-to-ensure-that-google-map-is-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!