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?
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/