4
3

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 5 years have passed since last update.

【Nuxt】何らかのパッケージを使わず普通にGoogleMapAPIを導入する

Last updated at Posted at 2020-01-29

nuxtやvueへの導入用のパッケージはいくつかあるのですが、
「俺はただ単にgoogleMapのjsが読み込めていれば、いつものロジックが使えればそれでいいんや!」っていう人向きです。

概要

  • scriptタグで読み込ませるだけのいつもの簡単なスタイルで実現。
  • 使うときにほんの少しだけ工夫する。

方法

nuxt.config.jsの設定

nuxt.config.jsの head > script 内に普通にURLを書く。
これでスクリプト自体の導入は完了です。

nuxt.config.js
head: {
  script: [
    { src: 'https://maps.google.com/maps/api/js?key=API_KEY&libraries=places&language=ja' }
  ]
}

使う時

.vueファイルから直接googleオブジェクトを使うことができます。
外部のJSで使いたい場合は引数としてオブジェクトごと渡して使います。

computedを設定

this.google でgoogleオブジェクトにアクセスできるようになります。

page.vue
computed: {
   google() {
      return window.google
    }
}

実行

ページ内で使う場合

page.vue
methods: {
  sample() {
    const google = this.google
    const test = new google.maps....
  }
}

外部のJSにロジックを書いている場合

ページファイルからgoogleオブジェクトを渡して使います。

page.vue
import { getRoute } from '@/plugins/path/to/googleMapSample'

methods: {
  sample() {
    const data = 1
    getRoute(this.google, data)
  }
}
googleMapSample.js
const getRoute = (google, data) => {
  const test = new google.maps....
}

export {
  getRoute
}

メリット

  • 設定がシンプルで消耗しない。
  • Vue.useを使ったり、設定用としてplugin配下にJSファイルを作る必要がない。
  • 外部JSに引数として渡してしまえば、普段と同じ感覚で使える。
  • 困った時に参照するのが一番手厚いGoogleMapの公式ドキュメントでよい

まとめ

  • ピュアなロジックを使いたいだけだったらこれが一番簡単だと思う。
  • 開発と本番でAPIキーを分ける必要があるがそれはまた別の問題。
4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?