LoginSignup
19
16

More than 5 years have passed since last update.

Vue.js + GoogleMapで地名検索を実装する

Posted at

GameWith Advent Calendar 2018

この記事はGameWith Advent Calendar 2018 の3日目になります!

はじめに

GoogleMapで地名を入力して検索をすると、ピンが立って緯度経度を取得するのをVue.jsを利用し実装しました。

スクリーンショット 2018-12-01 14.59.46.png

こちらから挙動を試せます。

前提

  • Vue version 2.5.7
  • Google Maps Apiの登録済み

実装

HTML

地名を入力するためにinputタグと、検索のトリガーになるbuttonタグとGoogleMap用のdivタグです。

<input type="text" v-model="address">
<button type="button" @click="mapSearch">検索</button>
<div id="map"></div>

JavaScript

地名検索はGeocodingを利用します。

google.map.Geocoder()Geocoder Objectを作成し、geocode()で検索します。

geocodeの第一引数には入力された地名を渡します。

渡せる引数は下記オブジェクトで、緯度経度なども渡せます。

{
 address: string,
 location: LatLng,
 placeId: string,
 bounds: LatLngBounds,
 componentRestrictions: GeocoderComponentRestrictions,
 region: string
}

検索処理が終わると第二引数の関数が実行されます。

resultsに渡るのは下記オブジェクトで、地名などが緯度経度から逆引きで取得ができます。

results[0].geometry.locationをマーカーオブジェクトに渡すことでピンを立てることができます。

results[]: {
 types[]: string,
 formatted_address: string,
 address_components[]: {
   short_name: string,
   long_name: string,
   postcode_localities[]: string,
   types[]: string
 },
 partial_match: boolean,
 place_id: string,
 postcode_localities[]: string,
 geometry: {
   location: LatLng,
   location_type: GeocoderLocationType
   viewport: LatLngBounds,
   bounds: LatLngBounds
 }
}

スクリーンショット 2018-12-01 15.36.38.png

その他詳しくはこちら

new Vue({
  el: '#wrapper',
  mounted() {
    this.map = new google.maps.Map(document.getElementById('map'));
    this.geocoder = new google.maps.Geocoder();
  },
  data() {
    return {
      map: {},
      marker: null,
      geocoder: {},
      address: ''
    }
  },
  methods: {
    mapSearch() {
      this.geocoder.geocode({
        'address': this.address
      }, (results, status) => {
        if (status === google.maps.GeocoderStatus.OK) {
          this.map.setCenter(results[0].geometry.location);
          // 緯度経度の取得
          // results[0].geometry.location.lat();
          // results[0].geometry.location.lng();
          this.marker = new google.maps.Marker({
            map: this.map,
            position: results[0].geometry.location
          });
        }
      });
    }
  },
});

終わりに

地名からの検索が勝手に難しいイメージを持ってましたが、さすがGoogleMap!

IngressやポケGOが流行っていますが、端末の性能があがってきたので地図系のアプリが今後どんどん増えそうですね!

19
16
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
19
16