今天我就講了一下怎麼經過vue和高德地圖開發的vue-amap組件來獲取經緯度。javascript
這是vue-amap的官網文檔:https://elemefe.github.io/vue-amap/#/css
這是個人碼雲項目的地址:http://git.oschina.net/ye_a_rs/project-vue-ele/tree/master/srcvue
npm install vue-amap --save
import Vue from 'vue'; import AMap from 'vue-amap'; import App from './App.vue'; Vue.use(AMap); AMap.initAMapApiLoader({ key: 'your amap key', plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor','AMap.Geolocation'] }); new Vue({ el: '#app', render: h => h(App) })
若是用到定位,就在app.vue這樣寫:java
<template> <div id="app"> <router-view name='index'></router-view> <router-view name='others'></router-view> <el-amap vid="amap" :plugin="plugin" class="amap-demo"></el-amap> <router-view></router-view> <!-- <foot></foot> --> </div> </template> <script> // import foot from './components/Footer'; export default { name: 'app', data() { let self = this; return { positions: { lng: '', lat: '', address: '', loaded: false }, center: [121.59996, 31.197646], plugin: [{ pName: 'Geolocation', events: { init(o) { // o 是高德地圖定位插件實例 o.getCurrentPosition((status, result) => { // console.log(result); // 能獲取定位的全部信息 if (result && result.position) { self.str = result.formattedAddress; self.positions.address = self.str.substring(self.str.indexOf('市') + 1); self.positions.lng = result.position.lng; self.positions.lat = result.position.lat; self.positions.loaded = true; self.$nextTick(); // 把獲取的數據提交到 store 的數據中,以便其餘單文件組件使用 self.$store.commit('POSITION', self.positions); // console.log(self.positions); sessionStorage.setItem('id', JSON.stringify(self.positions)); } }); } } }] }; } // components: { foot } } </script> <style lang='scss'> @import '../static/hotcss/px2rem.scss'; @import './common/css/resert.scss'; #app { height: 100%; .amap-demo { display: none; } } </style>