如何使用地图标记列表创建实时搜索淘汰赛?

时间:2018-03-04 20:34:01

标签: google-maps knockout.js marker livesearch

我正在尝试使用位置列表和地图标记创建实时搜索淘汰赛,但是当我将标记创建为ViewModel的一部分时,代码不适用于标记,它仅适用于位置标题。< / p>

我的问题是:

如何在不使用视图模型中的谷歌地图API的情况下将每个位置与其标记匹配,我之前已经创建过标记数组,但正如我所说,viewmodel无法处理它。有什么建议吗?

这是我的标记代码:

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>

1 个答案:

答案 0 :(得分:0)

好的,所以你有this.filter作为观察者。好。这不需要this.locationsthis.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;
    }));
});