Skip to content

Leaflet.js GeoJSON — Rendering Geographic Data

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about Leaflet.js GeoJSON. We cover key concepts, practical examples, and best practices to help you master this topic.

Leaflet.js GeoJSON layer renders geographic features from GeoJSON format, supporting points, lines, polygons, and multi-geometries with full styling control.

What You'll Learn

By the end of this guide, you will load GeoJSON data from files and APIs, style features based on properties, bind interactive popups, filter features, and build a choropleth map.

Basic GeoJSON

fetch('data.geojson')
    .then(function(res) { return res.json(); })
    .then(function(data) {
        L.geoJSON(data).addTo(map);
    });

Feature Styling

L.geoJSON(data, {
    style: function(feature) {
        return {
            fillColor: feature.properties.value > 50 ? '#ff6b35' : '#4ecdc4',
            weight: 2,
            opacity: 1,
            color: '#fff',
            fillOpacity: 0.7
        };
    }
}).addTo(map);
L.geoJSON(data, {
    onEachFeature: function(feature, layer) {
        layer.bindPopup(
            '<strong>' + feature.properties.name + '</strong><br>' +
            'Population: ' + feature.properties.population
        );
    }
}).addTo(map);

Feature Filtering

L.geoJSON(data, {
    filter: function(feature) {
        return feature.properties.population >= 100000;
    }
}).addTo(map);

Common Mistakes

1. Invalid GeoJSON Structure

GeoJSON requires type: "FeatureCollection" with features array. Single features must be wrapped in a FeatureCollection.

2. Coordinate Order: [lng, lat]

GeoJSON uses [longitude, latitude] order. Leaflet uses [latitude, longitude]. GeoJSON loaded via L.geoJSON handles this.

3. Missing Null Checks

Feature properties may be null. Always check before accessing nested properties.

4. Large Files Blocking UI

Large GeoJSON files (>5MB) block the main thread. Use simplify or load with a Web Worker.

5. Style Function Returning Undefined

Style function must return an object for every feature. Return a default for features without styling properties.

Practice Questions

Q1: What coordinate order does GeoJSON use? A: [longitude, latitude], the reverse of Leaflet's [lat, lng].

Q2: How do you apply different styles per feature? A: Use the style function that receives each feature and returns style options based on properties.

Q3: How do you filter features? A: Use the filter option with a function that returns true/false per feature.

Q4: What is pointToLayer used for? A: To customize how point features are rendered (e.g., use L.circleMarker instead of default marker).

Q5: How do you update GeoJSON data? A: Call geoJsonLayer.clearLayers() then geoJsonLayer.addData(newData).

Challenge: Build a choropleth map of US states colored by population density. Add a legend showing the color ranges on hover.

FAQ

Can I load GeoJSON from a file?

Yes. Use fetch() or a file input to load .geojson files. Leaflet parses them automatically.

How do I handle coordinate precision?

Leaflet handles projection automatically. For display, set L.CRS to EPSG4326 if your data is in lat/lng.

What is the recommended GeoJSON file size?

Under 1MB for fast initial load. Use TopoJSON or vector tiles for larger datasets.

Can I style lines differently from polygons?

Use pointToLayer for points and style for lines/polygons. Check feature.geometry.type in your function.

How do I animate GeoJSON features?

Add CSS transitions on SVG path elements, or use L.polyline with animate options.

Try It Yourself

Build a GeoJSON map with styled polygons and popups.

<!DOCTYPE html>
<html>
<head>
    <title>GeoJSON Demo</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.9/dist/leaflet.js"></script>
</head>
<body style="font-family:sans-serif;padding:20px;">
<h2>GeoJSON Map</h2>
<div id="map" style="height:400px;border-radius:8px;"></div>
<script>
var map = L.map('map').setView([39.8283, -98.5795], 4);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; OpenStreetMap'
}).addTo(map);

var sampleData = {
    type: 'FeatureCollection',
    features: [
        {
            type: 'Feature',
            properties: { name: 'Region A', value: 75 },
            geometry: { type: 'Polygon', coordinates: [[[-100, 40], [-95, 40], [-95, 45], [-100, 45], [-100, 40]]] }
        },
        {
            type: 'Feature',
            properties: { name: 'Region B', value: 30 },
            geometry: { type: 'Polygon', coordinates: [[[-95, 40], [-90, 40], [-90, 45], [-95, 45], [-95, 40]]] }
        }
    ]
};

L.geoJSON(sampleData, {
    style: function(f) {
        return {
            fillColor: f.properties.value > 50 ? '#ff6b35' : '#4ecdc4',
            fillOpacity: 0.6,
            color: '#fff',
            weight: 2
        };
    },
    onEachFeature: function(f, layer) {
        layer.bindPopup('<b>' + f.properties.name + '</b><br>Value: ' + f.properties.value);
    }
}).addTo(map);
</script>
</body>
</html>

What's Next

Cluster many markers.

Clustering — Marker clustering. Heatmap — Heatmap visualization.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro