Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the mapbox geocoder?

I use the Mapbox Geocoder and additionally several select menus to customize a map. Now I want to reset the geocoder as soon as the user selects a value from the select menu - so the input field should be cleared and the marker removed.

In the Docs a clear function is described and there is also a clear button in the default input field, but this function doesn't work if I call it from a change event.

This is what my attemp looks like so far:


const select  = $('#select');
const control = $('#geocoder');

const geocoder = new MapboxGeocoder({
 accessToken: accessToken,
 mapboxgl: mapboxgl
});

//Add the geocoder
document.getElementById(control).appendChild(geocoder.onAdd(map));

//Now reset the geocoder if the user selects something
select.change(function() {
 geocoder.clear();
});

I expect the reset of the input field and the removal of the marker, but the actual output is "geocoder.clear is not a function"

like image 997
agssl Avatar asked May 07 '19 08:05

agssl


1 Answers

I had a similar issue with a react app that uses mapbox-gl. I got around it by defining the marker outside of the geocoder.on call. This is all inside of the componentDidMount method of the map component.

let marker = new mapboxgl.Marker({ draggable: false, color: "green" })

geocoder.on('result', function(e) {
  marker.setLngLat(e.result.center).addTo(map)
});
like image 144
Alex Avatar answered Nov 19 '22 09:11

Alex