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!');
				}
			});
		});
	},
},

实例

相关推荐
unable code10 小时前
CTF-SPCS-Forensics
网络安全·ctf·misc·1024程序员节·取证
码云数智-园园1 天前
uni-app 实现物流进度跟踪功能:从 UI 到数据驱动的完整方案
ui·uni-app
unable code1 天前
内存取证-卡比卡比卡比
网络安全·ctf·misc·1024程序员节·内存取证
学传打活2 天前
【边打字.边学昆仑正义文化】_3_宇宙人类演化史(2)
微信公众平台·1024程序员节·汉字·昆伦正义文化
unable code2 天前
内存取证-Stager
网络安全·ctf·misc·1024程序员节·内存取证
予你@。3 天前
UniApp + Vue3 实现 Tab 点击滚动定位(微信小程序)
微信小程序·小程序·uni-app
游戏开发爱好者83 天前
完整教程:App上架苹果App Store全流程指南
android·ios·小程序·https·uni-app·iphone·webview
予你@。3 天前
uni-app progress 组件使用详解
uni-app
iOS阿玮3 天前
春节提审高峰来袭!App Store 审核时长显著延长。
uni-app·app·apple
开开心心就好3 天前
轻松加密文件生成exe,无需原程序解密
linux·运维·服务器·windows·pdf·harmonyos·1024程序员节