基于vue 2.X和高德地图的vue-amap组件获取经纬度

  今天我就讲了一下怎么通过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 >
   <router-view name='index'></router-view>
   <router-view name='others'></router-view>
   <el-amap v></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 >
@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储存。