我正在使用谷歌地图,我正在使用数组locations
放置地图标记,现在我想调用函数clearMarkers()
如果i==26
我该怎么做?
代码:
var markers = [];
var map;
var india = new google.maps.LatLng(21.9200,77.9000);
var image = 'images/pushpins/set1.png';
function initialize() {
var mapOptions = {
zoom: 5,
center: india
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
drop();
}
function drop() {
clearMarkers();
for (var i = 0; i < locations.length; i++) {
var city = locations[i][0];
var pro_cat = locations[i][1];
addMarkerWithTimeout(locations[i][2], i * 500);
getCity(city,pro_cat, i * 500);
}
if (i==26){
clearMarkers();
}
}
function addMarkerWithTimeout(position, timeout) {
window.setTimeout(function() {
markers.push(new google.maps.Marker({
position: position,
map: map,
icon: image,
optimized: false,
//animation: google.maps.Animation.BOUNCE
}));
}, timeout);
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
document.getElementById('order_list').innerHTML = "";
}
function getCity(city_name, product_cat, timeout){
window.setTimeout(function() {
var writecity = document.createTextNode(city_name+', '+product_cat);
document.getElementById("order_list").appendChild(writecity);
document.getElementById("order_list").appendChild(document.createElement('br'));
}, timeout);
}
google.maps.event.addDomListener(window, 'load', initialize);
这里我使用for循环来调用函数但是它没有工作
function drop() {
clearMarkers();
for (var i = 0; i < locations.length; i++) {
if (i==26){
clearMarkers();
}
var city = locations[i][0];
var pro_cat = locations[i][1];
addMarkerWithTimeout(locations[i][2], i * 500);
getCity(city,pro_cat, i * 500);
}
}
答案 0 :(得分:2)
if
语句在外部循环,因此i
变量未设置,并且与26的比较将始终返回false,除非您有全局i
变量。将您的drop函数更改为:
function drop() {
clearMarkers();
for (var i = 0; i < locations.length; i++) {
var city = locations[i][0];
var pro_cat = locations[i][1];
addMarkerWithTimeout(locations[i][2], i * 500);
getCity(city,pro_cat, i * 500);
if (i==26){
clearMarkers();
}
}
}
然而,你遇到的问题有点不同。在处理主函数后放置标记。因此什么都不会被清除。如果您删除了window.setTimout
中的addMarkerWithTimeout
,则应该有效。
function addMarkerWithTimeout(position, timeout) {
markers.push(new google.maps.Marker({
position: position,
map: map,
icon: image,
optimized: false,
//animation: google.maps.Animation.BOUNCE
}));
}