You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google Maps API移除多边形失效问题的修复咨询

修复Google Maps多边形隐藏按钮无效问题

问题原因

yellowPolygon 和 redPolygon 是 initialize 函数内部的局部变量,外部的 yellowOff、redOff 函数无法访问到这两个变量,调用 setMap(null) 时会触发变量未定义的错误,导致隐藏操作失效。

修复方案

将多边形变量声明在全局作用域,让按钮对应的函数能正确访问到它们。

完整修复代码

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Triangles</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=<你的Google Maps API密钥>"></script>
<script type="text/javascript">
// 声明全局变量存储多边形实例
let yellowPolygon, redPolygon;

function initialize() {
// 初始化地图:
   const myLatLng = new google.maps.LatLng(55.73,-6.25);  // 地图中心点
   const myOptions = { zoom: 10, center: myLatLng, mapTypeId: google.maps.MapTypeId.HYBRID }; // 地图配置项
   const map = new google.maps.Map(document.getElementById('map'), myOptions); // 创建地图实例
// 定义并绘制黄色三角形多边形:
   var yellowCoords = [ { lat: 55.828897, lng: -6.398249 }, { lat: 55.835067, lng: -6.126337 }, { lat: 55.674712, lng: -6.305552 } ];
   yellowPolygon = new google.maps.Polygon({ paths: yellowCoords, strokeColor: 'yellow', strokeOpacity: .7, strokeWeight: 2, fillColor: 'yellow', fillOpacity: 0.2 });
   yellowPolygon.setMap(map);
// 定义并绘制红色三角形多边形:
   var redCoords = [ { lat: 55.668897, lng: -6.198249 }, { lat: 55.835067, lng: -6.026337 }, { lat: 55.674712, lng: -6.005552 } ];
   redPolygon = new google.maps.Polygon({ paths: redCoords, strokeColor: 'red', strokeOpacity: .7, strokeWeight: 2, fillColor: 'red', fillOpacity: 0.2 });
   redPolygon.setMap(map);

} // 结束initialize函数

function yellowOff() {
  yellowPolygon.setMap(null);
}
function redOff() {
  redPolygon.setMap(null);
}

</script>
<style> #map { height: 800px; width: 800px; }</style>
</head>

<body onLoad="initialize();">

<div id="map"></div>
<button onClick="yellowOff()">Yellow Off</button>
<button onClick="redOff()">Red Off</button>
</body>
</html>

补充说明

  • 替换代码中的 <你的Google Maps API密钥> 为有效的Google Maps API密钥。
  • 移除了按钮onClick事件里多余的javascript:前缀,该前缀在HTML事件属性中属于冗余写法。

内容的提问来源于stack exchange,提问作者user2571504

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 09:31:06