uniapp根据经纬度绘制地图定位(APP端)

本篇文章用来为大家提供一个制作简单地图的思路

先来看一眼效果图

步骤:

        1.首先一定要仔细阅读uni官网获取位置文档,否则会踩大坑

        2.其次配置manifest.json文件,获取当前用户的地理位置经纬度信息。

        3.然后进行map方法绘制地图信息。

        4.滑动地图查看其它位置后,点击控件返回原地图坐标位置。

        5.点击按钮打开手机自带第三方地图APP。

1.阅读uni官方文档

注意:uni.getlocation()和map()是两个不同的方法,千万不能混淆是非

uni官网map方法icon-default.png?t=N7T8https://uniapp.dcloud.net.cn/component/map.html#
uni.getlocaton方法icon-default.png?t=N7T8https://uniapp.dcloud.net.cn/api/location/location.html#getlocation

2.配置manifest.json文件

注意:app不支持腾讯和百度地图的哦!!!

我这里演示的高德地图,也很推荐

        进行这两个地方配置

 appkey_android和appkey_ios是自己在高德地图申请的key,申请方法见我上个文章

3.获取当前用户的地理位置经纬度信息

  注意:绘制圆渐变颜色背景需要是十六进制

                https://www.cnblogs.com/shine-lovely/p/13918201.htmlicon-default.png?t=N7T8http://xn--65qysyzlrl12e0hbb9f9qpkp6blq5a

	// 获取地图定位
			getlocation() {
				var that = this
				uni.getLocation({
					type: 'gcj02', //国测局
					geocode: 'true',
					success: function(res) {
						console.log('当前位置的经度:' + res.longitude);
						console.log('当前位置的纬度:' + res.latitude);
						console.log('当前位置:' + JSON.stringify(res));
						// 创建地图坐标对象
						var point = new plus.maps.Point(res.longitude, res.latitude);
						//静态方法,反向地理编码
						plus.maps.Map.reverseGeocode(point, {}, (event) => {
							var address = event.address; // 转换后的地理位置
							that.locationaddress = address // 重新赋值
						}, function(e) {
							console.log("失败回调", e);
						});
						// 赋值经纬度,从而得到当前位置
						that.latitude = res.latitude
						that.longitude = res.longitude
						// 地图上显示所在图标开始
						let arr = [{
								id: 0,
								longitude: res.longitude,
								latitude: res.latitude,
								name: "所在位置"
							},
							{
								id: 1,
								latitude: 36.647,
								longitude: 114.550,
								name: "所在位置"
							}
						]
						let markers = []
						for (var i = 0; i < arr.length; i++) {
							markers = markers.concat({
								id: arr[i].id,
								latitude: arr[i].latitude, //纬度
								longitude: arr[i].longitude, //经度
								callout: { //自定义标记点上方的气泡窗口 点击有效
									content: arr[i].name, //文本
									color: '#ffaa00', //文字颜色
									fontSize: 18, //文本大小
									borderRadius: 8, //边框圆角
									bgColor: '#00c16f', //背景颜色
									display: 'ALWAYS', //常显
								},
								label: { //标签备注
									content: '',
									bgColor: 'red'
								},
								iconPath: '/static/dingwei.png', //	显示的图标
								width: 50,
								height: 50,
								position: { //控件位置
									left: 0,
									top: 0,
									width: 0,
									height: 0
								}
							})
						}
						that.markers = markers; // markers就是地图选点一样的功能,显示小坐标
						// 地图上显示所在图标结束
						that.controls = [{
							id: 1,
							position: { //控件在地图的位置
								left: 15,
								top: 15,
								width: 10,
								height: 10
							},
							iconPath: '/static/定位.png'
						}]
						that.circles = [{ //在地图上显示圆
								latitude: res.latitude,
								longitude: res.longitude,
								fillColor: "#3BBAFD29", //填充颜色(透明度)
								color: "#3BBAFD", //描边的颜色
								radius: 160, //半径
								strokeWidth: 2 //描边的宽度
							},
							{ //在地图上显示圆
								latitude: 36.647,
								longitude: 114.550,
								fillColor: "#3BBAFD29", //填充颜色
								color: "#3BBAFD", //描边的颜色
								radius: 100, //半径
								strokeWidth: 2 //描边的宽度 
							},
						]
					},
					// 定位失败
					fail: function(err) {
						uni.showToast({
							title: err,
							icon: 'none'
						});
					}
				})
			},

4.点击控件返回原地图坐标位置(两种控件返回原点方法)

 注意:官网显示这里的controls可能要被丢弃,建议使用cover-view方法。

<view class="page-section page-section-gap">
	<map id="map" style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude" :markers="markers" scale="16" :show-compass='true' :circles="circles" :controls="controls" show-location
				@controltap="onControltap">
			</map>
			<cover-image class="cover-view" src="/static/olddian.png" @click="onControltap"></cover-image>
</view>

// 回到定位点
			onControltap(control) {
				console.log('点击了回到原点')
				uni.createMapContext("map", this).moveToLocation({
					longitude: this.longitude,
					latitude: this.latitude,
				});
			},

5.点击按钮打开手机自带第三方地图APP(参考文档

	//点击打开第三方地图APP
			openmap() {
				// #ifdef APP
				this.openNavigation(this.longitude, this.latitude, this.locationaddress)
				//高德地图
				// #endif
			},
			//打开地图
			// 导航 会打开导航菜单供用户选择
			openNavigation(longitude, latitude, name) {
				let url = ""; // app url
				let webUrl = ""; // web url 用来为用户未安装导航软件时打开浏览器所使用url
				let qqmapkey = "Z3PBZ-88XRM-OB66T-6TPXJ-XGPM6-ZDBY6"
				plus.nativeUI.actionSheet({ //选择菜单
					title: "选择地图应用",
					cancel: "取消",
					buttons: [{
						title: "高德地图"
					}, {
						title: "百度地图"
					}, {
						title: "腾讯地图"
					}] // 可选的地图类型
				}, (e) => {
					// 判断用户选择的地图
					switch (e.index) {
						//下面是拼接url,不同系统以及不同地图都有不同的拼接字段
						case 1: //打开高德地图
							if (plus.os.name == "Android") { // 安卓
								url =
									`androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
							} else { //苹果
								url =
									`iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
							}
							webUrl =
								`https://uri.amap.com/marker?position=${longitude},${latitude}&name=${name}&src=mypage&coordinate=gaode`
							break;
						case 2: //打开百度地图
							if (plus.os.name == "Android") { // 安卓
								url =
									`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=andr.baidu.openAPIdemo&coord_type=gcj02`;
							} else { //苹果
								url =
									`iosamap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
							}
							webUrl =
								`http://api.map.baidu.com/marker?location=${latitude},${longitude}&title=${name}&content=${name}&output=html&src=webapp.baidu.openAPIdemo`
							break;
						case 3: //打开腾讯地图
							if (plus.os.name == "Android") { // 安卓
								url =
									`qqmap://map/geocoder?coord=${latitude},${longitude}&title${name}&addr=${name}=&referer=${qqmapkey}`
							} else { //苹果
								url =
									`qqmap://map/geocoder?coord=${latitude},${longitude}&title${name}&addr=${name}=&referer=${qqmapkey}`;
							}
							webUrl =
								`https://apis.map.qq.com/uri/v1/marker?marker=coord:${latitude},${longitude}&title=${name}&addr=${name}&referer=${qqmapkey}`
							break;
					}
					// 如果选中
					if (url != "") {
						url = encodeURI(url);
						// console.log(url, '地址')
						// 打开 app 导航 
						plus.runtime.openURL(url, (err) => { // 失败回到
							// 毕竟用户可能没有安装app但一定安装的有浏览器						
							// 如果失败则说明未安装 直接 打开网页版进行导航
							let chooseMap = ''
							if (e.index == 1) {
								chooseMap = "高德地图"
							} else if (e.index == 2) {
								chooseMap = "百度地图"
							} else {
								chooseMap = "腾讯地图"
							}
							uni.showModal({
								title: '提示',
								content: '检测到您本机暂未安装' + chooseMap + '应用,是否要选择使用浏览器打开?',
								confirmText: '确定', //确定文本的文字
								cancelText: '取消', //确定文本的文字
								showCancel: true, //没有取消按钮的弹框
								success: function(res) {
									if (res.confirm) {
										plus.runtime.openURL(webUrl)
										console.log('用户点击了确定')
									} else if (res.cancel) {
										console.log('用户点击了取消')
										// plus.nativeUI.alert("本机未安装指定的地图应用");
									}
								}
							})
						});
					}
				})
			}

高德地图调用API位置接口文档

百度地图调用API位置接口文档

腾讯地图调用API位置接口文档

注意:APP端打包时证书以及包名必须和申请高德地图key时填写的包名与证书必须一致!!!

贴上全部代码

<template>
	<view class="content">
		<view class="title">{{name}}</view>
		<u-button type="primary" text="获取当前位置" @click="getlocation"></u-button>
		<view class="one">经度:{{longitude}};</view>
		<view class="one">纬度:{{latitude}};</view>
		<view class="one">中文详细地址信息:{{locationaddress}}</view>
		<u-line margin="40rpx 0rpx 40rpx 0rpx"></u-line>
		<view class="page-section page-section-gap">
			<map id="map" style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude"
				:markers="markers" scale="16" :show-compass='true' :circles="circles" :controls="controls" show-location
				@controltap="onControltap">
			</map>
			<cover-image class="cover-view" src="/static/olddian.png" @click="onControltap"></cover-image>
		</view>
		<u-button type="primary" text="打开地图" @click="openmap"></u-button>
	</view>
</template> 

<script>
	export default {
		data() {
			return {
				name: 'APP获取当前位置信息-----高德地图',
				longitude: '',
				latitude: '',
				address: '',
				controls: [{
					//在地图上显示控件,控件不随着地图移动
					id: 0, //控件id
					iconPath: "/static/原点.png", //显示的图标
					clickable: true,
					position: {
						//控件在地图的位置
						left: 200,
						top: 200,
						width: 60,
						height: 60,
					},
				}, ],
				markers: '',
				locationaddress: '',
				circles: '',
			};
		},
		onLoad() {
			//APP开发获取当前的位置信息
			// #ifdef APP-PLUS
			this.getlocation(); //获取当前位置信息
			// #endif
		},
		methods: {
			// 获取地图定位
			getlocation() {
				var that = this
				uni.getLocation({
					type: 'gcj02', //国测局
					geocode: 'true',
					success: function(res) {
						console.log('当前位置的经度:' + res.longitude);
						console.log('当前位置的纬度:' + res.latitude);
						console.log('当前位置:' + JSON.stringify(res));
						// 创建地图坐标对象
						var point = new plus.maps.Point(res.longitude, res.latitude);
						//静态方法,反向地理编码
						plus.maps.Map.reverseGeocode(point, {}, (event) => {
							var address = event.address; // 转换后的地理位置
							that.locationaddress = address // 重新赋值
						}, function(e) {
							console.log("失败回调", e);
						});
						// 赋值经纬度,从而得到当前位置
						that.latitude = res.latitude
						that.longitude = res.longitude
						// 地图上显示所在图标开始
						let arr = [{
								id: 0,
								longitude: res.longitude,
								latitude: res.latitude,
								name: "所在位置"
							},
							{
								id: 1,
								latitude: 36.647,
								longitude: 114.550,
								name: "所在位置"
							}
						]
						let markers = []
						for (var i = 0; i < arr.length; i++) {
							markers = markers.concat({
								id: arr[i].id,
								latitude: arr[i].latitude, //纬度
								longitude: arr[i].longitude, //经度
								callout: { //自定义标记点上方的气泡窗口 点击有效
									content: arr[i].name, //文本
									color: '#ffaa00', //文字颜色
									fontSize: 18, //文本大小
									borderRadius: 8, //边框圆角
									bgColor: '#00c16f', //背景颜色
									display: 'ALWAYS', //常显
								},
								label: { //标签备注
									content: '',
									bgColor: 'red'
								},
								iconPath: '/static/dingwei.png', //	显示的图标
								width: 50,
								height: 50,
								position: { //控件位置
									left: 0,
									top: 0,
									width: 0,
									height: 0
								}
							})
						}
						that.markers = markers; // markers就是地图选点一样的功能,显示小坐标
						// 地图上显示所在图标结束
						that.controls = [{
							id: 1,
							position: { //控件在地图的位置
								left: 15,
								top: 15,
								width: 10,
								height: 10
							},
							iconPath: '/static/定位.png'
						}]
						that.circles = [{ //在地图上显示圆
								latitude: res.latitude,
								longitude: res.longitude,
								fillColor: "#3BBAFD29", //填充颜色(透明度)
								color: "#3BBAFD", //描边的颜色
								radius: 160, //半径
								strokeWidth: 2 //描边的宽度
							},
							{ //在地图上显示圆
								latitude: 36.647,
								longitude: 114.550,
								fillColor: "#3BBAFD29", //填充颜色
								color: "#3BBAFD", //描边的颜色
								radius: 100, //半径
								strokeWidth: 2 //描边的宽度 
							},
						]
					},
					// 定位失败
					fail: function(err) {
						uni.showToast({
							title: err,
							icon: 'none'
						});
					}
				})
			},
			// 点击刷新方法
			refresh(e) {
				this.getlocation();
			},
			// 回到定位点
			onControltap(control) {
				console.log('点击了回到原点')
				uni.createMapContext("map", this).moveToLocation({
					longitude: this.longitude,
					latitude: this.latitude,
				});
			},
			//点击打开第三方地图APP
			openmap() {
				// #ifdef APP
				this.openNavigation(this.longitude, this.latitude, this.locationaddress)
				//高德地图
				// #endif
			},
			//打开地图
			// 导航 会打开导航菜单供用户选择
			openNavigation(longitude, latitude, name) {
				let url = ""; // app url
				let webUrl = ""; // web url 用来为用户未安装导航软件时打开浏览器所使用url
				let qqmapkey = "Z3PBZ-XRM-OB66T-6TPXJ-XGPM6-ZDBY6"
				plus.nativeUI.actionSheet({ //选择菜单
					title: "选择地图应用",
					cancel: "取消",
					buttons: [{
						title: "高德地图"
					}, {
						title: "百度地图"
					}, {
						title: "腾讯地图"
					}] // 可选的地图类型
				}, (e) => {
					// 判断用户选择的地图
					switch (e.index) {
						//下面是拼接url,不同系统以及不同地图都有不同的拼接字段
						case 1: //打开高德地图
							if (plus.os.name == "Android") { // 安卓
								url =
									`androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
							} else { //苹果
								url =
									`iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
							}
							webUrl =
								`https://uri.amap.com/marker?position=${longitude},${latitude}&name=${name}&src=mypage&coordinate=gaode`
							break;
						case 2: //打开百度地图
							if (plus.os.name == "Android") { // 安卓
								url =
									`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=andr.baidu.openAPIdemo&coord_type=gcj02`;
							} else { //苹果
								url =
									`iosamap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
							}
							webUrl =
								`http://api.ap.baidu.com/marker?location=${latitude},${longitude}&title=${name}&content=${name}&output=html&src=webapp.baidu.openAPIdemo`
							break;
						case 3: //打开腾讯地图
							if (plus.os.name == "Android") { // 安卓
								url =
									`qqmap://map/geocoder?coord=${latitude},${longitude}&title${name}&addr=${name}=&referer=${qqmapkey}`
							} else { //苹果
								url =
									`qqmap://map/geocoder?coord=${latitude},${longitude}&title${name}&addr=${name}=&referer=${qqmapkey}`;
							}
							webUrl =
								`https://apis.map.qq.com/uri/v1/marker?marker=coord:${latitude},${longitude}&title=${name}&addr=${name}&referer=${qqmapkey}`
							break;
					}
					// 如果选中
					if (url != "") {
						url = encodeURI(url);
						// console.log(url, '地址')
						// 打开 app 导航 
						plus.runtime.openURL(url, (err) => { // 失败回到
							// 毕竟用户可能没有安装app但一定安装的有浏览器						
							// 如果失败则说明未安装 直接 打开网页版进行导航
							let chooseMap = ''
							if (e.index == 1) {
								chooseMap = "高德地图"
							} else if (e.index == 2) {
								chooseMap = "百度地图"
							} else {
								chooseMap = "腾讯地图"
							}
							uni.showModal({
								title: '提示',
								content: '检测到您本机暂未安装' + chooseMap + '应用,是否要选择使用浏览器打开?',
								confirmText: '确定', //确定文本的文字
								cancelText: '取消', //确定文本的文字
								showCancel: true, //没有取消按钮的弹框
								success: function(res) {
									if (res.confirm) {
										plus.runtime.openURL(webUrl)
										console.log('用户点击了确定')
									} else if (res.cancel) {
										console.log('用户点击了取消')
										// plus.nativeUI.alert("本机未安装指定的地图应用");
									}
								}
							})
						});
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		.page-section {
			position: relative;
			.cover-view {
				background: rgba(255,255,255, 0.5);
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				position: absolute;
				z-index:9999;
				right: 20rpx;
				bottom: 100rpx;				
			}
		}
	}
</style>

搞了一天,这样APP端地图定位就大功告成了,下一步继续搞定位打卡功能以及小程序定位打开功能!!!

  • 5
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱池鱼的酱酱仔

您的鼓励是我前进的动力哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值