Install Leaflet Geocoding 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-geocoding@v2.0.0/dist/css/L.Control.OpenCageGeocoding.min.css" />
<script src="https://cdn.jsdelivr.net/gh/opencagedata/leaflet-opencage-geocoding@v2.0.0/dist/js/L.Control.OpenCageGeocoding.min.js"></script>
The plugin works with both Leaflet v1 and v2 using v1 Polyfill. Choose the code example that matches your Leaflet version.
For Leaflet v1:
const map = L.map('map').setView([51.52255, -0.10249], 13);
L.tileLayer('https://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);
const options = {
key: 'YOUR-API-KEY',
limit: 10,
proximity: '51.52255, -0.10249' // favour results near here
};
const control = L.Control.openCageGeocoding(options).addTo(map);
For Leaflet v2 alpha using Global Script and v1 Polyfill:
If you are using Leaflet v2 alpha, you can use the global script and v1 polyfill.
<link rel="stylesheet" href="https://unpkg.com/leaflet@2.0.0-alpha/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@2.0.0-alpha/dist/leaflet-global.js"></script>
Download the file leaflet-v1-polyfill.js and add it to your scripts.
<script src="./leaflet-v1-polyfill.js"></script>
The Javascript code to use the plugin is almost the same then, we only need to add the polyfills.
// Load the polyfill for Leaflet v2
applyAllPolyfills();
// Now we can use the Leaflet v2 global script
const map = L.map('map').setView([51.52255, -0.10249], 13);
L.tileLayer('https://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);
const options = {
key: 'YOUR-API-KEY',
limit: 10,
proximity: '51.52255, -0.10249' // favour results near here
};
const control = L.Control.openCageGeocoding(options).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.const control = L.Control.openCageGeocoding(options).addTo(map);
control.markGeocode = function(result) {
const 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.const options = {
key: 'YOUR-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',
addResultToMap: true, // if a map marker should be added after the user clicks a result
onResultClick: undefined, // callback with result as first parameter
resultExtension: { // additional attributes to add to result
geohash: 'annotations.geohash',
what3words: 'annotations.what3words',
addressComponents: 'components'
}
};
const control = L.Control.openCageGeocoding(options).addTo(map);
See also
If you prefer to do your frontend development in React please check out react-leaflet-opencage.Some issues to consider:
Please note that putting your API key in client side javascript means that it is visible to anyone executing that javascript. We recommend you do this only for internal applications.
Please see our detailed guide to protecting your API key(s).
As an added measure of safety subscription customers can define a value for
the
Access-Control-Allow-Origin
header in their account dashboard which will limit AJAX requests to
a specific domain. You can find the
details in the API documentation.
That being said, one worry that potential clients sometimes raise is that someone will get their key and start using it heavily and they will face a large and unexpected bill. Fear not - that can't happen because of how our pricing works. Subscription customers buy a month in advance, and there is no usage-based charging. If we see an explosion of usage we email you and ask if it is expected and the source is known. If yes, and it will be ongoing, we ask you to move to a higher pricing tier in the future, but this never happens as a surprise. If no, we can help you work out what is going on. Please see all the details of how our pricing works.
2,500 geocoding API requests/day - No credit card required