h5应用获取当前位置,计算到商家距离,并调用地图导航应用的实现

baidu地图使用介绍:文档:http://lbsyun.baidu.com/index.php?title=jspopular
1、获取位置、计算距离:
1)使用baidu的map,先申请密钥:
申请密钥(ak)地址:http://lbs.baidu.com/apiconsole/key?application=key
2)引入api:

function MP() {
	const ak = '1NV70dFhCLQGi8u303C3pZT2scjw4ijo'
	return new Promise(function(resolve, reject) {
		window.onload = function() {
			resolve(BMap)
		}
		var script = document.createElement("script");
		script.type = "text/javascript";
		// script.src = "http://api.map.baidu.com/api?v=3.0&ak=" + ak;//3.0版本,导入后一直报ak无效,2.0版本可以用
		script.src = "http://api.map.baidu.com/api?v=2.0&ak=" + ak + "&callback=init"; //2.0版本
		script.onerror = reject;
		document.head.appendChild(script);
	})
}
MP(); //在页面导入baidu的api

3)获取用户当前位置,并计算距离:

//获取距离:
function getLocation({
	payload,
	callback
} = {}) {
	let geolocation = new BMap.Geolocation();
	const {
		Lng,
		Lat,
	} = payload;
	if (geolocation) {
		geolocation.getCurrentPosition((position) => {
			let map = new BMap.Map();
			let Longitude = position.longitude; //获取用户的经度
			let Latitude = position.latitude; //获取用户的纬度	
			let pointA = new BMap.Point(Longitude, Latitude); //用户的经纬度
			let pointB = new BMap.Point(Lng, Lat); //从数据库中取出商家的经纬度
			const distance = ((map.getDistance(pointA, pointB)) / 1000).toFixed(1) + 'km';
			callback && callback(distance);//回调函数,返回数据到页面上
		}, showError);
		//如果getCurrentPosition()运行成功,则向参数showPosition中规定的函数返回一个coordinates对象
		//getCurrentPosition()方法的第二个参数showError用于处理错误。它规定当获取用户位置失败时运行的函数
	} else {
		console.log("该设备浏览器不支持地理定位");
	}
}

function showError(error) {
	switch (error.code) {
		case error.PERMISSION_DENIED:
			console.log("用户不允许地理定位")
			break;
		case error.POSITION_UNAVAILABLE:
			console.log("无法获取当前位置")
			break;
		case error.TIMEOUT:
			console.log("操作超时")
			break;
		case error.UNKNOWN_ERROR:
			console.log("未知错误")
			break;
	}
}

2、调用地图导航,直接用 a 标签

  1. 使用百度地图((可以传经纬度,也可以传中文地址)
    参考: https://lbsyun.baidu.com/index.php?title=uri/api/web

  2. 使用高德地图(不能只传中文地址)
    参考: https://lbs.amap.com/api/uri-api/summary

使用百度举例
href参数:

/*
传的参数:
location(lat<纬度>,lng<经度):data.Lat(目的地的纬度),data.Lng(目的地的经度);
title(标注点显示标题):data.DisplayName(目的地名称);
content(标注点显示内容):data.Address(目的地地址);
*/
<a href="'http://api.map.baidu.com/marker?location='+data.Lat+','+data.Lng+'&title='+data.DisplayName+'&content='+data.Address+'&output=html&src=webapp.baidu.openAPIdemo'">导航</a>
发布了18 篇原创文章 · 获赞 0 · 访问量 361

猜你喜欢

转载自blog.csdn.net/weixin_39788999/article/details/104245891
今日推荐