1. 程式人生 > >基於vue 2.X和高德地圖的vue-amap組件獲取經緯度

基於vue 2.X和高德地圖的vue-amap組件獲取經緯度

實例 con ati ble off 組件 posit return play

  今天我就講了一下怎麽通過vue和高德地圖開發的vue-amap組件來獲取經緯度。

  這是vue-amap的官網文檔:https://elemefe.github.io/vue-amap/#/

  這是我的碼雲項目的地址http://git.oschina.net/ye_a_rs/project-vue-ele/tree/master/src

  • vue init webpack 項目名稱 創建一個項目
  • npm安裝vue-amap組件 :
 npm install vue-amap --save
  • 在main.js引入vue-amap :
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) })
  • initAMapApiLoader裏面用到什麽插件就在plugin裏面寫什麽插件名;

  如果用到定位,就在app.vue這樣寫:

<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>
  • 在pName:寫入‘Geolocation‘,並在main.js的AMap.initAMapApiLoader引入‘AMap.Geolocation’,在app裏寫以上代碼,定位的所有信息都在o.getCurrentPosition((status, result) 的result裏,再對裏面進行解析、獲取,可以將經緯度和地址通過sessionStorage的setItem儲存。

基於vue 2.X和高德地圖的vue-amap組件獲取經緯度