使用vue-google-maps套件實作地圖(一)


Posted by Akira on 2021-12-25

請事先建立好一份 Vue 專案。

安裝與基礎設定

第一步:安裝套件

npm install vue2-google-maps

第二步:拿到 Google Map API 金鑰

請到Google地圖平台申請帳號。

申請時會要你填寫信用卡資訊,Google Map 以載入次數計算費用,每月有 200 美金的免費額度,大約可使用 28000 次,超過每 1000 次收費 7 美金。沒有選擇付費服務的話,超過免費額度就自動停止服務,不會自動扣款,不用擔心。

申請方式就不多說, Google 一下就會有教學。

第三步:引入套件

src/main.js中引入套件。

import Vue from 'vue'
import * as VueGoogleMaps from 'vue2-google-maps'

Vue.use(VueGoogleMaps, {
  load: {
    key: 'YOUR_API_TOKEN',
    libraries: 'places', 
  },
  installComponents: true
})
  • key:輸入你的金鑰,這串金鑰要記得保密。
  • libraries:使用 places 自動載入所需的插件。
  • installComponents:如果要自動載入到專案中所有 components請選擇 true。也可以手動載入:import {GmapMarker} from 'vue2-google-maps/src/components/marker'

第四步:在 components (或你的views中)加入地圖。

我習慣在components開一個Map.vue,專門放地圖,需要用到時在views中引入。

<template>
    <GmapMap
      :center="center"
      :zoom="15"
      :options="options"
      style="width: 100%; height: 600px"
    >
      <GmapMarker
        :position="marker.position"
        :clickable="false"
        :draggable="false"
      />
    </GmapMap>
</template>
<script>
    export default {
      name: "AddGoogleMap",
      data() {
        return {
          marker: { position: { lat: 25.033671, lng: 121.564427 } },
          center: { lat: 25.033671, lng: 121.564427 },
          options: {
            mapTypeControl: false,
            scaleControl: false,
            streetViewControl: false,
            fullscreenControl: false,
            disableDefaultUI: true,
            scrollwheel: true,
            clickableIcons: false,
      },
        };
      }
     }
</script>

這樣我們就會有一個插旗在台北101上的地圖了!

接著我們來細看 GmapMap 上的屬性。

centerzoom為必要屬性。

  • center:設定地圖中心的經緯度。
  • zoom:設定地圖初始縮放比例,0-20。
  • options:以下介紹幾個常用的屬性。
屬性名稱 屬性 說明
zoomControl boolean 是否能放大縮小地圖,預設為true。
mapTypeControl boolean 是否能切換地圖樣式,EX:地圖、地形圖、衛星檢視。
scaleControl boolean 是否顯示地圖比例尺。
streetViewControl boolean 是否讓使用者使用街景功能。
fullscreenControl boolean 是否開啟全螢幕地圖功能。
clickableIcons boolean 地圖標記是否能點擊,預設點擊會彈出視窗。
scrollwheel boolean 是否支援滑鼠滾輪,預設為false。
draggable boolean 可否拖曳地圖,預設為true。

更多Map控制內容可以參考 Google Map 官方文件

再來是GmapMarker的屬性

  • position:要放marker的座標地點。
  • clickable:是否可以點擊。
  • draggable:是否可以拖拉marker。
  • icon:更改marker樣式。
    • url:給予圖片連結。
    • scaledSize: 調整圖片大小。

更多Marker內容可以參考 Google Map 官方文件

範例:

<GmapMarker
    :icon="{
        url: require('../assets/images/star.png'),
        scaledSize: { width: 30, height: 30 },
    }"
    :position="marker.position"
    :clickable="false"
    :draggable="false"
    />
</GmapMap>


marker 就變成星星囉!

下一回來講講如何建立多個地標、及顯示客製化地標資訊。

參考文件:
vue2-google-maps官方文件


#google map API #Vue #Vue.js #vue2-google-maps #Front-End #前端







Related Posts

初識 JSON 格式與資料轉換

初識 JSON 格式與資料轉換

JS30 Day 10 筆記

JS30 Day 10 筆記

AA and AB Testing on Reducing Error Rate

AA and AB Testing on Reducing Error Rate


Comments