uniapp H5端使用高德地图完成路线规划

本项目是H5端,APP端地图的使用方法请参考我的另一篇博客uniapp,map地图组件打包原生APP

首先到高德地图API,申请web端key

在这里插入图片描述

参考高德H5端教程开始写代码高德地图JS API

1、准备工作,会提示你先引入下边这块代码

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script> 

我的项目是uniapp项目,在自定义的html引入会报错,个人感觉可能是加载顺序的问题,最后修改成

import maps from '../../static/maps.js' 

关于maps.js文件是怎么来的,第一步准备工作的src链接,直接打开,将这个js文件保存到本地maps.js并引用就可以。

2、定义dom

<view id="container"></view>

3、为地图容器指定宽高

#container {
	width: 750rpx;
	height: 750rpx;
}

4、初始化地图控件,需要放在this.$nextTick函数内,否则会报错(之前是按照官方的写法window.onLoad,测试也可以,过了段时间不行了,不知道什么原因)

this.$nextTick(() => {
	let _this = this;
	_this.map = new AMap.Map('container', {
		zoom: 15, //缩放级别
		resizeEnable: true, //自动定位
	});
})

初始化完成如下图
在这里插入图片描述

uniapp data中的变量,下边的操作会向变量中赋值

data() {
	return {
		map: null,
		address0: {}, //起点信息
		address1: {}, //终点信息
		star: [], //起点
		end: [], //终点
		markers: [], //点标记
		routes: {}, //路线距离时间信息记录
	}
},

5、地图已经调出来了,现在应该获取定位,并在在地图上定位标记点

AMap.plugin('AMap.Geolocation', function() {
	uni.showLoading({
		title: '系统正在定位'
	});
	var geolocation = new AMap.Geolocation({
		enableHighAccuracy: true, //是否使用高精度定位,默认:true
		timeout: 10000, //超过10秒后停止定位,默认:5s
		buttonPosition: 'RB', //定位按钮的停靠位置
		buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
		zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
	
	});
	_this.map.addControl(geolocation);
	geolocation.getCurrentPosition(function(status, result) {
		if (status == 'complete') {
			//这个地方的result,可能会出现报错:获得地理定位时间。得到ipLocation成功。获取地址失败,请检查您的密钥或网络。
			//可能是密匙申请错了,重新申请密匙,生成maps.js文件。
			console.log(result)
			uni.hideLoading();
			uni.showToast({
				title: '定位成功',
			});
			let res = {
				name: result.formattedAddress,
				latitude: result.position.lat,
				longitude: result.position.lng,
			}
			
			let marker0 = new AMap.Marker({
				map: _this.map,
				position: [res.longitude, res.latitude], //位置
				icon: '/static/star.png', // 添加 Icon 图标 URL
				offset: new AMap.Pixel(-15, -42),//偏移量
			});
			_this.markers[0] = marker0; //添加 起点 标记
	
			_this.address0 = res; //起点数据
			_this.star = [res.longitude, res.latitude]; //起点经纬度
	
		} else {
			uni.hideLoading();
			uni.showToast({
				title: '定位失败,请手动选择出发地',
			});
			console.log(result)
		}
	});
});

如下图,定位标记,和数据都已获取到
在这里插入图片描述
6、下面是选择出发地和目的地事件,使用uni.chooseLocation()打开地图选择完成,

<view class="item" @click="chooseAddress(1)">
	<text class="title">请选择出发地</text>
</view>
<view class="item">
	<text class="color">{{address0.name}}</text>
</view>
<view class="item" @click="chooseAddress(2)">
	<text class="title">请选择目的地</text>
</view>
<view class="item">
	<text class="color">{{address1.name}}</text>
</view>
<view class="item">
	<text class="color" v-if="routes.distance">{{routes.distance/1000}}千米,</text>
	<text class="color" v-if="routes.policy == '速度最快'">出行模式:驾车,</text>
	<text class="color" v-if="routes.time">大约需要{{routes.time/60}}分钟。</text>
</view>
chooseAddress(type) {
	uni.chooseLocation({
		success: res => {
			if (type == 1) {
				this.markers[0].setMap(null); //删除 起点 标记
				let marker0 = new AMap.Marker({
					map: this.map,
					position: [res.longitude, res.latitude], //位置
					icon: '/static/star.png', // 添加 Icon 图标 URL
					offset: new AMap.Pixel(-15, -42),//偏移量
				});
				this.markers[0] = marker0; //覆盖 起点 标记

				this.star = [res.longitude, res.latitude]; //起点经纬度
				this.address0 = res;//起点数据
				if (this.markers.length == 2) {
					this.map.clearMap();//先清除地图覆盖物
					this.add_Driving();//在重新规划路线
				} else {
					this.map.setFitView(); //自动缩放地图
				}
			} else {
				let marker1 = new AMap.Marker({
					map: this.map,
					position: [res.longitude, res.latitude], //位置
					icon: '/static/end.png', // 添加 Icon 图标 URL
					offset: new AMap.Pixel(-15, -42),//偏移量
				});
				this.address1 = res;//终点数据
				this.end = [res.longitude, res.latitude]; //终点经纬度
				this.map.clearMap();//先清除地图覆盖物
				this.markers[1] = marker1; //添加 终点 标记
				this.add_Driving();//规划路线
			}
		}
	});
},

7、地址选择完毕后规划路线

add_Driving() {
	let _this = this;
	this.map.plugin('AMap.Driving', () => {
		var driving = new AMap.Driving({
			// 驾车路线规划策略,AMap.DrivingPolicy.LEAST_TIME是最快捷模式
			map: this.map,
			policy: AMap.DrivingPolicy.LEAST_TIME
		})
		driving.search(this.star, this.end, function(status, result) {
			console.log(result)
			_this.routes = result.routes[0]
			_this.markers[0].setMap(null);
			_this.markers[1].setMap(null);
		})
	})
},

完成后的效果图如下
在这里插入图片描述

附上项目完整代码,注意你的key (web端 js API)
这里你只需要把你的maps.js放在static目录,
star.png,end.png 起点终点图标放在static目录,
完成后可以直接使用本代码,

<template>
	<view class="login">
		<view id="container"></view>
		
		<view class="item" @click="chooseAddress(1)">
			<text class="title">请选择出发地</text>
		</view>
		<view class="item">
			<text class="color">{{address0.name}}</text>
		</view>
		<view class="item" @click="chooseAddress(2)">
			<text class="title">请选择目的地</text>
		</view>
		<view class="item">
			<text class="color">{{address1.name}}</text>
		</view>
		<view class="item">
			<text class="color" v-if="routes.distance">{{routes.distance/1000}}千米,</text>
			<text class="color" v-if="routes.policy == '速度最快'">出行模式:驾车,</text>
			<text class="color" v-if="routes.time">大约需要{{routes.time/60}}分钟。</text>
		</view>
	</view>
</template>
<script>
	import maps from '../../static/maps.js'
	export default {
		data() {
			return {
				map: null,
				address0: {}, //起点信息
				address1: {}, //终点信息
				star: [], //起点经纬度
				end: [], //终点经纬度
				markers: [], //点标记
				routes: {}, //路线距离时间信息记录
			}
		},

		onLoad() {
			this.$nextTick(() => {
				let _this = this;
				_this.map = new AMap.Map('container', {
					zoom: 15, //缩放级别
					resizeEnable: true, //自动定位
				});

				AMap.plugin('AMap.Geolocation', function() {
					uni.showLoading({
						title: '系统正在定位'
					});
					var geolocation = new AMap.Geolocation({
						enableHighAccuracy: true, //是否使用高精度定位,默认:true
						timeout: 10000, //超过10秒后停止定位,默认:5s
						buttonPosition: 'RB', //定位按钮的停靠位置
						buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
						zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点

					});
					_this.map.addControl(geolocation);
					geolocation.getCurrentPosition(function(status, result) {
						if (status == 'complete') {
							//这个地方的result,可能会出现报错:获得地理定位时间。得到ipLocation成功。获取地址失败,请检查您的密钥或网络。
							//可能是密匙申请错了,重新申请密匙,生成maps.js文件。
							console.log(result)
							uni.hideLoading();
							uni.showToast({
								title: '定位成功',
							});
							let res = {
								name: result.formattedAddress,
								latitude: result.position.lat,
								longitude: result.position.lng,
							}
							let marker0 = new AMap.Marker({
								map: _this.map,
								position: [res.longitude, res.latitude], //位置
								icon: '/static/star.png', // 添加 Icon 图标 URL
								offset: new AMap.Pixel(-15, -42),//偏移量
							});
							_this.markers[0] = marker0; //添加 起点 标记

							_this.address0 = res; //起点数据
							_this.star = [res.longitude, res.latitude]; //起点经纬度

						} else {
							uni.hideLoading();
							uni.showToast({
								title: '定位失败,请手动选择出发地',
							});
							console.log(result)
						}
					});
				});
			}
		},
		methods: {
			//选择地址
			chooseAddress(type) {
				uni.chooseLocation({
					success: res => {
						if (type == 1) {
							this.markers[0].setMap(null); //删除 起点 标记
							let marker0 = new AMap.Marker({
								map: this.map,
								position: [res.longitude, res.latitude], //位置
								icon: '/static/star.png', // 添加 Icon 图标 URL
								offset: new AMap.Pixel(-15, -42),//偏移量
							});
							this.markers[0] = marker0; //覆盖 起点 标记

							this.star = [res.longitude, res.latitude]; //起点经纬度
							this.address0 = res;//起点数据
							if (this.markers.length == 2) {
								this.map.clearMap();//先清除地图覆盖物
								this.add_Driving();//重新规划路线
							} else {
								this.map.setFitView(); //自动缩放地图
							}
						} else {
							let marker1 = new AMap.Marker({
								map: this.map,
								position: [res.longitude, res.latitude], //位置
								icon: '/static/end.png', // 添加 Icon 图标 URL
								offset: new AMap.Pixel(-15, -42),//偏移量
							});
							this.address1 = res;//终点数据
							this.end = [res.longitude, res.latitude]; //终点经纬度
							this.map.clearMap();//先清除地图覆盖物
							this.markers[1] = marker1; //添加 终点 标记
							this.add_Driving();//规划路线
						}
					}
				});
			},
			//规划路线
			add_Driving() {
				let _this = this;
				this.map.plugin('AMap.Driving', () => {
					var driving = new AMap.Driving({
						// 驾车路线规划策略,AMap.DrivingPolicy.LEAST_TIME是最快捷模式
						map: this.map,
						policy: AMap.DrivingPolicy.LEAST_TIME
					})
					driving.search(this.star, this.end, function(status, result) {
						console.log(result)
						_this.routes = result.routes[0]
						_this.markers[0].setMap(null);
						_this.markers[1].setMap(null);
					})
				})
			},
		},
	}
</script>
<style>
	#container {
		width: 750rpx;
		height: 750rpx;
	}
	.item {
		font-size: 28rpx;
		padding: 20rpx;
		height: 50rpx;
	}
	.title {
		margin-right: 40rpx;
	}
	.color {
		color: red;
	}
</style>

11.16代码更新:

1、地图不加载问题:
之前测试的时候代码写在window.onLoad = () => 是可以的,现在不知道怎么回事不执行了, 
解决方法:换成this.$nextTick(()=> 之后就可以了。
2、使用geolocation.getCurrentPosition方法获取定位可能出现报错:获得地理定位时间。得到ipLocation成功。获取地址失败,请检查您的密钥或网络。
解决方法:重新申请web端 JS KEY,重新生成maps.js文件。
3路线规划,重新选择终点上次的路线不能清除
解决方法:this.map.clearMap();//先清除地图覆盖物,在使用this.add_Driving();//规划路线,全局搜索this.map.clearMap(),这个方法是我新加的,测试后可以正常规划路线了。
  • 16
    点赞
  • 106
    收藏
    觉得还不错? 一键收藏
  • 36
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 36
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值