当我缩放每级Google地图时,如何指定加载一个kml文件? 这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Getting Properties With Event Handlers</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var kmlLayer;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: { lat: 10.89779, lng: 106.64619 }
});
map.addListener('idle', function () {
if (map.getZoom() == 9) {
//alert('aa');
kmlLayer = new google.maps.KmlLayer({
url: 'a.kml',
map: map
});
}
else if (map.getZoom() == 10) {
kmlLayer = new google.maps.KmlLayer({
url: 'b.kml',
map: map
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API&callback=initMap">
</script>
</body>
</html>
这意味着map.getZoom() == 9
时,地图将按文件a.kml
绘制。 Map.getZoom() == 10
将根据b.kml
文件进行绘制,而a.kml
文件所创建的所有细节都将被删除。
但是当a.kml
文件创建缩放和细节时,我上面的代码并不平滑。 Map.getZoom() == 10
不会将其删除。
请帮助我解决此问题。谢谢
答案 0 :(得分:0)
您需要先隐藏现有的KmlLayer,然后再显示新的KmlLayer。像这样:
var kmlLayer;
map.addListener('idle', function () {
if (map.getZoom() == 9) {
if (kmlLayer && kmlLayer.setMap) kmlLayer.setMap(null);
kmlLayer = new google.maps.KmlLayer({
url: 'a.kml',
map: map
});
}
else if (map.getZoom() == 10) {
if (kmlLayer && kmlLayer.setMap) kmlLayer.setMap(null);
kmlLayer = new google.maps.KmlLayer({
url: 'b.kml',
map: map
});
}
(如果您为所有缩放级别定义了KmlLayers,则可能需要将隐藏现有图层的代码移到if
之外)