我正在玩谷歌地图KML图层(和学习)。下面的代码可以工作,但一旦关闭(或设置为null),我就无法重新打开图层。我假设我需要添加一个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>
我得到一个错误“map not defined”with“layers [i] .setMap(map);”当我试图再次打开它时。
TIA
答案 0 :(得分:1)
这是因为map变量是函数initialize()中定义的局部变量。您可以在定义map时删除'var',也可以在initialize()函数的上方定义map -
var map = new google.maps.Map(document.getElementById("show_map"),myOptions);