Filter within a Layer

This example shows how to filter a layer based on user input using setFilter(). Download the earthquake sample data.

NPM module setup


npm install --save @maptiler/sdk
import { Map, MapStyle, config } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';

config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';

const data = {};

const map = new Map({
  container: 'map',
  style: MapStyle.DATAVIZ.DARK,
  center: [-156.6, 44],
  zoom: 1.6,
});

map.on('load', async function () {
  await maptilersdk.helpers.addPoint(map, {
    layerId: 'earthquakes',
    data: 'YOUR_MAPTILER_DATASET_ID_HERE',
    pointColor: '#FB3A1B',
    pointRadius: 40
  });

});

document.getElementById('nav-filter').addEventListener('change', (e) => {
  let filterOnValue = ['all'];
  let operator = '==';

  switch (e.target.id) {
    /// example: `map.setFilter("earthquakes", ["any", [">", "felt", 16.0]])`
    case 'felt':
      operatorFelt = document.getElementById('operator-felt');
      felt = document.getElementById('range-felt');
      operator = operatorFelt.value;

      // eslint-disable-next-line no-unused-expressions
      e.target.checked ? data.felt = Number(felt.value) : delete data['felt'];

      break;

    /// example: `map.setFilter("earthquakes", ["any", [">", "mag", 5.0]])`
    case 'mag':
      operatorMag = document.getElementById('operator-mag');
      mag = document.getElementById('range-mag');
      operator = operatorMag.value;

      // eslint-disable-next-line no-unused-expressions
      e.target.checked ? data.mag = Number(mag.value) : delete data['mag'];

      break;

    /// example: `map.setFilter("earthquakes", ["any", [">", "tsunami", 0]])`
    case 'tsunami':
      // eslint-disable-next-line @typescript-eslint/quotes
      tsunami = document.querySelector("input[type='radio'][name=tsunami]:checked");
      operator = '==';

      // eslint-disable-next-line no-unused-expressions
      e.target.checked ? data.tsunami = Number(tsunami.value) : delete data['tsunami'];

      break;
    default:
      console.log('default');
  }

  filterOnValue = Object.keys(data);

  mapLibreFilterSpread = ['all', ...filterOnValue.map(id => [operator, id, data[id]])];
  mapLibreFilter = mapLibreFilterSpread;

  document.getElementById('filter-result').textContent = JSON.stringify(mapLibreFilter);

  map.setFilter('earthquakes', mapLibreFilter);
});
Filter symbols by text input

Filter symbols by text input

Examples

Filter symbols by typing names into a text input.

Point filtering by property

Point filtering by property

Examples

Filter features in real time by property.

Create a time slider

Create a time slider

Examples

Visualize and filter earthquake data using a time slider.

Point layer colored and sized according to a property (point helper)

Point layer colored and sized according to a property (point helper)

Examples

Style point layer by property using point helper.

Was this helpful?