I want to search address using geolocation and user selects any address, then it should show location in map as well get coordinates and then display in latitude and longitude textbox.
Here code that I tried for implementation.
Related Links
<link href="https://api.mapbox.com/mapbox-gl-js/v2.10.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.10.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/mapbox-gl-geocoder.css" type="text/css">
<script src="https://unpkg.com/@mapbox/mapbox-sdk/umd/mapbox-sdk.min.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/mapbox-gl-geocoder.min.js"></script>
Html & javascript
<div class="row">
<div class="col-md-12">
<div style="position:relative;margin:1rem 0;">
<div class="form-group">
<label for="address">@lang('Location')</label>
<div id="geocoder" class="geocoder"></div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="latitude">@lang('Latitude')</label>
<input type="text" id="latitude" name="latitude" class="form-control"
value="{{ old('latitude') }}">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="longitude">@lang('Longitude')</label>
<input type="text" id="longitude" name="longitude" class="form-control"
value="{{ old('longitude') }}">
</div>
</div>
</div>
<div id="map"></div>
</div>
</div>
</div>
</div>
mapboxgl.accessToken = '';
const map = new mapboxgl.Map({
container: 'map',
// Choose from Mapbox's core styles, or make your own style with Mapbox Studio
style: 'mapbox://styles/mapbox/streets-v11',
center: [-79.4512, 43.6568],
zoom: 13
});
// Add the control to the map.
const geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl
});
geocoder.on('result', (event) => {
console.log(event.result.geometry);
$('#longitude').val(event.result.geometry.coordinates[0]);
$('#latitude').val(event.result.geometry.coordinates[1]);
});
document.getElementById('geocoder').appendChild(geocoder.onAdd(map));
Since I am storing location in database I cannot fetch it doesn't have name on it and it auto built from the mapbox.
I wanted like this, If I have textbox, when I type on it, it shows multiple options like 'geolocation', then selects, it shows location on map and as well coordinates.