3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Vue】google-maps-api-loaderで郵便番号から住所を補完させる

Last updated at Posted at 2020-06-25

概要

入力された郵便番号を元に、Google Maps API(google-maps-api-loader)を利用して「都道府県/市区町村/番地」を取得してオートコンプリートでフォームを補完させる方法

事前準備

  • ライブラリの導入
yarn add google-maps-api-loader
yarn add axios

実装

<template>
  <div>
    <label>郵便番号</label>
    <input
      @input="onChangePostalCodeFirst($event)"
    />
    -
    <input @input="onChangePostalCode($event)" />
    <select v-model="prefectureId">
      <option :value="null" disabled>選択してください</option>
      <option
        v-for="prefecture in prefectures"
        :key="`prefecture-${prefecture.value}`"
        :value="prefecture.value"
      >
        {{ prefecture.label }}
      </option>
    <input ref="address" v-model="address" />
  </div>
</template>

<script>
import GoogleMapsApiLoader from 'google-maps-api-loader'
import axios from 'axios'

export default {
  data() {
    return {
      address: '',
      prefectures: [
        { label: '北海道', value: 1 },
        { label: '青森県', value: 2 },
        ...省略...
      ]
    }
  },
  methods: {
    onChangePostalCodeFirst(event) {
      if (event.target.value.length === 3) {
        this.$refs.postalCodeSecond.focus()
      }
    },
    async onChangePostalCodeSecond(event) {
      if (event.target.value.length === 4) {
        const google = await GoogleMapsApiLoader({
          apiKey: *************,  // APIキーを入力
          libraries: ['places']
        })

        const address = new google.maps.Geocoder()
        address.geocode(
          {
            address: this.postalCode,
            region: 'jp'
          },
          (results, status) => {
            if (status === google.maps.GeocoderStatus.OK) {
              let address = results[0].address_components
              address.shift() // '日本'を削除
              address = address.reverse() // 住所を逆ソート
              address.shift()  // 郵便番号を削除
              address = address.map(data => {
                return data.long_name  // 住所のテキストを抜き出し
              })
              const prefecture = address.shift()  // 都道府県を抜き出し

              this.prefectureId = this.prefectures.find(p => {
                return p.label === prefecture
              }).value
              this.cityAddress = address.join('')
            }
          }
        )
      }
    }
  }
}

動作

Image from Gyazo

参考

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?