I am using Mapbox GL JS to show certain location marked on the map. I need to set location through JavaScript code and I don't know the lat and long coordinates, I only have an address in string form (example: "address, city, country" or some similar format).
I have searched a lot on the internet, but the only way that I have found for doing this in Mapbox GL JS is by using Geocoder input control, but I don't want to input location through it, I want to set Address through code and then have it marked on map when the map loads.
Is it possible to do this in Mapbox GL without knowing lat and long coordinates? How can I do that?
Thanks in advance! Best regards!
You can use the Mapbox Geocoding API without the Geocoder control. You have to compose your url (and encode it).
Always consider you could get more than one result in the featureCollection response depending your params, so finally you have to refine the results with some of the attributes allowed such as proximity
and limit
. At the beginning is a bit of try and error task, but after some practice it's quite accurate.
Here you have an example url for the address 123 Main St Boston MA 02111
, filtering the results in United States only.
https://api.mapbox.com/geocoding/v5/mapbox.places/123%20Main%20St%20Boston%20MA.json?country=US&access_token=PASTE_YOUR_TOKEN_HERE
This will return 5 streets in the Massachusetts state.
I recommend you to read the documentation in forward geocoding, and also the section on address geocoding format to compose properly the url.