Removing Map Pin with Search

后端 未结 3 1831
-上瘾入骨i
-上瘾入骨i 2021-01-19 02:43

I\'m trying to create a search bar that filters out items from a list if they do not match the search query. The additional functionality that I\'m trying to add is that if

3条回答
  •  没有蜡笔的小新
    2021-01-19 03:10

    I would encapsulate your markers into their own data model that takes care of the interaction with Google Maps behind the scenes:

    // we have to give it access to the map object, so that
    // it can register and de-register itself
    var Pin = function Pin(map, name, lat, lon, text) {
      var marker;
    
      this.name = ko.observable(name);
      this.lat  = ko.observable(lat);
      this.lon  = ko.observable(lon);
      this.text = ko.observable(text);
    
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon),
        animation: google.maps.Animation.DROP
      });
    
      this.isVisible = ko.observable(false);
    
      this.isVisible.subscribe(function(currentState) {
        if (currentState) {
          marker.setMap(map);
        } else {
          marker.setMap(null);
        }
      });
    
      this.isVisible(true);
    }
    

    Now you can create your pins with pin = new Pin(map, 1, 2, 'text'), and when you toggle their visibility state with pin.isVisible(false), they automatically register or deregister with the map.

    Your filter function thus becomes

    self.filterPins = ko.computed(function () {
        var search  = self.query().toLowerCase();
    
        return ko.utils.arrayFilter(self.pins(), function (pin) {
            var doesMatch = pin.name().toLowerCase().indexOf(search) >= 0;
    
            pin.isVisible(doesMatch);
    
            return doesMatch;
        });
    });
    

提交回复
热议问题