Leaflet Geocoding – Address Searching using Leaflet for Improved Mapping

addressgeocodingleaflet

I am pretty new to coding.

I have been using Leaflet to create an interactive map, I have managed to pull in some data from a PostGIS database and have points on the map, downloaded some plugins from GitHub which enabled me to change basemap, turn on and off layers etc. So I have some experience of using plugins.

However I want the users to be able to enter an address and the map take them to that address. I have tried a few different ones which I have found around the web but I have struggled to implement it into my map, I got one sort of working, but the address search wasn't the best, mainly going to US addresses, and I need UK.

Anyway, a good address search is probably this one:

https://github.com/smeijer/leaflet-geosearch

But honestly I don't really know where to start. It mentions npm, which I don't properly understand and there is a ton of files.

I just find it all a bit overwhelming, in the Leaflet example is mentions code such as:

import L from 'leaflet';
import { GeoSearchControl, OpenStreetMapProvider } from 'leaflet-geosearch';

const provider = new OpenStreetMapProvider();

const searchControl = new GeoSearchControl({
  provider: provider,
});

const map = new L.Map('map');
map.addControl(searchControl);

Is it just a case of downloading all the files then adding that code into my existing JS code?

I think I have basically tried that and had no luck so I presume the answer is no.

Best Answer

I tried too and failed. Here is an option that uses OSM and has other options. https://github.com/perliedman/leaflet-control-geocoder

and a HTML page that works using it.

<!DOCTYPE html>
<html>
<head><title>Leaflet</title>
 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>

<link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />
<script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>     
</head>
<body>
    <style> #map {width: 100%;height: 100%; }   </style>

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

<script>
//Example from https://github.com/perliedman/leaflet-control-geocoder  
    var map = L.map('map').setView([42.697765, -73.108005], 3);  

    var osm=new L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);

    L.Control.geocoder().addTo(map);

</script>
</body>
</html>