Mapbox: Filtering out markers in a Leaflet Omnivor

2019-09-19 11:04发布

问题:

I am exporting Google Directions routes as KML and displaying them on a Mapbox map by reading them with Omnivore and adding them to the map,

The Google KML stores each route as two Places (the start and end points) and one LineString (the route). In Mapbox I would like to show only the routes, that is to filter out the markers somehow. I'm displaying markers out of my own database and the Google markers clutter it up.

Here is my code. I change the styling of the LineStrings just to show that I can, but do not know what magic call(s) to make to not display the Points. Thanks.

runLayer = omnivore.kml('data/xxxx.kml')
  .on('ready', function() {
    var llBnds = runLayer.getBounds();
    map.fitBounds(llBnds);

    this.eachLayer(function (layer) {

      if (layer.feature.geometry.type == 'LineString') {
        layer.setStyle({
          color: '#4E3508', 
          weight: 4
        });
      }

      if (layer.feature.geometry.type == 'Point') {
        //
        // Do something useful here to not display these items!!
        //
      }                 
    });
  })
  .addTo(map);

回答1:

Welcome to SO!

Many possible solutions:

  • Most straight forward from the code you provided, just use the removeLayer method on your runLayer Layer Group when you get a 'Point' feature.

  • Cleaner solution would be to filter out those features before they are even converted into Leaflet layers, through a custom GeoJSON Layer Group passed as 3rd argument of omnivore.kml, with a specified filter option:

var customLayer = L.geoJSON(null, {
  filter: function(geoJsonFeature) {
    // my custom filter function: do not display Point type features.
    return geoJsonFeature.geometry.type !== 'Point';
  }
}).addTo(map);

var runLayer = omnivore.kml('data/xxxx.kml', null, customLayer);

You can also use the style and/or onEachFeature options on customLayer to directly apply your desired style on your LineString.