使用1个按钮切换显示/隐藏谷歌圈子



我在谷歌地图中围绕所述位置的中心创建了圆圈。我想用一个按钮切换它来显示或隐藏我在互联网上查找的参考资料中找不到的圆/半径。

引用: https://developers.google.com/maps/documentation/javascript/shapes 使用谷歌地图API在点击时隐藏标记 在谷歌地图上显示/隐藏圈子 JavaScript API

代码:

<button class="button-red pure-button" onclick="toggleRadius()">
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 1.3420894594991328, lng: 103.83490918886719},
});
var ntuc = {lat: 1.32805676, lng: 103.9216584};
var ntucCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: ntuc,
radius: 5000, // in metres
visible: false
});
ntucCircle.bindTo('center', marker, 'position');
}

我已经尝试了3种方法来切换Google圈子,但无济于事。

第一种方法:

function toggleRadius() {
ntucCircle.set('opacity', ntucCircle.get('opacity') ? null : 0.35);
}

第二种方法:

function toggleRadius() {
ntucCircle.setMap(ntucCircle.getMap() ? null : map);
}

第三种方法:

function toggleRadius() {
if (ntucCircle.getMap() != null) {
ntucCircle.setMap(null);
} else {
ntucCircle.setMap(map);
}
}

我不确定出了什么问题。我感谢任何形式的帮助,希望有人能够回答我的问题 - 使用 1 个按钮切换 Google 圈子。

使用您的代码:

function toggleRadius() {
ntucCircle.setMap(ntucCircle.getMap() ? null : map);
}

我收到一个 javascript 错误:Uncaught TypeError: Cannot read property 'setMap' of undefined因为ntucCircleinitMap函数的本地,而不是在全局上下文中(需要 HTML 单击处理程序函数

(。概念验证小提琴

代码片段:

// global variables
var map;
var ntucCircle;
var markers = [];
function toggleRadius() {
ntucCircle.setMap(ntucCircle.getMap() ? null : map);
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: 1.3420894594991328,
lng: 103.83490918886719
},
});
var ntuc = {
lat: 1.32805676,
lng: 103.9216584
};
// initialize the global variable
ntucCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: ntuc,
radius: 5000, // in metres
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<button class="button-red pure-button" onclick="toggleRadius()">toggle</button>
<div id="map"></div>

我已经解决了我自己的问题,这是解决方案。

<button class="button-red pure-button" onclick="toggleRadius()">
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 1.3420894594991328, lng: 103.83490918886719},
});
var ntuc = {lat: 1.32805676, lng: 103.9216584};
var ntucCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: ntuc,
radius: 5000, // in metres
});
ntucCircle.setMap(null);

function toggleRadius() {
ntucCircle.setMap(ntucCircle.getMap() ? null : map);
}

最新更新