MapSnippets logoMapSnippets logo

Load GeoJSON Data in Leaflet

Leaflet

Fetch a GeoJSON file and render its features on a Leaflet map with custom styling and interactive popups.

progress_activityLoading map...
const map = L.map('map').setView([50.0755, 14.4378], 6);
L.tileLayer('https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', {
  tileSize: 256,
  attribution: '&copy; <a href="https://www.maptiler.com/">MapTiler</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'
}).addTo(map);
const geojsonData = {
  type: 'FeatureCollection',
  features: [
    { type: 'Feature', properties: { name: 'Prague' }, geometry: { type: 'Point', coordinates: [14.4378, 50.0755] } },
    { type: 'Feature', properties: { name: 'Brno' }, geometry: { type: 'Point', coordinates: [16.6068, 49.1951] } },
    { type: 'Feature', properties: { name: 'Ostrava' }, geometry: { type: 'Point', coordinates: [18.2625, 49.8209] } },
    { type: 'Feature', properties: { name: 'Plzen' }, geometry: { type: 'Point', coordinates: [13.3776, 49.7384] } }
  ]
};
L.geoJSON(geojsonData, {
  pointToLayer: (f, latlng) => L.circleMarker(latlng, { radius: 8, fillColor: '#FF5722', color: '#fff', weight: 2, fillOpacity: 0.8 }),
  onEachFeature: (f, layer) => layer.bindPopup(f.properties.name)
}).addTo(map);

How it works

L.geoJSON() parses and renders GeoJSON data on the map. It handles the coordinate order conversion from GeoJSON’s [lng, lat] to Leaflet’s [lat, lng] automatically. The example uses inline GeoJSON, but you can also load from a URL with fetch().

The pointToLayer callback customizes how point features are rendered: here using circle markers instead of default pins. The onEachFeature callback attaches popups with the feature’s name property. For lines and polygons, use the style option instead.

Key APIs

API Description Docs
L.geoJSON() Render GeoJSON data leafletjs.com/reference.html#geojson
pointToLayer Custom point rendering leafletjs.com/reference.html#geojson-pointtolayer
L.circleMarker() Circle marker at point leafletjs.com/reference.html#circlemarker

FAQ

How do I load GeoJSON from a URL?

Use fetch('data.geojson').then(r => r.json()).then(data => L.geoJSON(data).addTo(map)).

Can I filter features before displaying?

Yes. Use the filter option: L.geoJSON(data, { filter: f => f.properties.population > 100000 }).

Common mistakes

  • Manually swapping GeoJSON coordinates: L.geoJSON() handles the [lng, lat] to [lat, lng] conversion automatically
  • Forgetting pointToLayer when you want styled points: the default is a standard marker icon
  • Not checking that the GeoJSON type is valid: Leaflet silently ignores malformed features
auto_awesome

Build maps using Leaflet with AI

Generate code like this load geojson data in leaflet example using the Leaflet skill in your IDE.