我正在尝试使用位置列表和地图标记创建实时搜索挖空,但是当我将标记创建为 ViewModel 的一部分时,代码不适用于标记,它仅适用于位置标题。
我的问题是:
如何在视图模型中不使用谷歌地图API的情况下将每个位置与其标记相匹配,我之前已经创建了标记数组,但正如我所说,视图模型无法处理它。有什么建议吗?
这是我的标记代码:
for (var i=0; i<locations.length; i++)
{
var position = locations[i].location;
var title = locations[i].title;
var marker = new google.maps.Marker({
map: map,
icon: 'http://1.bp.blogspot.com/_GZzKwf6g1o8/S6xwK6CSghI/AAAAAAAAA98/_iA3r4Ehclk/s1600/marker-green.png',
position: position,
title: title,
animation: google.maps.Animation.DROP,
id: i
});
视图模型:
// using knockout to make a live search
function ViewModel(){
var self =this;
this.filter = ko.observable();
this.locations = ko.observableArray(locations);
this.markers = ko.observableArray(markers);
this.visibleLocations = ko.computed(function(){
return this.locations().filter(function(location){
if(!self.filter() || location.title.toLowerCase().indexOf(self.filter().toLowerCase()) !== -1)
return location;
location.marker.setMap(matches ? self.map : null);
//this.location.marker.setVisible(true);
//marker.setVisible(true);
});
},this);
}
ko.applyBindings(new ViewModel());
观点 :
<label for="filter">Filter:</label>
<input id="filter" type="text" data-bind="textInput: filter"/>
<ul data-bind="foreach: visibleLocations">
<li class="markers_info"> <a href="#" data-bind="text: title"> </a></li>
</ul>
好的
,所以你this.filter
作为一个可观察量。好。这不需要this.locations
或this.markers
。只需添加一个marker
成员,locations
设置该位置的标记。然后订阅对this.filter
的更改:
self.visibleLocations = ko.observableArray();
self.filter.subscribe(function (filterValue) {
locations.forEach(function (location) {
var matches =
!filterValue ||
location.title.toLowerCase().indexOf(filterValue.toLowerCase()) !== -1;
location.marker.setMap(matches ? self.map : null);
});
self.visibleLocations(locations.filter(function (location) {
return location.marker.getMap() != null;
}));
});