I want to create a location picker including the search field to focus on an area. So when the user doesn't know about the address, he can pick on the map or search the area first on the search field before picking the address on map.
I want to create a location picker including the search field to focus on an area. So when the user doesn't know about the address, he can pick on the map or search the area first on the search field before picking the address on map.
In this example, when the user picks the map's location, the fetch function will be triggered to get the address based on coordinate (lng,lat) as the parameter.
<head>
<link href='https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css' rel='stylesheet' />
<script src='https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.js'></script>
<link rel="stylesheet"
href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.5.1/mapbox-gl-geocoder.css"
type="text/css">
<script
src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.5.1/mapbox-gl-geocoder.min.js"></script>
</head>
<body>
<div id="map" style="width: 400px;height: 400px;"></div>
<br>
<input type="text" id="address">
</body>
<script>
mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN';
var map = new mapboxgl.Map({
container: 'map', //id element html
style: 'mapbox://styles/mapbox/streets-v11',
zoom: 9 // starting zoom
});
var geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl,
marker: false,
zoom: 20
});
map.addControl(
geocoder
);
let marker = null
map.on('click', function (e) {
mapClickFn(e.lngLat);
if (marker == null) {
marker = new mapboxgl.Marker()
.setLngLat(e.lngLat)
.addTo(map);
} else {
marker.setLngLat(e.lngLat)
}
});
function mapClickFn(coordinates) {
const url =
"https://api.mapbox.com/geocoding/v5/mapbox.places/" +
coordinates.lng +
"," +
coordinates.lat +
".json?access_token=" +
mapboxgl.accessToken
fetch(url).then(res => res.json()).then((data) => {
if (data.features.length > 0) {
const address = data.features[0].place_name;
document.getElementById("coordinate").value = address;
} else {
document.getElementById("coordinate").value = "No address found";
}
});
}
</script>