uniApp 加载google地图 并规划路线

uniApp 加载google地图 并规划路线

备注:

打开谷歌地图失败的话 参考google开发文档

javascript 复制代码
https://developers.google.com/maps/documentation/urls/ios-urlscheme?hl=zh-cn#swift

核心代码

javascript 复制代码
mounted() {
	this.loadGoogleMapsScript();
},
methods: {
    //加载
	loadGoogleMapsScript() {
		const script = document.createElement('script');
		script.src =
			'https://maps.googleapis.com/maps/api/js?key=你自己的Key';
		script.async = true;
		script.defer = true;
		window.initMap = this.initMap; // 将 initMap 方法绑定到全局作用域
		document.head.appendChild(script);
	},
	//初始化
	initMap() {
		//获取当前的定位   经纬度
		navigator.geolocation.getCurrentPosition(position => {
			const {
				latitude,
				longitude
			} = position.coords;

			console.log("pos", position);

			const pos = {
				lat: latitude,
				lng: longitude
			};
			//加载到地图
			this.map = new google.maps.Map(document.getElementById('map'), {
				center: {
					lat: latitude,
					lng: longitude
				},
				zoom: 8,
			});


			// this.map = new google.maps.Map(document.getElementById('map'), {
			// 	center: {
			// 		lat: -34.397,
			// 		lng: 150.644
			// 	},
			// 	zoom: 8,
			// });

			// 设置起点和终点
			const start = new google.maps.LatLng(latitude, longitude);
			console.log(latitude, longitude);
			console.log(latitude + 1, longitude + 1);
			const end = new google.maps.LatLng(latitude + 1, longitude + 1);

			// 创建方向服务和方向渲染器实例
			const service = new google.maps.DirectionsService();
			const renderer = new google.maps.DirectionsRenderer({
				map: this.map
			});
			renderer.setMap(map);

			// 计算路径并在地图上显示
			service.route({
				origin: start,
				destination: end,
				travelMode: 'DRIVING', // 可选值:'DRIVING'(驾驶)、'WALKING'(步行)、'BICYCLING'(骑行)、'TRANSIT'(公共交通)
			}, (response, status) => {
				if (status === 'OK') {
					renderer.setDirections(response);
				} else {
					console.error('Directions request failed!');
				}
			});
		});
	},
},

实例

相关推荐
2501_9151063215 小时前
iOS性能调优的系统化实践,从架构分层到多工具协同的全流程优化指南(开发者深度版)
android·ios·小程序·架构·uni-app·iphone·webview
liu****17 小时前
18.HTTP协议(一)
linux·网络·网络协议·http·udp·1024程序员节
洛_尘17 小时前
JAVA EE初阶 6: 网络编程套接字
网络·1024程序员节
TE-茶叶蛋1 天前
Uniapp运行MuMu模拟器
uni-app
2301_800256111 天前
关系数据库小测练习笔记(1)
1024程序员节
一人一程温一壶酒1 天前
微信小程序uniapp开发附源码——图片加水印
微信小程序·uni-app·notepad++
一个假的前端男1 天前
uniapp 3端轮播
前端·javascript·uni-app
Memory沙漏1 天前
IOS如何免费申请开发者证书(uniapp开发)
ios·uni-app
集成显卡1 天前
AI取名大师 | uni-app + Wot UI 跟随设备自动切换明暗主题
人工智能·ui·uni-app·外观配色
zhangyao9403301 天前
uni-app scroll-view特定情况下运用
前端·javascript·uni-app