Skip to content

Commit

Permalink
Merge pull request #49 from developmentseed/feature/geocoding
Browse files Browse the repository at this point in the history
Add geocoder
  • Loading branch information
kamicut authored Jun 7, 2024
2 parents 539f15f + d0a056a commit abfcfc1
Show file tree
Hide file tree
Showing 3 changed files with 6,332 additions and 3,929 deletions.
4 changes: 4 additions & 0 deletions packages/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
"lint": "eslint . --ext .js,.ts,.tsx"
},
"dependencies": {
"@maplibre/maplibre-gl-geocoder": "^1.5.0",
"@turf/area": "^6.5.0",
"@turf/bbox-polygon": "^6.5.0",
"date-fns": "^3.6.0",
"events": "^3.3.0",
"flatgeobuf": "^3.26.2",
"lodash.get": "^4.4.2",
"maplibre-gl": "^3.3.1",
Expand All @@ -23,7 +25,9 @@
"devDependencies": {
"@babel/runtime": "^7.22.15",
"@preact/preset-vite": "^2.5.0",
"@types/events": "^3.0.3",
"@types/lodash.get": "^4.4.7",
"@types/node": "^20.14.2",
"@types/turf": "^3.5.32",
"@typescript-eslint/eslint-plugin": "^6.7.0",
"@typescript-eslint/parser": "^6.7.0",
Expand Down
41 changes: 41 additions & 0 deletions packages/web/src/app/map/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { useEffect } from "preact/hooks";
import MapLibreGL, { MapMouseEvent } from "maplibre-gl";
import { AppActionTypes, AppDispatch, AppState } from "../reducer";
import MaplibreGeocoder from "@maplibre/maplibre-gl-geocoder";
import "@maplibre/maplibre-gl-geocoder/dist/maplibre-gl-geocoder.css";

interface MapProps {
appState: AppState;
Expand Down Expand Up @@ -162,6 +164,45 @@ export function Map(props: MapProps) {
},
});

const geocoderApi = {
forwardGeocode: async (config: { query: string }) => {
const features = [];
try {
const request = `https://nominatim.openstreetmap.org/search?q=${config.query}&format=geojson&polygon_geojson=1&addressdetails=1`;
const response = await fetch(request);
const geojson = await response.json();
for (const feature of geojson.features) {
const center = [
feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2,
feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2,
];
const point = {
type: "Feature",
geometry: {
type: "Point",
coordinates: center,
},
place_name: feature.properties.display_name,
properties: feature.properties,
text: feature.properties.display_name,
place_type: ["place"],
center,
};
features.push(point);
}
} catch (e) {
// eslint-disable-next-line no-console
console.error(`Failed to forwardGeocode with error: ${e}`);
}

return {
features,
};
},
};

map.addControl(new MaplibreGeocoder(geocoderApi, { zoom: 10 }));

function onClick(e: MapMouseEvent) {
// @ts-expect-error - MapMouseEvent doesn't know about features
const features = e.features as GeoJSON.Feature[];
Expand Down
Loading

0 comments on commit abfcfc1

Please sign in to comment.