我正在使用Google Maps Javascript V3 API构建搜索表单。我想添加一些过滤器,点击时会隐藏地图上某些类型的标记。要隐藏的标记用
表示locations[i][11] == 'Other'
<a href="#" class="hideOtherMarkers">Hide Other Markers</a>
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
};
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var locations = <?php echo json_encode($locations_array); ?>;
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var content = '';
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addDomListener(document.getElementsByClassName('hideOtherMarkers')[0], 'click', function() {
if (locations[i][11] == 'Other') {
marker.setVisible(false); // maps API hide call
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
当我点击链接时,没有任何内容触发,通过警报验证。我也试过google.maps.event.addListener(没有Dom)但没有成功。
答案 0 :(得分:1)
正如geocodezip评论的那样,这种方法不起作用,因为i
总是会指向locations
的结尾。此外,这将最多隐藏1个标记(已创建的最后一个标记)。
可能的方法:
将标记的可见状态存储在MVCObject中:
地图选项:
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
//that's the property where we store the state
visibility:new google.maps.MVCObject
};
在创建marker
之后在循环内部:
//when the state is not set yet, set it
if(typeof map.get('visibility').get(locations[i][11])==='undefined'){
map.get('visibility').set(locations[i][11],true);
}
//bind the visible-property of the marker to the state
marker.bindTo('visible',map.get('visibility'),locations[i][11]);
添加侦听器(在循环之外):
google.maps.event.addDomListener(
document.getElementsByClassName('hideOtherMarkers')[0],
'click',
function() {
//simply set the desired property of the MVCObject to false
map.get('visibility').set('Other',false);
});