diff options
author | Anton Tananaev <anton@traccar.org> | 2022-06-19 09:36:12 -0700 |
---|---|---|
committer | Anton Tananaev <anton@traccar.org> | 2022-06-19 09:36:12 -0700 |
commit | e3827fbad0cb51e0e1e92b722d1c0c132c3d07c9 (patch) | |
tree | 585321727f053558cfac8bbcd0e2041cb7fbf297 /modern/src/map/geocoder/MapGeocoder.js | |
parent | e67aafb900f474da2381ea418c3e8eb09bc4683b (diff) | |
download | trackermap-web-e3827fbad0cb51e0e1e92b722d1c0c132c3d07c9.tar.gz trackermap-web-e3827fbad0cb51e0e1e92b722d1c0c132c3d07c9.tar.bz2 trackermap-web-e3827fbad0cb51e0e1e92b722d1c0c132c3d07c9.zip |
Implement geocoding search
Diffstat (limited to 'modern/src/map/geocoder/MapGeocoder.js')
-rw-r--r-- | modern/src/map/geocoder/MapGeocoder.js | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/modern/src/map/geocoder/MapGeocoder.js b/modern/src/map/geocoder/MapGeocoder.js new file mode 100644 index 00000000..de1791e6 --- /dev/null +++ b/modern/src/map/geocoder/MapGeocoder.js @@ -0,0 +1,56 @@ +import './geocoder.css'; +import maplibregl from 'maplibre-gl'; +import MaplibreGeocoder from '@maplibre/maplibre-gl-geocoder'; +import { useEffect } from 'react'; +import { useDispatch } from 'react-redux'; +import { map } from '../core/MapView'; +import { errorsActions } from '../../store'; + +const MapGeocoder = () => { + const dispatch = useDispatch(); + + useEffect(() => { + const geocoder = { + forwardGeocode: async (config) => { + 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(); + geojson.features.forEach((feature) => { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + features.push({ + 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, + }); + }); + } catch (e) { + dispatch(errorsActions.push(e.message)); + } + return { features }; + }, + }; + + const control = new MaplibreGeocoder(geocoder, { + maplibregl, + collapsed: true, + }); + map.addControl(control); + return () => map.removeControl(control); + }, [dispatch]); + + return null; +}; + +export default MapGeocoder; |