Search code examples
javascriptreactjsleafletgeocodingreact-leaflet

React leaflet, the name of the place, not the coordinates


Is it possible to render a map in React Leaflet giving the name of the place and not the map coordinates? Instead of giving coordinates of place i wish to enter place name eg. "St. James’s Park " or "Circuit de Barcelona-Catalunya"

import React from "react";
import { MapContainer, TileLayer } from "react-leaflet";

function MyMap() {
  const position = [53.35, 18.8];
  return (
    <MapContainer
      className="map"
      center={position}
      zoom={6}
      style={{ height: 500, width: "100%" }}>
      <TileLayer
        attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"/>
    </MapContainer>
  );
}
export default MyMap;



Solution

  • You need to apply geocoding. One solution is to use esri-leaflet-geocoder library.

    Install it via npm i esri-leaflet-geocoder and create a Geocoder component that will take the address and will set the map view to the selected location after converting the address to coordinates.

        function Geocoder({ address }) {
            const map = useMap();
        
            ELG.geocode()
              .text(address)
              .run((err, results, response) => {
                console.log(results.results[0].latlng);
                const { lat, lng } = results.results[0].latlng;
                map.setView([lat, lng], 12);
              });
        
            return null;
          }
    

    Use it like this :

        <MapContainer
              className="map"
              center={position}
              zoom={6}
            >...
              <Geocoder address="Circuit de Barcelona-Catalunya" />
          </MapContainer>
    

    Demo