Install Leaflet plugin
Add geocoding control to your webpage
To use the Leaflet plugin, load the plugin's CSS and JavaScript files:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/opencagedata/leaflet-opencage-search@d4cbd36122efc8d17152b4177ed0e12165305441/dist/css/L.Control.OpenCageData.Search.min.css" />
<script src="https://cdn.jsdelivr.net/gh/opencagedata/leaflet-opencage-search@d4cbd36122efc8d17152b4177ed0e12165305441/dist/js/L.Control.OpenCageSearch.min.js"></script>
Then add the plugin's control to an
L.Map
instance:
var map = L.map('map').setView([51.52255, -0.10249], 13);
var options = {
key: 'YOUR-API-KEY',
limit: 10,
proximity: '51.52255, -0.10249' // favour results near here
};
var control = L.Control.openCageSearch(options).addTo(map);
L.tileLayer('https://{s}.tile.thunderforest.com/neighbourhood/{z}/{x}/{y}{r}.png?apikey=YOUR_THUNDERFOREST_API_KEY', {
attribution: 'Data <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors, Map tiles © <a href="https://www.thunderforest.com/">Thunderforest</a>',
minZoom: 4,
maxZoom: 18
}).addTo(map);
Demo
Note: in this example we use map tiles from our friends at Thunderforest, but you can use any map provider.Customizing
By default, when a geocoding result is found, the control will center the map on it and place a marker at its location. This can be customized by overwriting the control's markGeocode function, to perform any action desired.For example:
var control = L.Control.openCageSearch(options).addTo(map);
control.markGeocode = function(result) {
var bbox = result.bbox;
L.polygon([
bbox.getSouthEast(),
bbox.getNorthEast(),
bbox.getNorthWest(),
bbox.getSouthWest()
]).addTo(map);
};
This will add a polygon representing the result's boundingbox when a result is selected.
Options
You can overwrite the following options, for example to translate.var options = {
key: '', // your OpenCage API key
limit: 5 // number of results to be displayed
position: 'topright',
placeholder: 'Search...', // the text in the empty search box
errorMessage: 'Nothing found.',
showResultIcons: false,
collapsed: true,
expand: 'click',
};
var control = L.Control.openCageSearch(options).addTo(map);