Toggle hide/show Google map markers

前端 未结 2 1839
一向
一向 2021-01-03 14:04

I have a custom Google map with markers of artist locations. I want to make 8 different categories of markers. I read about having to make arrays of markers and assigning a

相关标签:
2条回答
  • 2021-01-03 14:18

    The best way to create different arrays of markers is to do something like this. You said you had 8 categories of markers, so do this 8 times.

    var locations = [
    
                     ['Shanghai', 31.232, 121.47, 5885],
                     ['Beijing', 39.88, 116.40, 6426],
                     ['Guangzhou', 23.129, 113.264, 4067],
                     ['Shenzhen', 22.54, 114.05, 3089],
                     ['Hangzhou', 30.27, 120.15, 954],
                     ['Hong Kong', 22.39, 114.10, 1885]
                   ];
    
    function getMarkers() {
        for (i = 0; i < locations.length; i++) { 
                marker[i] = new MarkerWithLabel({
                    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                    draggable: false,
                    map: map,
                        labelContent: locationsCA[i][3],
                    icon: new google.maps.MarkerImage(iconArray[i]),
                    labelAnchor: new google.maps.Point(30, 0),
                    labelClass: "labels", // the CSS class for the label
                     labelStyle: {opacity: 0.75}
                });
    

    As for your second question about toggle visibility with check boxes, I don't know how to make check boxes, but the toggle feature can be easily implemented with an event trigger. Whether it is a marker click or a zoom, or any other event (check the documentation for events), you get set up an action following that event. Here is an example.

    google.maps.event.addListener(map,'zoom_changed',function () {
             if (map.getZoom() >= 4) {
                hideMarkers();          
             }
    }
    

    And your hideMarkers() function with use this command to make it invisible

    marker.setVisible(false);
    

    Hope that helps

    0 讨论(0)
  • 2021-01-03 14:27

    you can store them in an array and toggle the visbility with marker.setMap(null) for invisible and marker.setMap(map) for visible.

    see the example from the docs: https://developers.google.com/maps/documentation/javascript/examples/marker-remove

    0 讨论(0)
提交回复
热议问题