vue加入高德地图
网上找了很多相关的东西,有些地方就一点小错误,但是让人摸不着头脑,以下是自己运用到工程项目中的代码,分享给大家。
1.Vue中安装
npm install vue-amap --save
2.main.js引用
在网上,好多都是import AMap,其实这样会和原生的高德地图产生冲突,我就是这样的。一直显示不了地图。后面改为这个名字,就显示出来了。当然主要页面也得写正确
import VueAMap from 'vue-amap'
Vue.use(VueAMap );
Vue.config.productionTip = false;
// 初始化vue-amap
VueAMap .initAMapApiLoader({
// 高德key
key: '37f05ef459ba1b315d7ce12932846be1',
// 插件集合 (插件按需引入)
plugin: ['AMap.Geolocation','AMap.OverView','AMap.PlaceSearch'],
v: '1.4.4'
//,'AMap.CircleEditor','AMap.MapType', 'AMap.PolyEditor','AMap.Autocomplete', 'AMap.PlaceSearch'
});
3. 主要的界面
template里面代码如下
<div>
<el-button type="text" @click="changeShow" class="mapstyle" >点击显示地图</el-button>
</div>
<div v-show="showmap">
<div class="amap-page-container" >
<el-amap vid="amap" :plugin="plugin" class="amap-demo" :center="center">
</el-amap>
<div class="toolbar">
<span v-if="loaded">
location: lng = {{ lng }} lat = {{ lat }}
</span>
<span v-else>正在定位</span>
</div>
</div>
</div>
<style>
.amap-page-container{
height: 500px;
width: 80%;
}
.mapstyle{
font-size: 24px;
font-weight: bold;
}
</style>
基本上加上下面的代码就可以显示出地图,当然我写了一个函数,让他开始的时候显示,点击后不显示,再点击一次显示,主要是方便我自己加入新的代码。一个大地图显示占位置。
data() {
let self = this;
return {
showmap:true,
ip:'',
counts:0,
center: [121.59996, 31.197646],
lng: 0,
lat: 0,
loaded: false,
plugin: [{
pName: 'Geolocation',
convert: true, //自动偏移坐标,偏移后的坐标为高德坐标,默认:true
showButton: true, //显示定位按钮,默认:true
buttonPosition: 'RB', //定位按钮停靠位置,默认:'LB',左下角
showMarker: true, //定位成功后在定位到的位置显示点标记,默认:true
showCircle: true, //定位成功后用圆圈表示定位精度范围,默认:true
panToLocation: true, //定位成功后将定位到的位置作为地图中心点,默认:true
zoomToAccuracy:true,//定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:f
extensions:'all',
enableHighAccuracy: true,//是否使用高精度定位,默认:true
events: {
init(o) {
// o 是高德地图定位插件实例
o.getCurrentPosition((status, result) => {
if (result && result.position) {
self.lng = result.position.lng;
self.lat = result.position.lat;
self.center = [self.lng, self.lat];
self.loaded = true;
self.$nextTick();
}
});
}
}
}]
};
},
点击显示函数,method方法
changeShow(){
this.counts++;
// this.counts++;
if((this.counts)%2 !=0 ){
this.showmap = false;
}else {
this.showmap = true;
}
},