Google Maps marker grouping

前端 未结 2 759
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 10:54

I\'m trying to achieve the following thing: Have different types of markers on my map for example, schools, libraries, bus stops and I want to be able to show/hide each grou

2条回答
  •  误落风尘
    2020-12-15 11:04

    There are various ways to tackle this, but let me show you one approach.

    First, let's start with an array of locations (borrowed from the Google Maps API Tutorials):

    var beaches = [
      ['Bondi Beach', -33.890542, 151.274856, 1],
      ['Coogee Beach', -33.923036, 151.259052, 1],
      ['Cronulla Beach', -34.028249, 151.157507, 2],
      ['Manly Beach', -33.800101, 151.287478, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 2]
    ];
    

    This is actually an array of arrays. It represents 5 Australian beaches, and we have the name, latitude, longitude and category. The category in this case is just a number for the sake of simplicity.

    Then it is important that we keep a reference of the markers that we create. To do this, we can use a markers array where we store each new marker, and we can also augment each marker object with its category id:

    var markers = [];
    
    var i, newMarker;
    
    for (i = 0; i < beaches.length; i++) {
      newMarker = new google.maps.Marker({
        position: new google.maps.LatLng(beaches[i][1], beaches[i][2]),
        map: map,
        title: beaches[i][0]
      });     
    
      newMarker.category = beaches[i][3];     
      newMarker.setVisible(false);
    
      markers.push(newMarker);
    }
    

    Finally, when we need to show the markers, we can simply iterate over the markers array, and call the setVisible() method according to what category we would like to show.

    You may want to check out the following complete example:

    
     
     
        
       Google Maps JavaScript API v3 Example: Marker Categories 
       
     
     
       

    Screenshot from the above example, after clicking on the "Show Group 2" button:

提交回复
热议问题