Filed under Leaflet

Import JSON Data from an External File in Leaflet

If your JSON or GeoJSON data is long, you might want to store it in a separate file to make your code more readable or to reduce repetition and allow you to access the same data file from multiple pages. You can do that with jQuery.

First, load jQuery 1.10.2 or the newest version of jQuery (2.0 onward does not support Internet Explorer 6, 7, or 8) in the header:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Next, in your leaflet script at the bottom of the body, you'll need to add all your other code and your basemap, like normal, for example:

var map = L.map('map').setView([38.0740, -55], 3);

function onEachFeature(feature, layer) {
    layer.bindPopup(feature.properties.City + ", " + feature.properties.State + ", " + feature.properties.Country);
}

Then, you can just use jQuery to get the JSON or GeoJSON file. A simple version of this would be:

$.getJSON("cities.geoJSON", function (cities) {
    L.geoJson(cities).addTo(map);
})

But you can also add more options to your L.geoJson code, just like you would if using data stored in the HTML file. For example:

$.getJSON("cities.geoJSON", function (cities) {
    L.geoJson(cities, {
        onEachFeature: onEachFeature,
        pointToLayer: function (feature, latlng) {
            switch (feature.properties.Remember) {
                case '1': return L.marker(latlng, {icon: visitedIcon});
                case '?': return L.marker(latlng, {icon: uncertainIcon});
                case '0': return L.marker(latlng, {icon: uncertainIcon});
            }
        }
    }).addTo(map);
})

So just a couple lines of jQuery allow you to store your JSON or GeoJSON data in a separate file.

The example code is available in a gist and the example is viewable here.

Further Reading

Tagged , , , , , ,

Make All Polygons the Same Shade in Leaflet

The Quick Start tutorial shows us how to change the color of a polygon:

var circle = L.circle([51.508, -0.11], 500, {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5
}).addTo(map);

But what if we want to change the color and style of all (or a set of the) polygons?

First we can define the style:

var defaultStyle = {
    color: 'green',
    fillOpacity: 0.2
};

And then we can just add that style to our polygons:

var polygon = L.polygon([
    [51.509, -0.08],
    [51.503, -0.06],
    [51.51, -0.047]
]).setStyle(defaultStyle).addTo(map);

var circle = L.circle([51.508, -0.11], 500).setStyle(defaultStyle).addTo(map);

The full code (based on the Quick Start tutorial) is available in a gist.

Tagged , , ,