1
votes

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);
   });
});
1

1 Answers

0
votes

This code is structured with the lines

var el = document.createElement('div');
el.id = 'marker';
var markerObject;   

outside of the geocoder.on('result' method. If you want a new marker added every time that the callback provided to geojson.on('result' fires, then this is the issue: you're trying to use the same div element for multiple markers. Mapbox GL JS doesn't clone or duplicate that element for you: the expectation is that the element argument of a new mapboxgl.Marker is a new element.

So, to fix this issue, you would move the above lines inside of the callback for geocoder.on('result'.