# 在Nuxt使用Leaflet地圖套件  ### 安裝 首先參照官方文件安裝套件 1. **vue2Leaflet 官方文件**: https://vue2-leaflet.netlify.app/ (*vue2Leaflet Github: https://github.com/vue-leaflet/Vue2Leaflet*) 2. **nuxt-leaflet**: https://github.com/schlunsen/nuxt-leaflet - NPM `npm install leaflet vue2-leaflet nuxt-leaflet --save` - YARN `yarn add leaflet vue2-leaflet nuxt-leaflet` :::info 總共會安裝三個套件`leaflet`、`nuxt-leaflet`、`vue2-leaflet` ::: --- ### 設定 #### 全域plugins 在plugins資料夾底下新增一個 leaflet.js ``` javascript= import Vue from 'vue'; import { LMap, LTileLayer, LMarker } from 'vue2-leaflet'; import 'leaflet/dist/leaflet.css'; Vue.component('l-map', LMap); Vue.component('l-tile-layer', LTileLayer); Vue.component('l-marker', LMarker); ``` #### nuxt.config.js ``` javascript= plugins: [ { src: '~plugins/leaflet.js', ssr: false } // ssr設定為false表示僅在client端渲染 ], modules: [ 'nuxt-leaflet' // 簡易使用 ] ``` --- ### 使用地圖 ``` javascript= <l-map ref="mymap" :zoom="3" :center="specimenLocation"> <l-tile-layer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" :attribution="attribution"/> <l-marker :lat-lng="specimenLocation" /> </l-map> ``` - zoom:調整地圖顯示的遠近程度,數字越小=地圖顯示越遠,數字越大=地圖顯示越近 - center:地圖中心定位的位置 - url:地圖風格樣式,網路上有很多免費/付費的樣式可供選擇,這邊使用openstreet提供的原始版本 - attribution:放copyright的小標籤,會顯示在地圖右下角 - lat-lng:l-marker圖釘定位的座標,是一維陣列,例:[20.0128, 100.007] --- ### Fullscreen 全螢幕插件 #### 安裝 vue2-leaflet-fullscreen Github: https://github.com/mikeu/vue2-leaflet-fullscreen - NPM `npm --save install vue2-leaflet-fullscreen` - YARN `yarn add vue2-leaflet-fullscreen` #### leaflet.js 將組件引入並讓vue使用 ``` javascript= import LControlFullscreen from 'vue2-leaflet-fullscreen' Vue.component('l-control-fullscreen', LControlFullscreen) ``` Nuxt是伺服器渲染(SSR,Server Side Render) 為避免報錯誤訊息-- **window is not found** ((之前踩這個坑踩得好苦啊... 將會使用到window的組件寫在`monted()` ※ html結構中需先給l-map一個ref ``` html= <l-map ref="mymap" ...> ``` ``` javascript= mounted() { const map = this.$refs.mymap.mapObject map.addControl(new window.L.Control.Fullscreen({ title: { false: 'View Fullscreen', true: 'Exit Fullscreen' }, position: 'topright' })) } ``` 可以對該fullscreen toggle button設定其他參數 - title:button所顯示的提示訊息 - position:button所在位置,例:topright、topleft... 參考: (1) https://ithelp.ithome.com.tw/articles/10292430 (2) https://devpress.csdn.net/vue/632c0787357a883f870c7c55.html (3) https://www.letswrite.tw/leaflet-plugins/#%E5%85%A8%E8%9E%A2%E5%B9%95%EF%BC%9Aleafletcontrolfullscreen
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up