> For the complete documentation index, see [llms.txt](https://wpmaps-docs.mapster.me/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wpmaps-docs.mapster.me/mapster-wp-maps-v2/developer/examples.md).

# Examples

## Fly to a Location on External Element Click

A common pattern is building a sidebar or list where clicking an item flies the map to the corresponding feature. This example uses location IDs from the WordPress backend to match list items to map features.

```html
<!-- HTML: list items with IDs matching location post IDs -->
<div>
  <p class="map-office" id="map-office-578">Mount Vernon Office</p>
  <p class="map-office" id="map-office-577">Puyallup Office</p>
</div>

<script>
window.mwm_v2.onload(() => {
  window.mwm_v2.add_action('features:rendered', ({ map, features }) => {
    document.querySelectorAll('.map-office').forEach(el => {
      el.addEventListener('click', () => {
        const id = parseInt(el.id.replace('map-office-', ''));
        const feature = features.find(f => f.id === id);
        if (feature) {
          map.flyTo({ center: feature.data.location.coordinates, zoom: 12 });
        }
      });
    });
  });
});
</script>
```

## Run Code Only on a Specific Map

On pages with multiple maps, use `config.id` to target one:

```js
window.mwm_v2.onload(() => {
  window.mwm_v2.add_action('map:loaded', ({ map, config }) => {
    if (config.id !== 42) return;
    // only runs for the map with WordPress ID 42
    map.setZoom(10);
  });
});
```

## Show and Hide Layers on Button Click

```html
<button id="hide-btn">Hide Features</button>
<button id="show-btn">Show Features</button>

<script>
window.mwm_v2.onload(() => {
  window.mwm_v2.add_action('features:rendered', ({ map }) => {
    // Use the native library to toggle layer visibility directly
    document.getElementById('hide-btn').addEventListener('click', () => {
      map.setLayoutProperty('your-layer-id', 'visibility', 'none');
    });
    document.getElementById('show-btn').addEventListener('click', () => {
      map.setLayoutProperty('your-layer-id', 'visibility', 'visible');
    });
  });
});
</script>
```

## Attach a Native Map Event Listener

For interaction detail not available through the `add_action` API (such as which specific feature was clicked), attach listeners directly to the `map` object using the native library's event API:

```js
window.mwm_v2.onload(() => {
  window.mwm_v2.add_action('map:loaded', ({ map }) => {
    // MapLibre / Mapbox GL JS native event
    map.on('click', (e) => {
      const features = map.queryRenderedFeatures(e.point);
      if (features.length > 0) {
        console.log('Clicked feature:', features[0]);
      }
    });
  });
});
```
