An Update to Working with GeoJSON in the Browser

By Raymond Camden | 18 August 2020

A few weeks ago, I wrote a blog post about working with GeoJSON entirely within the browser (Working with GeoJSON in the Browser). In that article, I presented the different ways of working with GeoJSON using JavaScript in the browser. In the second example, I demonstrate how to load data from a GeoJSON file and display it using our JavaScript Maps API. As it turns out, learning never ends and I discovered there was an even easier way. Let me show you how!

So for reference, here's the approach I took in that first post:

var icon = new H.map.Icon('park.png');

let resp = await fetch('./national-parks.geojson');
let data = await resp.json();

data.features.forEach(f => {
    map.addObject(new H.map.Marker({lat:f.geometry.coordinates[1], lng:f.geometry.coordinates[0]}, { icon:icon}));
});

One of the engineers on the MapsJS product reached out and they shared that I had missed out on a featured called the GeoJSON Reader. Let's make sure that you don’t miss out on this feature like I did as it provides a great shortcut. It lets you add a layer of GeoJSON data in three simple lines:

let reader = new H.data.geojson.Reader('/path/to/geojson/file.json');
reader.parse();
map.addLayer(reader.getLayer());

While not much shorter than before, it's certainly a bit simpler. One possible issue with this code block is that uses the default the marker object icons. If you remember, my demo had a custom park icon. Luckily that's also pretty easy to implement. The Reader constructor supports an options object that lets you pass a styling function. Here's an example of that:

var icon = new H.map.Icon('park.png');
let reader = new H.data.geojson.Reader('./national-parks.geojson', {
    style(mapObject) {
        if(mapObject instanceof H.map.Marker) {
            mapObject.setIcon(icon);
        }
    }, disableLegacyMode: true
});

reader.parse();
map.addLayer(reader.getLayer());

The styling function is passed every object that's created on this particular layer, so you'll notice a bit of code that checks to ensure the object is a marker first. Certainly, more could be done here than just setting an icon. The data from your features will be available via mapObject.getData() letting you inspect and react to different values set within them.

You can see another example of the GeoJSON reader in our examples and don't forget you can peruse the entire JavaScript Maps API Reference to find cool features like this.

The complete source code for this demo may be found here: https://github.com/cfjedimaster/heredemos/blob/master/mapsjs/test_markers_from_geojson2.html You can run this demo in your browser here: https://cfjedimaster.github.io/heredemos/mapsjs/test_markers_from_geojson2.html Don't forget you can sign up for a free developer account and begin building your own maps today!