I've seen several examples of Mapbox maps with multiple markers but the marker locations are pre-programmed into a geoJSON array such as the one here.
I'd like to be able to add a marker to the map via a method and keep existing markers. The markers would be created from the built-in geocoder search. It seems like it is possible with the old mapbox.js with something along the lines of this:
L.geoJson(geojsonFeature, { ... }).addTo(map);
However, I cannot seem to find documentation for such a method/functionality with mapbox-gl-js. I'd like to be able to keep track of these markers and edit/delete them like in this fiddle. Am I missing something?
Here is my current code that only works with one marker. If you add a new marker, it currently replaces the old. I'd like to keep adding them from the geocoder hook:
mapboxgl.accessToken = 'xxx';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-79.4512, 43.6568],
zoom: 13
});
var geocoder = new mapboxgl.Geocoder({
container: 'geocoder-container'
});
map.addControl(geocoder);
map.on('load', function() {
map.addSource('single-point', {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": []
}
});
map.addLayer({
"id": "point",
"source": "single-point",
"type": "circle",
"paint": {
"circle-radius": 5,
"circle-color": "#007cbf"
}
});
var el = document.createElement('div');
el.id = 'marker';
var markerObject;
map.addControl(new mapboxgl.NavigationControl());
geocoder.on('result', function(ev) {
var placeName = JSON.stringify(ev.result.place_name);
console.log(placeName);
var popup = new mapboxgl.Popup({offset:[0, -30]})
.setText(ev.result.place_name);
markerObject = new mapboxgl.Marker(el, {offset:[-25, -25]})
.setLngLat(ev.result.geometry.coordinates)
.setPopup(popup)
.addTo(map);
});
});