Getting the lat/long of the address searched with mapbox on the leaflet map

633 Views Asked by At

I have a scenario like this. The user is typing in the destination address. He chooses one of the addresses below the input. And I want to record the latitude and longitude of this address. I am using the mapbox api. How can I do that? I could not find or see it in the documentation.

HTML:

    <div class="col-md-12">
      <div class="row">
      <div class="col-md-12">
         <label class="control-label geocoder" for="geocoder">Address</label>
        <div id="geocoder" class="geocoder"></div>             
      </div>
      </div>
    </div>

JS:

<script type="text/javascript">
accessToken = 'xxxxxxxx';
    
var mapboxTiles = L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=' + accessToken, {
       attribution: '© <a href="https://www.mapbox.com/feedback/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
       tileSize: 512,
       zoomOffset: -1
});

var map = L.map('map')
  .addLayer(mapboxTiles)
  .setView([39.525247, 34.160501], 6);
var geocoder = new MapboxGeocoder({
accessToken: accessToken,
mapboxgl: mapboxgl
});
document.getElementById('geocoder').appendChild(geocoder.onAdd(map));
</script>

Clicking on the address under the search input shows that location on the map. When I click on that address, I want to alert the latitude and longitude of the address. How can I do it? Thanks.

1

There are 1 best solutions below

0
storedprocedure On BEST ANSWER

I solved my problem. I write the answer that anybody needs help.

accessToken = 'xxxxxxxx';
    
var mapboxTiles = L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=' + accessToken, {
       attribution: '© <a href="https://www.mapbox.com/feedback/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
       tileSize: 512,
       zoomOffset: -1
});

var map = L.map('map')
  .addLayer(mapboxTiles)
  .setView([39.525247, 34.160501], 6);
var geocoder = new MapboxGeocoder({
accessToken: accessToken,
mapboxgl: mapboxgl
});
document.getElementById('geocoder').appendChild(geocoder.onAdd());
geocoder.on('result', e => {
  console.log(e.result)
})