MapSnippets logoMapSnippets logo

Load GeoJSON Source in MapLibre GL JS

MapLibre GL JS

Fetch a remote GeoJSON file and add it as a source with styled layers on a MapLibre GL JS map.

progress_activityLoading map...
const map = new maplibregl.Map({
  container: 'map',
  style: 'https://api.maptiler.com/maps/streets-v4/style.json?key=YOUR_MAPTILER_KEY',
  center: [-100, 40],
  zoom: 3
});
map.on('load', async () => {
  const res = await fetch('https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_admin_1_states_provinces_shp.geojson');
  const data = await res.json();
  map.addSource('states', { type: 'geojson', data });
  const labels = map.getStyle().layers.find(l => l.type === 'symbol' && /label/.test(l.id));
  map.addLayer({ id: 'states-fill', type: 'fill', source: 'states',
    paint: { 'fill-color': '#6366f1', 'fill-opacity': 0.15 }
  }, labels ? labels.id : undefined);
  map.addLayer({ id: 'states-border', type: 'line', source: 'states',
    paint: { 'line-color': '#6366f1', 'line-width': 1 } });
  map.on('click', 'states-fill', (e) => {
    const f = e.features[0];
    new maplibregl.Popup().setLngLat(e.lngLat).setHTML(`<b>${f.properties.name || 'Unknown'}</b>`).addTo(map);
  });
  map.on('mouseenter', 'states-fill', () => { map.getCanvas().style.cursor = 'pointer'; });
  map.on('mouseleave', 'states-fill', () => { map.getCanvas().style.cursor = ''; });
});

How it works

MapLibre can load GeoJSON data from any URL. Fetch the file with the Fetch API, parse it, and pass the result directly to addSource(). The source accepts a parsed GeoJSON object or a URL string.

This example loads Natural Earth state/province boundaries and renders them as a semi-transparent fill with borders. Clicking a state shows its name in a popup. The fill layer is inserted below labels for readability.

For large GeoJSON files, consider using a URL string directly in the source data property instead of fetching manually: MapLibre handles the request and can better manage memory.

Key APIs

API Description Docs
map.addSource() Add a data source maplibre.org docs
type: 'geojson' GeoJSON source type maplibre.org docs
queryRenderedFeatures() Get features at a point maplibre.org docs

FAQ

Can I pass a URL directly to the source instead of fetching?

Yes. Set data: 'https://example.com/data.geojson' on the source and MapLibre will fetch it automatically.

How do I update the GeoJSON data later?

Call map.getSource('states').setData(newData) to replace the source data at any time.

Common mistakes

  • Loading very large GeoJSON files (>10 MB): consider using vector tiles instead
  • Not inserting fill layers below labels: data covers map text
  • Forgetting to handle fetch errors: wrap in try/catch for network issues
auto_awesome

Build maps using MapLibre GL JS with AI

Generate code like this load geojson source in maplibre gl js example using the MapLibre GL JS skill in your IDE.