今天我就講了一下怎么通過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儲存。
