我有一张地图,显示Circle,在我的位置数组中,每组坐标周围的半径为50英里。我希望有一系列按钮来增加或减少地图上每个圆圈的半径。我现在拥有它的方式,它只是改变与我的数组中最后一个位置相关的圆的半径。我理解为什么会这样(因为圆形变量被分配给for
循环中的每个点),但我不知道如何更改它以便更新每个圆的半径。
var retailerCircle;
var retailermap = {
chicago: {
coords: {lat: 41.878, lng: -87.629}
},
newyork: {
coords: {lat: 40.714, lng: -74.005}
},
losangeles: {
coords: {lat: 34.052, lng: -118.243}
},
vancouver: {
coords: {lat: 49.25, lng: -123.1}
}
};
function initMap() {
// Create the map.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 41.878003, lng: -93.097702},
mapTypeId: 'terrain'
});
for (var retailer in retailermap) {
// Add the circle for this retailer to the map.
retailerCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: retailermap[retailer].coords,
radius: 80467.2 // 50 miles
});
}
}
function updateRadius(circle, rad){
circle.setRadius(rad);
}
$(function() {
$('button').click(function(e) {
e.preventDefault();
updateRadius(retailerCircle, 160934); // 100 miles
});
});

html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 80%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="map"></div>
<button>CLICK ME</button>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
&#13;
答案 0 :(得分:1)
保持对所有圆圈的引用(在数组中将是一个选项),然后遍历该数组,更新半径。
function updateRadius(circle, rad) {
for (var i = 0; i < circles.length; i++) {
circles[i].setRadius(rad);
}
}
代码段
var retailerCircle;
var circles = [];
var retailermap = {
chicago: {
coords: {
lat: 41.878,
lng: -87.629
}
},
newyork: {
coords: {
lat: 40.714,
lng: -74.005
}
},
losangeles: {
coords: {
lat: 34.052,
lng: -118.243
}
},
vancouver: {
coords: {
lat: 49.25,
lng: -123.1
}
}
};
function initMap() {
// Create the map.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: 41.878003,
lng: -93.097702
},
mapTypeId: 'terrain'
});
for (var retailer in retailermap) {
// Add the circle for this retailer to the map.
var retailerCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: retailermap[retailer].coords,
radius: 80467.2 // 50 miles
});
circles.push(retailerCircle);
}
}
function updateRadius(circle, rad) {
for (var i = 0; i < circles.length; i++) {
circles[i].setRadius(rad);
}
}
$(function() {
$('button').click(function(e) {
e.preventDefault();
updateRadius(retailerCircle, 160934); // 100 miles
});
});
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 80%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="map"></div>
<button>CLICK ME</button>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>