将筛选列表传递给可见标记

时间:2017-11-01 14:09:12

标签: javascript knockout.js

我有一个简单的位置列表,

    var myLocations = [
{name: "Jim's Steaks", type: "Food", latlngLoc: {lat: 39.941557, lng: -75.149310}},
{name: "Theater of the Living Arts", type: "Entertainment", latlngLoc: {lat: 39.941461, lng: -75.148745}},
{name: "Inferno Body Piercing", type: "Body Art", latlngLoc: {lat: 39.941932, lng: -75.152870}},
{name: "South Street Diner", type: "Food", latlngLoc: {lat: 39.941259, lng: -75.145176}},
{name: "Philadelphia's Magic Gardens", type: "Entertainment", latlngLoc: {lat: 39.942642, lng: -75.159285}}];

我已经过滤了它们,

var ViewModel = function() {
    var self = this;

    this.pinList = ko.observableArray([]);

    myLocations.forEach(function(pinItem) {
        self.pinList.push(new Pin(pinItem));
    });

    this.currentPin = ko.observable(this.pinList()[0]);

    self.myLocations = myLocations;
    self.selectedType = ko.observable("All");
    self.filteredmyLocations = ko.computed(function(pinItem) {
        var type = self.selectedType();
        if(type === "All") {
        return self.myLocations;
        } else {
            var tempList = self.myLocations.slice();
            return tempList.filter(function(myLocation) {
                return myLocation.type === type;
            });
        }
    });
    this.setPin = function(clickedPin) {
        largeInfoWindow.marker = null;
        self.currentPin(clickedPin);
        showInfoWindow(clickedPin.marker, largeInfoWindow);
        loadData(clickedPin.name);
        console.log(clickedPin);
    };
};
ko.applyBindings(new ViewModel());

我的标记是这样放置的,

function makeMarkers(i) {
    var position = myLocations[i].latlngLoc;
    var name = myLocations[i].name;
    var type = myLocations[i].type;
        var marker = new google.maps.Marker({
            map: map,
            position: position,
            name: name,
            type: type,
            animation: google.maps.Animation.DROP,
            icon: defaultIcon,
            id: i
    });

    markers.push(marker);

现在我无法解决的问题是过滤标记以匹配过滤后的列表。任何帮助都会很棒,被困一个星期。

1 个答案:

答案 0 :(得分:0)

如果没有完整的代码,我必须做一些更改/假设才能得到一个有效的示例,这可能不完全符合您的尝试。希望这个概念无论如何都是有用的。我会构造像这样计算的过滤,这样它就不一定会返回任何东西,但会在计算时触发地图的刷新。 (注意 - 这必须是普通计算而不是pureComputed)

  this.filteredmyLocations = ko.computed(function(){
      var type = self.selectedType();
      var pins = self.pinList();
      if(type !== "All") {
          pins = pins.filter(function(myLocation) {
              return myLocation.type === type;
          });
      }
      self.makeMarkers(pins);
  });

然后,makeMarkers函数将获取传入的位置数组,并使用这些位置更新地图,而不是返回原始数组。完整示例:https://jsfiddle.net/a52wa21c/