如何确保谷歌地图已加载? [英] How to ensure that google map is loaded?
问题描述
我必须使用phantomjs制作Google地图的屏幕截图.我将少量标记动态传递到幻象正在执行的网页上,在地图上绘制它们,然后调用map.fitBounds(bounds)
以确保地图将覆盖所有标记.问题是我必须知道何时加载地图(所有图块?),才能制作屏幕截图.我知道如何从幻像执行的页面到渲染脚本进行通信,但是我不知道如何确保加载地图.这是我的代码:
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)
}
推荐答案
正如@Timur所建议的那样,我需要'idle'事件,但是我不得不添加一些额外的代码以使其在PhantomJs中正常工作:
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
这篇关于如何确保谷歌地图已加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!