Add markers on the fly to geoJSON array with mapbox-gl-js -
i've seen several examples of mapbox maps multiple markers marker locations pre-programmed geojson array such 1 here.
i'd able add marker map via method , keep existing markers. markers created built-in geocoder search. seems possible old mapbox.js along lines of this:
l.geojson(geojsonfeature, { ... }).addto(map);
however, cannot seem find documentation such method/functionality mapbox-gl-js. i'd able keep track of these markers , edit/delete them in fiddle. missing something?
here current code works 1 marker. if add new marker, replaces old. i'd keep adding them 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); }); });
this code structured lines
var el = document.createelement('div'); el.id = 'marker'; var markerobject;
outside of geocoder.on('result'
method. if want new marker added every time callback provided geojson.on('result'
fires, issue: you're trying use same div
element multiple markers. mapbox gl js doesn't clone or duplicate element you: expectation element argument of new mapboxgl.marker
new element.
so, fix issue, move above lines inside of callback geocoder.on('result'
.
Comments
Post a Comment