Leaflet Geocoding – Getting Coordinates After Picking Address in Leaflet Geosearch Control

geocodingleafletleaflet-plugins

I'm using leaflet to make a web map with an address search bar. For that I'm using leaflet-geosearch plugin

I need to retrieve the result once the user has picked the correct address from the search bar, so I can make spatial operations with that data.

Reading the documentation and some old questions from here, I presume I may have to use this event, which is fired when a location is chosen from the result list:

map.on('geosearch/showlocation', yourEventHandler);

So, my idea would be to grab a "result" object and print it to the console (if I can do that, I probably would be able to do the rest).

So far, this is what I have:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
  <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/geosearch.css"/>
  <title>Test map</title>
  <style>
    
    body {
    padding: 0;
    margin: 0;
   }

    html, body, #map {
        height: 100%;
        width: 100vw;
    }

</style>
<style>body { padding: 0; margin: 0; } #map { height: 100%; width: 100vw; }</style>
</head>

<body>
  
  <div id="map"></div>

<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="https://unpkg.com/[email protected]/dist/geosearch.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="./data/hexgrid.js"></script>


<script>

  var Esri_WorldImagery = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
    attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
  });

  var CartoDB_Positron = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>',
    subdomains: 'abcd',
    maxZoom: 19
  });
  
  const extent = [34, -118.22]

    var map = L.map('map', {
        center: extent,
        zoom: 10,
    preferCanvas: true,
        layers: CartoDB_Positron
    });

  var baseLayers = {
      "Image": Esri_WorldImagery,
      "Roads": CartoDB_Positron
    };

L.control.layers(baseLayers).addTo(map);

const search = new GeoSearch.GeoSearchControl({
  notFoundMessage: 'Address not found. Contact us to improve this tool.',
  provider: new GeoSearch.OpenStreetMapProvider({
    params: {
      countrycodes: 'us',
      limit: 5,
      viewbox: [25.140,-80.866,26.337,-80.061]
    }
  }),
  showMarker: true, // optional: true|false  - default true
  showPopup: true, // optional: true|false  - default false
  marker: {
    icon: new L.Icon.Default(),
    draggable: false,
  },
  popupFormat: ({ query, result }) => result.x.toString(), // optional: function    - default returns result label,
  resultFormat: ({ result }) => result.label, // optional: function    - default returns result label
  keepResult: true, // optional: true|false  - default false
  style: 'bar'
});

map.addControl(search);


</script>

</body>

</html>

Any hint on how to grab the result from leaflet-geoserch would be of great help.

Best Answer

This is classic example of getting the results of an event handler:

function searchEventHandler(result) {
  console.log(result.location);
}

map.on('geosearch/showlocation', searchEventHandler);

Here is an example of result.location object:

{
  "x": -77.0365427,
  "y": 38.8950368,
  "label": "Washington, District of Columbia, United States",
  "bounds": [
    [
      38.7916303,
      -77.1197949
    ],
    [
      38.995968,
      -76.909366
    ]
  ],
  "raw": {
    "place_id": 282620879,
    "licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
    "osm_type": "relation",
    "osm_id": 5396194,
    "boundingbox": [
      "38.7916303",
      "38.995968",
      "-77.1197949",
      "-76.909366"
    ],
    "lat": "38.8950368",
    "lon": "-77.0365427",
    "display_name": "Washington, District of Columbia, United States",
    "class": "boundary",
    "type": "administrative",
    "importance": 0.49732222465289555,
    "icon": "https://nominatim.openstreetmap.org/ui/mapicons//poi_boundary_administrative.p.20.png"
  }
}