Geocode with OpenCage and the maplibre-gl-geocoder plugin.
A Pen by Arnaud Ferrand on CodePen.
<!-- Load the `maplibre-gl-geocoder` plugin. --> | |
<div id="map"></div> |
Geocode with OpenCage and the maplibre-gl-geocoder plugin.
A Pen by Arnaud Ferrand on CodePen.
// Replace with your API Key, here this is a test key that returns only "Friedrich-Ebert-Straße 7, 48153 Münster, Germany" | |
var YOUR_API_KEY="6d0e711d72d74daeb2b0bfd2a5cdfdba"; | |
var map = new maplibregl.Map({ | |
container: "map", | |
// Use a minimalist raster style | |
style: { | |
version: 8, | |
name: "Blank", | |
center: [0, 0], | |
zoom: 0, | |
sources: { | |
"raster-tiles": { | |
type: "raster", | |
tiles: ["https://tile.openstreetmap.org/{z}/{x}/{y}.png"], | |
tileSize: 256, | |
minzoom: 0, | |
maxzoom: 19 | |
} | |
}, | |
layers: [ | |
{ | |
id: "background", | |
type: "background", | |
paint: { | |
"background-color": "#e0dfdf" | |
} | |
}, | |
{ | |
id: "simple-tiles", | |
type: "raster", | |
source: "raster-tiles" | |
} | |
], | |
id: "blank" | |
}, | |
center: [0, 51], | |
zoom: 4, | |
// pitch: 40, | |
// bearing: 20, | |
antialias: true | |
}); | |
var geocoder_api = { | |
forwardGeocode: async (config) => { | |
const features = []; | |
try { | |
let request = | |
"https://api.opencagedata.com/geocode/v1/geojson?q=" + | |
config.query + | |
"&key="+YOUR_API_KEY+"&no_annotations=1"; | |
const response = await fetch(request); | |
const geojson = await response.json(); | |
for (let feature of geojson.features) { | |
let point = { | |
type: "Feature", | |
geometry: { | |
type: "Point", | |
coordinates: feature.geometry.coordinates | |
}, | |
place_name: feature.properties.formatted, | |
properties: feature.properties, | |
text: feature.properties.formatted, | |
place_type: ["place"] | |
// center: center | |
}; | |
features.push(point); | |
} | |
} catch (e) { | |
console.error(`Failed to forwardGeocode with error: ${e}`); | |
} | |
return { | |
features: features | |
}; | |
} | |
}; | |
map.addControl( | |
new MaplibreGeocoder(geocoder_api, { | |
maplibregl: maplibregl | |
}) | |
); |
<script src="https://unpkg.com/[email protected]/dist/maplibre-gl.js"></script> | |
<script src="https://unpkg.com/@maplibre/[email protected]/dist/maplibre-gl-geocoder.min.js"></script> |
body { | |
margin: 0; | |
padding: 0; | |
} | |
#map { | |
position: absolute; | |
top: 0; | |
bottom: 0; | |
width: 100%; | |
} |
<link href="https://unpkg.com/[email protected]/dist/maplibre-gl.css" rel="stylesheet" /> | |
<link href="https://unpkg.com/@maplibre/[email protected]/dist/maplibre-gl-geocoder.css" rel="stylesheet" /> |