Mapbox GL JS and GeoJSON as an external file

George Kiosov picture George Kiosov · Aug 6, 2017 · Viewed 8.8k times · Source

I have code to set markers with Mapbox map

$(function() {
    mapboxgl.accessToken = 'pk.###';

    var map = new mapboxgl.Map({
        container: 'map-global',
        style: '..'
    });

    var geojson = {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "properties": {
                    "title": "POI Title"
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [0, 0]
                }
            }
        ]
    };

    geojson.features.forEach(function(marker) {
        // create a HTML element for each feature
        var el = document.createElement('div');
        el.className = 'marker';
        new mapboxgl.Marker(el)
            .setLngLat(marker.geometry.coordinates)
            .setPopup(new mapboxgl.Popup()
            .setHTML(marker.properties.title))
            .addTo(map);        
    });
});

And it works fine. But I want to use GeoJSON as an external file:

var geojson = 'file.geojson';

And here I have a problem — it doesn't work:

TypeError: undefined is not an object (evaluating '"map.geojson".features.forEach')".

Is there any way to use external GeoJSON file with custom HTML markers?

Answer

Andi-lo picture Andi-lo · Aug 7, 2017

You can load external geojson files with plain mapbox addSource().

map.on('load', function() {
  var url = 'http://your_geojson_file.com/some_file.geojson';
  map.addSource('source_id', { type: 'geojson', data: url});
});

See this example: https://www.mapbox.com/mapbox-gl-js/example/live-geojson/