多个交叉过滤器Google Maps API

时间:2016-02-29 19:11:30

标签: javascript json google-maps google-maps-api-3

我已经搜索了几个星期,试图找出如何使用JavaScript和Google Maps API过滤多个条件,并找到this 这本质上是我要添加到地图的功能(请参阅下面的代码和JSfiddle),但对于我的生活,我无法让它工作......我哪里出错?

// bring in park data JSON

var pJSON = [{
  "id": 287,
  "date": "2016-02-24T21:35:49",
  "date_gmt": "2016-02-24T21:35:49",
  "guid": {
    "rendered": "http:\/\/test.yourpdg.net\/crpd\/?post_type=parks&p=287"
  },
  "modified": "2016-02-24T21:38:40",
  "modified_gmt": "2016-02-24T21:38:40",
  "slug": "white-rock-neighborhood-park-2",
  "type": "parks",
  "link": "http:\/\/test.yourpdg.net\/crpd\/parks\/white-rock-neighborhood-park-2\/",
  "title": {
    "rendered": "White Rock Neighborhood Park"
  },
  "content": {
    "rendered": ""
  },
  "excerpt": {
    "rendered": ""
  },
  "featured_image": 0,
  "menu_order": 0,
  "acf": {
    "park_photos": false,
    "park_type": [{
      "term_id": 26,
      "name": "Parks",
      "slug": "parks",
      "term_group": 0,
      "term_taxonomy_id": 26,
      "taxonomy": "facility",
      "description": "",
      "parent": 0,
      "count": 36,
      "filter": "raw"
    }, {
      "term_id": 23,
      "name": "Pool & Spray Parks",
      "slug": "pool-spray-parks",
      "term_group": 0,
      "term_taxonomy_id": 23,
      "taxonomy": "facility",
      "description": "",
      "parent": 0,
      "count": 8,
      "filter": "raw"
    }],
    "park_address": "10488 White Rock Road <br \/>\r\nRancho Cordova, CA",
    "map_coordinates": {
      "address": "10488 White Rock Road, Rancho Cordova, CA, United States",
      "lat": "38.5852927",
      "lng": "-121.30029189999999"
    },
    "park_info": "<p>General Information: 916-362-1841<\/p>\n<p>Rental Information: 916-362-1841<br \/>\nRENTALS AVAILABLE(link to download rental information)<\/p>\n<p>Park Hours: Sunrise to Sunset<\/p>\n<p><strong>Splash Park Hours:<br \/>\n<\/strong>May and September: Friday-Sunday only, 10AM-7PM<br \/>\nMemorial Day through Labor Day: Every day, 10AM-7PM<\/p>\n",
    "park_description": "<p>White Rock Park is located across the street from White Rock Elementary School. Updated in 2011, this 14-acre park now features a new community center, aquatic splash park, playground, picnic pavilion, picnic areas and athletic fields.<\/p>\n",
    "aquatic_center": "1",
    "community_center": "1",
    "youth_playground": "1",
    "dog_park": "",
    "restrooms": "",
    "family_picnic_areas": "1",
    "group_picnic_areas": "1",
    "baseball_fields": "1",
    "soccer_fields": "1",
    "tennis_courts": "1",
    "horseshoe_courts": "3",
    "parking": false,
    "links_interest": "",
    "custom_sidebar": ""
  },
  "_links": {
    "self": [{
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/parks\/287"
    }],
    "collection": [{
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/parks"
    }],
    "about": [{
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/types\/parks"
    }],
    "version-history": [{
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/parks\/287\/revisions"
    }],
    "https:\/\/api.w.org\/attachment": [{
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/media?parent=287"
    }],
    "https:\/\/api.w.org\/term": [{
      "taxonomy": "facility",
      "embeddable": true,
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/parks\/287\/facility"
    }, {
      "taxonomy": "amenities",
      "embeddable": true,
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/parks\/287\/amenities"
    }]
  }
}, {
  "id": 285,
  "date": "2016-02-24T21:34:36",
  "date_gmt": "2016-02-24T21:34:36",
  "guid": {
    "rendered": "http:\/\/test.yourpdg.net\/crpd\/?post_type=parks&#038;p=285"
  },
  "modified": "2016-02-24T21:34:36",
  "modified_gmt": "2016-02-24T21:34:36",
  "slug": "waterbrook-park",
  "type": "parks",
  "link": "http:\/\/test.yourpdg.net\/crpd\/parks\/waterbrook-park\/",
  "title": {
    "rendered": "Waterbrook Park"
  },
  "content": {
    "rendered": ""
  },
  "excerpt": {
    "rendered": ""
  },
  "featured_image": 0,
  "menu_order": 0,
  "acf": {
    "park_photos": false,
    "park_type": [{
      "term_id": 26,
      "name": "Parks",
      "slug": "parks",
      "term_group": 0,
      "term_taxonomy_id": 26,
      "taxonomy": "facility",
      "description": "",
      "parent": 0,
      "count": 36,
      "filter": "raw"
    }],
    "park_address": "10849 Waterbrook Drive<br \/>\r\nRancho Cordova, CA",
    "map_coordinates": {
      "address": "10858 Waterbrook Way, Gold River, CA 95670, USA",
      "lat": "38.57520937925042",
      "lng": "-121.28271602083203"
    },
    "park_info": "<p>General Information: 916-362-1841<\/p>\n<p>Park Hours: Sunrise to Sunset<\/p>\n",
    "park_description": "<p>This quaint park is nestled between homes in Stone Creek. A large playground structure is the centerpiece of this park.<\/p>\n",
    "aquatic_center": "",
    "community_center": "",
    "youth_playground": "1",
    "dog_park": "",
    "restrooms": "",
    "family_picnic_areas": "",
    "group_picnic_areas": "",
    "baseball_fields": "",
    "soccer_fields": "",
    "tennis_courts": "",
    "horseshoe_courts": "",
    "parking": false,
    "links_interest": "",
    "custom_sidebar": ""
  },
  "_links": {
    "self": [{
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/parks\/285"
    }],
    "collection": [{
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/parks"
    }],
    "about": [{
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/types\/parks"
    }],
    "version-history": [{
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/parks\/285\/revisions"
    }],
    "https:\/\/api.w.org\/attachment": [{
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/media?parent=285"
    }],
    "https:\/\/api.w.org\/term": [{
      "taxonomy": "facility",
      "embeddable": true,
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/parks\/285\/facility"
    }, {
      "taxonomy": "amenities",
      "embeddable": true,
      "href": "http:\/\/test.yourpdg.net\/crpd\/wp-json\/wp\/v2\/parks\/285\/amenities"
    }]
  }
}, ]

//restructure JSON into parkData object

var parkData = [];

for (i = 0; i < pJSON.length; i++) {
  park = pJSON[i];

  parkData.push({
    id: pJSON[i].id,
    title: pJSON[i].title.rendered,
    address: pJSON[i].acf.park_address,
    lat: pJSON[i].acf.map_coordinates.lat,
    lng: pJSON[i].acf.map_coordinates.lng,
    category: pJSON[i].acf.park_type[0].slug,
    aquatic_center: parseInt(pJSON[i].acf.aquatic_center),
    community_center: parseInt(pJSON[i].acf.community_center),
    youth_playground: parseInt(pJSON[i].acf.youth_playground),
    dog_park: parseInt(pJSON[i].acf.dog_park),
    restrooms: parseInt(pJSON[i].acf.restrooms),
    family_picnic_areas: parseInt(pJSON[i].acf.family_picnic_areas),
    group_picnic_areas: parseInt(pJSON[i].acf.group_picnic_areas),
    baseball_fields: parseInt(pJSON[i].acf.baseball_fields),
    soccer_fields: parseInt(pJSON[i].acf.soccer_fields),
    tennis_courts: parseInt(pJSON[i].acf.tennis_courts),
    horseshoe_courts: parseInt(pJSON[i].acf.horseshoe_courts)
  });
}



console.log(parkData);

//begin map

var myMap = function() {
  var options = {
    zoom: 13,
    center: new google.maps.LatLng(38.5890723, -121.302728),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  }

  function init(settings) {
    map = new google.maps.Map(document.getElementById(settings.idSelector), options);
    loadMarkers();
  }

  //MARKERS

  markers = {};
  markerList = [];

  function loadMarkers(parklist) {
    var parks = (typeof parklist !== 'undefined') ? parklist : parkData;

    //console.log(parks);

    for (i = 0; i < parks.length; i++) {
      var park = parks[i];

      if (markerList.indexOf(park.id) !== -1) continue;

      var lat = park.lat,
        lng = park.lng,
        markerId = park.id;

      var infoWindow = new google.maps.InfoWindow({
        maxWidth: 400
      });

      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        title: park.title,
        markerId: park.id,
        //icon: park.pin,
        map: map
      });

      markers[markerId] = marker;
      markerList.push(parks.id);

      var content = park.title + '<br>' + park.category + '<br>' + park.address;

      google.maps.event.addListener(marker, 'click', (function(marker, content) {
        return function() {
          infoWindow.setContent(content);
          infoWindow.open(map, marker);
        }
      })(marker, content));
    }
  }

  function removeParkMarker(id) {
    if (markers[id]) {
      markers[id].setMap(null);
      loc = markerList.indexOf(id);
      if (loc > -1) markerList.splice(loc, 1);
      delete markers[id];
    }
  }

  //filters

  var filter = {
    category: 0,
    aquatic_center: 0,
    community_center: 0,
    youth_playground: 0,
    dog_park: 0,
    restrooms: 0,
    family_picnic_areas: 0,
    group_picnic_areas: 0,
    baseball_fields: 0,
    soccer_fields: 0,
    tennis_courts: 0,
    horseshoe_courts: 0
  }

  var filterMap;


  function reduceArray(a) {
    r = a.shift().reduce(function(re, v) {
      if (res.indexOf(v) === -1 && a.every(function(a) {
          return a.indexOf(v) !== -1;
        })) res.push(v);
      return res;
    }, []);
    return r;
  }

  function isInt(n) {
    return n % 1 === 0;
  }

  function filterCtrl(filterType, value) {
    var results = [];

    if (isInt(value)) {
      filter[filterType] = parseInt(value);
    } else {
      filter[filterType] = value;
    }

    for (k in filter) {
      if (!filter.hasOwnProperty(k) && !(filter[k] !== 0)) {
        loadMarkers();
        return false;
      } else if (filter[k] !== 0) {
        results.push(filterMap[k](filter[k]));
      } else {

      }
    }

    if (filter[filterType] === 0) results.push(parkData);

    if (results.length === 1) {
      results = results[0];
    } else {
      results = reduceArray(results);
    }

    loadMarkers(results);
    console.log(results);
  }

  filterMap = {
    category: function(value) {
      return filterByString('category', value);
    },

    aquatic_center: function(value) {
      return filterIntLessThan('aquatic_center', value);
    },

    community_center: function(value) {
      return filterIntLessThan('community_center', value);
    },

    youth_playground: function(value) {
      return filterIntLessThan('youth_playground', value);
    },

    dog_park: function(value) {
      return filterIntLessThan('dog_park', value);
    },

    restrooms: function(value) {
      return filterIntLessThan('restrooms', value);
    },

    family_picnic_areas: function(value) {
      return filterIntLessThan('family_picnic_areas', value);
    },

    group_picnic_areas: function(value) {
      return filterIntLessThan('group_picnic_areas', value);
    },

    baseball_fields: function(value) {
      return filterIntLessThan('baseball_fields', value);
    },

    soccer_fields: function(value) {
      return filterIntLessThan('soccer_fields', value);
    },

    tennis_courts: function(value) {
      return filterIntLessThan('tennis_courts', value);
    },

    horseshoe_courts: function(value) {
      return filterIntLessThan('horseshoe_courts', value);
    }

  }

  function filterByString(dataProperty, value) {
    var parks = [];
    for (var i = 0; i < parkData.length; i++) {
      var park = parkData[i];
      if (park[dataProperty] == value) {
        parks.push(park);
      } else {
        removeParkMarker(park.id);
      }
    }

    return parks;
  }

  function filterIntLessThan(dataProperty, value) {
    var parks = [];
    for (var i = 0; i < parkData.length; i++) {
      var park = parkData[i];
      if (park[dataProperty] >= value) {
        parks.push(park);
      } else {
        removeParkMarker(park.id);
      }
    }
    return parks;
  }

  function resetFilter() {
    filter = {
      category: 0,
      aquatic_center: 0,
      community_center: 0,
      youth_playground: 0,
      dog_park: 0,
      restrooms: 0,
      family_picnic_areas: 0,
      group_picnic_areas: 0,
      baseball_fields: 0,
      soccer_fields: 0,
      tennis_courts: 0,
      horseshoe_courts: 0
    }
  }

  return {
    init: init,
    loadMarkers: loadMarkers,
    filterCtrl: filterCtrl,
    resetFilter: resetFilter

  };

}();

$(function() {

  var mapConfig = {
    idSelector: 'map',
  };

  myMap.init(mapConfig);

  $('.load-btn').on('click', function() {
    var $this = $(this);

    // reset everything
    $('select').val(0);
    myMap.resetFilter();
    myMap.loadMarkers();

    if ($this.hasClass('is-success')) {
      $this.removeClass('is-success').addClass('is-default');
    }
  });

  $('.cat-select').on('change', function() {
    myMap.filterCtrl('category', this.value);
  });

  $('.amen-select').on('change', function() {
    myMap.filterCtrl($(this).find('option:selected').data('id'), this.value);
  });
});
    #map {
          width: 500px;
          height: 500px;
        }
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map"></div>

<div class="filter-set" style="margin-top:0;">
  <button id="load-btn" class="load-btn button is-success">clear filter</button>
</div>
<div class="filter-set">
  <label for="cat-select">Park Type:</label>
  <select name="cat-select" id="cat-select" class="cat-select">
    <option value="0">Any</option>
    <option value="pool-spray-parks">Pool &amp; Spray Parks</option>
    <option value="athletic-fields">Athletic Fields</option>
    <option value="sports-centers">Sports Centers</option>
    <option value="recreation-centers">Recreation Centers</option>
    <option value="district-offices">District Offices</option>
    <option value="parks">Parks</option>
  </select>
</div>
<div class="filter-set">
  <label for="amen-select">Amenities:</label>
  <select name="amen-select" id="amen-select" class="amen-select">
    <option>Any</option>
    <option data-id="aquatic_center" value="1">Aquatic Center</option>
    <option data-id="community_center" value="1">Community Center</option>
    <option data-id="youth_playground" value="1">Youth Playground</option>
    <option data-id="dog_park" value="1">Dog Park</option>
    <option data-id="restrooms" value="1">Restrooms</option>
    <option data-id="family_picnic_areas" value="1">Family Picnic Areas</option>
    <option data-id="group_picnic_areas" value="1">Group Picnic Areas</option>
    <option data-id="baseball_fields" value="1">Baseball Fields</option>
    <option data-id="soccer_fields" value="1">Soccer Fields</option>
    <option data-id="tennis_courts" value="1">Tennis Courts</option>
    <option data-id="horseshoe_courts" value="1">Horseshoe Courts</option>
  </select>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

see JSfiddle here。我能够让过滤器单独工作,但我不能让m像他们应该的那样堆叠。为简单起见,我已将JSON直接粘贴到JavaScript中。

1 个答案:

答案 0 :(得分:1)

@treighton尝试设置标记,其中包含一些细节以用于测试目的,例如:

data-toggle="modal" data-target="#myModal"

在这里,我们在每个标记中标记了标题,位置,类别和城市。更少的代码/行类型意味着更高的百分比来查明问题的原因。 现在已经完成了一些过滤器的标记,我们现在创建了一个过滤(隐藏和显示)标记的函数。

marker1 = new google.maps.Marker({
            title : title,
            position : pos,
            category : category,
            city : city,
            map : map
        });