🌟

リバース ジオコーディング(住所検索)のリクエストとレスポンス

2023/06/25に公開

Geocoding APIの準備

keyの設定

Geocoding API で API キーを使用する  |  Google for Developers

緯度と経度から都道府県、市区町村、市区町村以下を抽出

レスポンスの型 ← 自分が使うようだったので、細かくしたい人はファイト

interface AddressComponent {
  long_name: string
  short_name: string
  types: string[]
}

interface Location {
  lat: number
  lng: number
}

interface Viewport {
  northeast: Location
  southwest: Location
}

interface Geometry {
  location: Location
  location_type: string
  viewport: Viewport
}

interface Result {
  address_components: AddressComponent[]
  formatted_address: string
  geometry: Geometry
  place_id: string
  plus_code: {
    compound_code: string
    global_code: string
  }
  types: string[]
}

interface JSONData {
  plus_code: {
    compound_code: string
    global_code: string
  }
  results: Result[]
  status: string
}

API部分

const key = process.env.NEXT_PUBLIC_GOOGLE_MAP_API_KEY
export const useAddressProvider = () => {
  const fetchAddress = async (lat: number, lng: number) => {
    const res = await fetch(
      `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${key}&language=ja&result_type=street_address|premise`,
      {
        method: 'GET',
      }
    )
    const json = (await res.json()) as JSONData
    return extractAddressComponents(json)
  }

  return {
    fetchAddress,
  }
}

function extractAddressComponents(jsonData: JSONData) {
  const results = jsonData.results
  if (results.length === 0) {
    return null
  }

  const result = results[0]
  const addressComponents = result.address_components
  const updatedAddressComponents = addressComponents.filter(
    (addressComponent) => {
      return !addressComponent.types.includes('country')
    }
  )

  // reverse updatedAddressComponents
  updatedAddressComponents.reverse()
  const zip = updatedAddressComponents[0].long_name
  const prefecture = updatedAddressComponents[1].long_name
  const city = updatedAddressComponents[2].long_name

  // updatedAddressComponentの3番目以降を結合
  const street = updatedAddressComponents
    .slice(3)
    .map((addressComponent) => addressComponent.long_name)
    .join('')
  const address = `${prefecture}${city}${street}`
  return {
    zip,
    prefecture,
    city,
    street,
    address,
  }
}

参考

リバース ジオコーディング(住所検索)のリクエストとレスポンス  |  Geocoding API  |  Google for Developers

Discussion