etc.../TIL

maplibre-gl-geocoder 사용법 +Carmen GeoJSON

짱닭 2023. 3. 16. 14:31
반응형

https://maplibre.org/maplibre-gl-js-docs/example/geocoder/
https://github.com/maplibre/maplibre-gl-geocoder

npm install --save @maplibre/maplibre-gl-geocoder

패키지 설치

import MaplibreGeocoder from '@maplibre/maplibre-gl-geocoder';
import '@maplibre/maplibre-gl-geocoder/dist/maplibre-gl-geocoder.css';

// Functions should return Carmen GeoJSON https://github.com/mapbox/carmen/blob/master/carmen-geojson.md
// Carmen GeoJSON 은 삭제된 과거 문서에만 명세가 나와있어 삭제되기 전 기록을 찾아봐야 한다
// 여기서 확인 할 수 있다. https://web.archive.org/web/20210224184722/https://github.com/mapbox/carmen/blob/master/carmen-geojson.md
const Geo = {
  forwardGeocode: async (config) => { /* definition here */ },
  reverseGeocode: async (config) => { /* definition here */ }, // optional reverse geocoding API
  getSuggestions: async (config) => { /* definition here */ } // optional suggestion API
};
// Geo 내부 키값은 맞춰서 사용해야 한다.

const options = { marker: false } // API.md에 있는 추가 옵션
const geocoder = new MaplibreGeocoder(Geo, { mapboxgl: maplibregl, ...options });

// forwardGeocode example
const forwardGeocode = async config => {
  const features = []
  try {
    const response = await axios.get(`https://nominatim.openstreetmap.org/search?q=${config.query}&format=geojson&polygon_geojson=1&addressdetails=1`)

    for (let feature of response.features) {
      let center = [feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2]

      // point 객체를 Carmen GeoJSON 형태로 맞춰줘야 에러가 발생하지 않는다. maplibreGl 홈페이지 예제와 같음
      let point = {
        ...feature,
        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: center,
      }
      features.push(point)
    }    
  } catch (e) {
    console.error(e)
  }

  return {
    features: features,
  }
}

Carmen GeoJSON 명세
https://web.archive.org/web/20210224184722/https://github.com/mapbox/carmen/blob/master/carmen-geojson.md

반응형