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

实例

相关推荐
计算机学姐2 小时前
基于微信小程序的图书馆座位预约系统【uniapp+springboot+vue】
vue.js·spring boot·微信小程序·小程序·java-ee·uni-app·intellij-idea
中犇科技3 小时前
电商app源码系统推荐|开源 uniapp 商城系统
uni-app
海水冷却7 小时前
uniapp 实现直播功能的完整方案与实战指南
uni-app
wuxianda10308 小时前
Object-C/Swift/UniApp项目苹果商店上架3天极速解决方案汇报总结
ios·uni-app·objective-c·cocoa·苹果上架
WKK_8 小时前
uniapp 微信小程序使用TextEncoder,arrayBufferToBase64
微信小程序·小程序·uni-app
喜崽9 小时前
uniapp消息会话界面【消息组件一左一右】-01
uni-app
一渊之隔9 小时前
uniapp蓝牙搜索连接展示蓝牙设备包含信号显示
前端·网络·uni-app·bluetooth
喜崽10 小时前
uniapp消息会话界面【消息滚动到底部】-02
uni-app
Geek_Vison12 小时前
三款小程序容器技术选型对比分析——融媒新闻APP如何进行技术选型~
小程序·uni-app·app开发·finclip·小程序开发平台·跨端开发·小程序容器
DK185838322521 天前
知识付费会员小程序/付费圈子系统——课程兑换码+会员体系完整实战,开源运营级方案
小程序·uni-app·开源·php