Skip to content

Instantly share code, notes, and snippets.

@tsamaya
Created March 22, 2023 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsamaya/dd6fdf3ed4ee9e4497216a52af58c44e to your computer and use it in GitHub Desktop.
Save tsamaya/dd6fdf3ed4ee9e4497216a52af58c44e to your computer and use it in GitHub Desktop.
Maplibre Geocoding with Opencage
<!-- Load the `maplibre-gl-geocoder` plugin. -->
<div id="map"></div>
// 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/maplibre-gl@2.4.0/dist/maplibre-gl.js"></script>
<script src="https://unpkg.com/@maplibre/maplibre-gl-geocoder@1.2.0/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/maplibre-gl@2.4.0/dist/maplibre-gl.css" rel="stylesheet" />
<link href="https://unpkg.com/@maplibre/maplibre-gl-geocoder@1.2.0/dist/maplibre-gl-geocoder.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment