LoginSignup
1
0

【Vue】Google Places API でインクリメンタルサーチの実装【JS】

Posted at

概要

今回は、地点を検索するフォームに文字が入力されたとき、一文字打つごとに候補がサジェストされるインクリメンタルサーチを作ります。

画面収録-2023-06-02-15.09.09.gif

実装

Google APIの準備

Google Maps APIのPlaces API を使用するので、あらかじめAPIキーを取得しておきましょう。

検索フォームにイベントを追加

フォームの@inputに関数をセットします。
フォームの内容が変わる度にAPIが呼び出され、suggestが更新されます。

<input 
     v-model="keyword" 
     type="text" 
     placeholder="行きたい場所" 
     @input="Search" 
/>

<div
    v-for="suggest in suggests"
    :key="suggest"
>
    {{ suggest }}
</div>

現在地の情報を取得する

Places APIを使うために現在地情報が必要になります。
onBeforeMountでVueGeolocationを使い、取得しておきます。

import { ref, onBeforeMount } from 'vue'
import VueGeolocation from 'vue3-geolocation'


//現在地情報の取得
const current = ref({
        lat: undefined,
        lng: undefined,
        getLocation: () => {
            VueGeolocation.getLocation()
                .then((coordinates) => {
                    current.value.lat = coordinates.lat //現在地の緯度
                    current.value.lng = coordinates.lng //現在地の経度
                })
                .catch((error) => {
                    console.log(error)
                })
        },
    })

onBeforeMount(() => {
    current.value.getLocation()
})

Places APIを呼び出す

import axios from 'axios'


const keyword = ref()

//検索フォームの内容が変わるたび、place apiを呼び出す
const Search = async () => {  
        await axios
            .get(https://maps.googleapis.com/maps/api/place/textsearch/json, {
                params: {
                    query: keyword.value,
                    location: current.value.lat + ',' + current.value.lng, 
                    radius: '50000',
                    language: 'ja',
                    key: 'google APIのキー',
                },
            })
            .then((res) => {
                suggests = res.data.ResultSet.Point
            })
    }

以上になります。ぜひご参考いただけますと幸いです。

画面収録-2023-06-02-15.09.09.gif

1
0
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
1
0