趁热笔记。。。
直接上代码吧,至于脚手架中引入高德地图的问题,看我上一篇文章
1.首先在methods方法中定义地图初始化的代码
//创建地图
this.map = new AMap.Map('container', {
//初始化地图的经纬度坐标
center: [121.227577, 31.101471],
resizeEnable: true,
zoom: 11
})
//创建鼠标画图对象(点击鼠标可以在地图画直线,圆圈,弧线等待,这里只做了直线,其他可参考官网)
//这里有一定要注意!!!需要在index入口文件引入的时候,引入MouseTool插件,注意后面拼接了插件的
//<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.4.4&key=d6c35bb2619f107f86ccda4b378415f6&plugin=AMap.MouseTool">//
this.mouseTool = new AMap.MouseTool(this.map)
//将vue实例对象赋值给临时变量,因为监听器内的this是被监听的对象,无法访问vue的属性
let cpThis=this
//给鼠标添加监听器,结束画线,获取到经纬度,存起来
AMap.event.addListener(this.mouseTool,"draw",function(pt){ //添加事件
let arr = pt.obj.getPath();
for(var i=0;i<arr.length;i++){
cpThis.projectFrom.mapinfo.push({"longitude":arr[i].lng,"latitude":arr[i].lat});
}
console.log(cpThis.projectFrom.mapinfo)
});
},
2.页面有两个单选按钮,一个是点击坐标,一个是画线的
//单选按钮变化事件,判断v-model返回的值是项目坐标还是道路,1坐标,2道路
// 获取按钮对象,给按钮对象注册地图点击事件
radioChange(){
if(this.projectFrom.radio==='1'){
//切换到标记坐标的情况,关掉鼠标
this.mouseTool.close(true)
//给地图添加点击事件
this.map.on('click', this.showInfoClick);
}else{
//道路路线,切到到道路路线时,清空数组,然后如果地图上有坐标,删除坐标,解除点击绑定
this.projectFrom.mapinfo=[]
if(this.marker!==undefined){
//删除坐标
this.map.remove(this.marker)
//解除坐标点击绑定
this.map.off('click', this.showInfoClick);
}
//生成线路
this.drawPolyline()
}
},
3.生成线路的代码
drawPolyline () {
this.mouseTool.polyline({
strokeColor: "#3366FF",
strokeOpacity: 1,
strokeWeight: 6,
// 线样式还支持 'dashed'
strokeStyle: "solid",
// strokeStyle是dashed时有效,虚线
// strokeDasharray: [10, 5],
})
},
4.生成坐标的代码
//在此方法中,获取经纬度,并在地图上生成坐标,并将项目经纬度坐标保存,添加项目使用
showInfoClick(e){
//如果坐标存在,则remove掉,重新生成最新的坐标(因为项目坐标只能有一个存在,业务需要)
if(this.marker!==undefined){
this.map.remove(this.marker)
}
//记录经纬度
this.projectFrom.longitude=e.lnglat.getLng()
this.projectFrom.latitude=e.lnglat.getLat()
//通过经纬度生成坐标点
this.marker = new AMap.Marker({
position:[this.projectFrom.longitude,this.projectFrom.latitude ]//位置
})
//将坐标添加到地图
this.map.add(this.marker)
},
5把地图的html代码也贴上把
<!--高德地图-->
<div class="box">
<div id="container" style="width:100%; height:500px"></div>
</div>
6.就完事收工!!!
这里说一下,代码中this.xxx的一些属性是在data中定义好的,加油!
贴下页面图,帮助理解