Reputation: 1573
How can I use Mapbox Geocoder without map?
When I remove the map code, the autocomplete text field disappears.
What I have tried is (Which is not working for me):
<div id="geocoder"></div>
mapboxgl.accessToken = 'pk.eyJ1IjoiaGFzc2Fuc2FyZGFyYmFuZ2FzaCIsImEiOiJjazg3MHNldWowbGllM2hvMGloMGY0MXd0In0.baO5lzQ8q4al4T0rDAloQA';
var geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl
});
geocoder.on('select', function (data) {
geocoder._toggle()
})
geocoder.on('result', function(result) {
console.log(result);
})
document.getElementById('geocoder');
How can I manage to use only Geocoder autocomplete, with out showing map?
Here is my working fiddle:
https://jsfiddle.net/rv085oL1/
Upvotes: 1
Views: 1214
Reputation: 23
If you are looking for a react implementation of a geocoder without a map:
https://www.npmjs.com/package/react-geocoder-mapbox
It does not look pretty, but you can style it with CSS :)
In the project directory:
npm i --save react-geocoder-mapbox
Inside of the component you want the geocoder:
import Geocoder from "react-geocoder-mapbox";
Include the component in your app:
export const GeocoderWithoutMap = () => {
const [geocode, setGeocode] = useState();
useEffect(() => {
console.log(geocode);
}, [geocode]);
return (
<Geocoder
accessToken={TOKEN}
onSelect={geocoderObject => { setGeocode(geocoderObject);}}
/>
);
};
I hope this saves you the time I spent searching!
Upvotes: 0
Reputation: 1299
The documentation for mapbox/mapbox-gl-geocoder
here explains how to add a geocoder without a map. That is, the JavaScript in your JSFiddle should be updated to:
var geocoder = new MapboxGeocoder({ accessToken: mapboxgl.accessToken });
geocoder.addTo('#geocoder');
Also, you'll need to update your mapbox-gl-geocoder
version to at least v4.5.0
. This is the version in which the addTo
method was integrated, as noted in the changelog here.
Upvotes: 3