我现在正在玩(和学习)谷歌地图 KML 图层。下面的代码有效,但一旦关闭(或设置为空),我就无法重新打开图层。我假设我需要添加一个 DOM 侦听器,但不确定如何执行此操作。帮助表示赞赏。
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
var layers = [];
function initialize() {
var myLatLng = new google.maps.LatLng(-41.356341319572, 147.41842480153);
var bounds = new google.maps.LatLngBounds();
var myOptions = {
zoom: 12,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("show_map"),myOptions);
var image1 = 'images/sa.png';
var ctaLayer = new google.maps.KmlLayer('http://a.server/inc/kml_files/search_tests.kmz');
ctaLayer.setMap(map);
var varLatLng = new google.maps.LatLng(-41.356341319572,147.41842480153);
layers[1] = new google.maps.KmlLayer('http://a.server/inc/kml_gps/p2track.kml', {preserveViewport:true});
layers[1].setMap(map);
layers[2] = new google.maps.KmlLayer('http://a.server/inc/kml_gps/p5_day2.kml', {preserveViewport:true});
layers[2].setMap(map);
bounds.extend(varLatLng);
map.fitBounds(bounds);
}
function toggleLayer(i) {
if(layers[i].getMap() === null) {
layers[i].setMap(map);
} else {
layers[i].setMap(null);
}
}
</script>
</head />
<body style="margin:0px; padding:0px;" onload="initialize()" />
<div id="show_map" style="width:100%; height:95%;"></div>
<input type="button" id="layer1" onclick="toggleLayer(1)" value="GPS Tracks 1 On/Off">
<input type="button" id="layer2" onclick="toggleLayer(2)" value="GPS Tracks 2 On/Off">
</body>
</html>
我收到错误“未定义地图”,“layers[i].setMap(map);” 当我尝试再次打开它时。
TIA