essmahr
essmahr

Reputation: 676

getBounds() of defined group of markers

I'm wanting to zoom a mapBox map to a specific group of markers based on a shared property.

I have a map with a bunch of markers, and from that group I've built two arrays for two separate regions like so:

var regionOne = [], regionTwo = [];

map.markerLayer.on('layeradd', function(e){

  var marker = e.layer,
      feature = marker.feature;

   switch (feature.properties.region) {
      case 'region-one':
        regionOne.push(feature);
        break;
      case 'region-two':
        regionTwo.push(feature);
        break;
    }
});

but I am stuck on next steps. I need to convert the array of marker objects to a featureGroup (as described here and documented in the leaflet docs) so I can apply the getBounds() method but just running

var regionGroup = new L.featureGroup(regionOne);

throws an error, even though regionOne is a valid array of mabox marker objects.

Upvotes: 0

Views: 906

Answers (1)

patsweet
patsweet

Reputation: 1558

Are you sure your regionOne and regionTwo arrays are populated?

It doesn't appear that the feature object is accessible in your function. Give this a shot:

map.markerLayer.on('layeradd', function(e){
   var layer = e.layer;
   switch (layer.properties.region) {
      case 'region-one':
        regionOne.push(layer);
        break;
      case 'region-two':
        regionTwo.push(layer);
        break;
    }
});

EDIT:

Need to assign the layer to each array, not the feature.

var regionOne = [], regionTwo = [];

map.markerLayer.on('layeradd', function(e){

  var marker = e.layer,
      feature = marker.feature;

   switch (feature.properties.region) {
      case 'region-one':
        regionOne.push(marker);
        break;
      case 'region-two':
        regionTwo.push(marker);
        break;
    }
});

Upvotes: 1

Related Questions