1

我现在正在玩(和学习)谷歌地图 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&nbsp;Tracks 1 On/Off">
<input type="button" id="layer2" onclick="toggleLayer(2)" value="GPS&nbsp;Tracks 2 On/Off">
</body>
</html>

我收到错误“未定义地图”,“layers[i].setMap(map);” 当我尝试再次打开它时。

TIA

4

1 回答 1

1

这是因为 map 变量是在函数 initialize() 中定义的局部变量。您可以在定义 map 时删除“var”,也可以在 initialize() 函数上方定义 map -

  var map = new google.maps.Map(document.getElementById("show_map"),myOptions);
于 2013-01-20T04:53:58.253 回答