Search code examples
javascriptleafletgeocodingesri

Geocoding Address name from Database using leaflet esri plugin


I am trying to build a map app that use address name in data base and display marker in leaflet map. I had come across leaflet esri plugin but not sure how to use the code. Could anyone please teach me how to extract result(longitude and latitude) from the geocoding function and draw a marker? Thanks!

Geocode function:

L.esri.Geocoding.geocode(<Object> options)

Results:

{results: [
    {
      latlng: L.LatLng,
      text: 'Formatted Address',
      score: 100, // certainty ranking of the match
      properties: {
        // additional info like specific address components (Country Code etc.)
      }
    }
  ]
}

http://esri.github.io/esri-leaflet/api-reference/tasks/geocode.html


Solution

  • Here is an example using ES6:

    import L from "leaflet";
    // import library as ELG
    import * as ELG from "esri-leaflet-geocoder";
    
    // here is an example address in the US - use the one from your DB
    const address = "380 New York St, Redlands, California, 92373";
    
    // call geocode method of the library, no need to call L.esri.Geocoding.geocode() as in vanilla js
    ELG.geocode()
      // pass the address
      .text(address)
      .run((err, results, response) => {
        console.log(results.results[0].latlng);
        // retrieve latitude, longitude from related response
        const { lat, lng } = results.results[0].latlng;
        // build a marker using the retrieved address
        L.marker([lat, lng])
          .addTo(mymap)
          .bindPopup(address)
          .openPopup();
    });
    

    Demo