Why MapLibre Instead of Leaflet on the Frontend

Leaflet renders maps using raster tiles — pre-rendered PNG images from a tile server. The colors on those images are fixed. MapLibre GL JS renders maps using vector tiles — raw geometry data — combined with a style JSON you write yourself. Every road color, water color, building color, and label style is defined in that JSON. If you need full color control over the base map, MapLibre is the only open-source option that delivers it without depending on a paid tile provider.

Enqueuing MapLibre in WordPress

MapLibre GL JS is loaded from a CDN and enqueued only on pages that contain the [map10] shortcode. The shortcode handler sets a flag when it runs, and the wp_footer hook checks that flag before enqueuing. This avoids loading MapLibre on every page of the site.

function map10_enqueue_frontend_assets() {
  if ( ! defined( 'MAP10_SHORTCODE_USED' ) ) return;

  wp_enqueue_style(
    'maplibre-gl',
    'https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css',
    [], '4.7.1'
  );
  wp_enqueue_script(
    'maplibre-gl',
    'https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js',
    [], '4.7.1', true
  );
  wp_enqueue_script(
    'map10-map',
    MAP10_URL . 'public/js/map.js',
    ['maplibre-gl'], MAP10_VERSION, true
  );
}
add_action( 'wp_footer', 'map10_enqueue_frontend_assets' );

Building the Style JSON with OpenFreeMap

OpenFreeMap provides free vector tiles with no API key and no usage limits for reasonable traffic. The map is initialized with a style URL pointing to OpenFreeMap’s Liberty style, which is then customized by overriding specific layer paint properties after the map loads. This approach — loading a base style and then modifying specific layers — is simpler than writing a complete style JSON from scratch.

const map = new maplibregl.Map({
  container: containerId,
  style: 'https://tiles.openfreemap.org/styles/liberty',
  center: [mapData.lng, mapData.lat],
  zoom: mapData.zoom,
});

After the load event fires, color overrides are applied using map.setPaintProperty(). This targets individual layers by their ID in the OpenFreeMap Liberty style. The layer IDs are stable across tile versions, so hardcoding them is acceptable for this use case.

This article is part of our complete guide:

How to Build an Interactive Map Plugin for WordPress from Scratch

Read the full guide →