Google地图过滤基于标记属性

时间:2017-10-03 20:19:18

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

我正在尝试为我现有的Google地图JS添加过滤功能,但我真的不知道从哪里开始。下面的代码加载所有诊所,按钮需要匹配marker.specialties数组中的项目。如何在显示此功能时添加隐藏所有其他诊所的简单功能?

function loadPlaces(map, lat = 37.78099539999999, lng = -122.47150820000002) {
    var filters = { healthcare: false, denistry: false };
    // Filter trigger
    $$("input[name=filter]").on("change", function() {
        console.log("it runs");
        // let selectedFilter = this.id;
        if (this.id === "healthcare" && filters.healthcare === false) {
            filters.healthcare = true;
        } else {
            filters.healthcare = false;
        }

        // toggle
        // filters.healthcare = true;
        console.log(filters);
        // 2. Check vars and filter by which ones are true
        filterMarkers(filters);
    });

    axios.get(`/api/clinics/near?lat=${lat}&lng=${lng}`).then(res => {
        const places = res.data;
        if (!places.length) {
            alert("no places found!");
            return;
        }

        const bounds = new google.maps.LatLngBounds();
        const infoWindow = new google.maps.InfoWindow();

        const markers = places.map(place => {
            const [placeLng, placeLat] = place.location.coordinates;
            const position =  { lat: placeLat, lng: placeLng };
            const marker = new google.maps.Marker({
                map,
                position
            });
            bounds.extend(position);
            marker.place = place;
            return marker;
        });

        // when someone clicks ona a marker, show the details of that place
        markers.forEach(marker =>
            marker.addListener("click", function() {
                infoWindow.setContent(this.place.name);
                console.log(this.place);
                infoWindow.open(map, this);
            })
        );

        // zoom map to fit markers perfectly
        map.setCenter(bounds.getCenter());
        map.fitBounds(bounds);
    });
}

function makeMap(mapDiv) {
    if (!mapDiv) return;

    const map = new google.maps.Map(mapDiv, mapOptions);
    loadPlaces(map);

    const input = $("[name=geolocate]");
    const autocomplete = new google.maps.places.Autocomplete(input);
}

export default makeMap;

2 个答案:

答案 0 :(得分:1)

您需要setMap(null)为每个标记隐藏所有标记并setMap(map)支持您想要显示的标记。

https://developers.google.com/maps/documentation/javascript/examples/marker-remove

答案 1 :(得分:1)

只隐藏所有不需要的标记

function filter(markers) {
   for (var i = 0; i < markers.length; i++) {
      if(/* conditional statement to check whether you'll going to hide this marker */) {
           markers[i].setMap(null);
      }
   }
}

如果你想再次展示它

function showAllMarkers(markers, map) {
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(map);
    }
}