如何使用Knockout.js过滤Google地图标记

我试图通过输入框过滤地图标记。 我想对地图标记名称属性上的标记进行全文排序。

 

// JS

我以为我可以将标记添加到数组中并尝试清除它们但它不起作用。 这是我的标记数组。

 this.markers = ko.observableArray([]); //Create array of hotspot locations this.hotSpotList = ko.observableArray([]); 

这会将我的“hotSpot”对象添加到热点arrays中

  initialHotSpots.forEach(function(spot){ self.hotSpotList.push(new hotSpot(spot)); }); 

这是针对hotSpots name属性搜索的filter字符串。

  this.filter = ko.observable(""); 

这是过滤后的数组的计算值。 这部分有效,因为我可以使用视图上的foreach数据绑定对我的数组列表进行排序。

  this.searchLocation = ko.computed(function() { var filter = this.filter().toLowerCase(); if (!filter) { return this.hotSpotList(); } else { return ko.utils.arrayFilter(this.hotSpotList(), function(item){ return item.name().toLowerCase().indexOf(filter) != -1; }); } }, this); 

这是创建谷歌地图。

  var mapOptions = { center: new google.maps.LatLng(39.203714,-76.861046), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById('map'), mapOptions); var infoWindow = new google.maps.InfoWindow; var marker , i; var contentString = ""; var makers var url = "" ; 

这是我在添加新集之前尝试清除标记的第一次尝试。 到目前为止,它只是将它们擦掉而且它们不再出现。

  // this.clearLocations = function() { // for (var i = 0; i < this.markers.length; i++) { // makers[i].setMap(null) // } // } 

我想如果我只是订阅了searchLocation数组它将删除旧标记并创建新标记。 它工作但只是第一次,如果文本filter字符串更改它不会再次排序标记。

  this.searchLocation.subscribe(function() { //Initialize marker and infowindow console.log('changed'); for (i = 0; i < self.searchLocation().length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(self.searchLocation()[i].lat(), self.searchLocation()[i].lng()), map: map }); this.markers.push(marker); google.maps.event.addListener(marker,'click',(function(marker, i){ return function() { url = self.searchLocation()[i].img(); contentString = "

" + self.searchLocation()[i].name() + "


" + "

" + self.searchLocation()[i].street() + "
" + self.searchLocation()[i].city() + ", " + self.searchLocation()[i].state() + "
" + self.searchLocation()[i].phone() + "
website


" + ""; infoWindow.setContent(contentString); infoWindow.open(map, marker); } })(marker, i)); } }); console.log(markers);

有任何想法吗?

以下是通过搜索框在列表视图中过滤标记的相对简单的方法:

HTML:

  

Places

JS:

 function viewModel() { var self = this; self.places = ko.observableArray(somelocations); this.filter = ko.observable(); this.visiblePlaces = ko.computed(function() { return this.places().filter(function(place) { if (!self.filter() || place.title.toLowerCase().indexOf(self.filter().toLowerCase()) !== -1) return place; }); }, this);