使用Knockout.js过滤谷歌地图标记

时间:2015-09-24 07:59:55

标签: javascript jquery google-maps google-maps-api-3 knockout.js

我尝试使用搜索栏来隐藏谷歌地图标记。我只希望在地图上显示匹配项,我希望隐藏不匹配项。我已经尝试将标记放在一个数组中,并隐藏哪些条目与用户输入不匹配,但我似乎无法清除任何标记。我把我的HTML放在下面。

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title> Neighborhood Map</title>
        <link rel="stylesheet" href="css/styles.css">
        <script src="https://maps.googleapis.com/maps/api/js"></script>
    </head>
    <body>
        <input type="text" name="search" id="pac-input" class="controls" placeholder="Search Box" data-bind="textInput: userInput">
        <div id="map"></div>
        <div id="listView">
            <ul data-bind="foreach: point(),foreach: markerFilter(), foreach: search()">
                <li data-bind="text: name"></li>
            </ul>
        </div>
        <script src="js/lib/jquery.min.js"></script>
        <script src="js/lib/knockout-3.3.0.js"></script>
        <script src="js/app.js"></script>
      </body>
    </html>

这是我的JavaScript:

    var markers = [];
    var places = [
    {
      name: 'El Camino',
      latlng: {lat: 45.415416, lng: -75.688027}
    },
    {
      name: 'Nature Museum',
      latlng: {lat: 45.412976, lng: -75.688523}
    }
    ];

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

    self.points= ko.observableArray(places);

    self.Map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 45.4214, lng: -75.6919},
      zoom: 15
    });

    for(var i=0; i<self.points().length; i++){
        var marker = new google.maps.Marker({
        position: self.points()[i].latlng,
        title: self.points().name,
        map: self.Map
      });
      markers.push(marker);
    };

    function clearMarkers(){
      for (var i=0; i<markers.length; i++) {
        if (markers[i].title.toLowerCase().index(self.userInput()) ===-1) {
          markers[i].setMap(null);
        }
      }
    }


    self.userInput = ko.observable('');


    self.search = ko.computed(function(){
      return ko.utils.arrayFilter(self.points(), function(point){
        return point.name.toLowerCase().indexOf(self.userInput().toLowerCase()) >= 0;
      });
    });
}

ko.applyBindings(viewModel);    

0 个答案:

没有答案