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

实例

相关推荐
云起SAAS1 小时前
小智笔记APP源码 | 8大广告联盟聚合(穿山甲/优量汇/快手/百度) | 应用市场过审极速版 | uni-app全栈商用项目
笔记·uni-app·广告联盟·笔记app
蹦哒4 小时前
UniApp 原生插件开发完整指南
uni-app
a_Ichuan4 小时前
在HBuilderX创建的uniapp项目中使用unocss
前端·uni-app
web前端神器4 小时前
记录uniapp小程序的报错
小程序·uni-app·apache
学传打活5 小时前
【边打字.边学昆仑正义文化】_21_爱的结晶(1)
微信公众平台·1024程序员节·汉字·昆仑正义文化
yqcoder7 小时前
uni-app 之 网络请求
网络·uni-app
克里斯蒂亚诺更新7 小时前
uniapp适配H5和Android-apk实现获取当前位置经纬度并调用接口
android·前端·uni-app
2501_9160088919 小时前
深入解析iOS应用启动性能优化策略与实践
android·ios·性能优化·小程序·uni-app·cocoa·iphone
巴巴博一1 天前
uni-app 踩坑实录:实现“可拖拽全局悬浮按钮”时的 movable-view 坐标失效与 Flex 布局视错觉
vue.js·uni-app
阿奇__1 天前
h5微信授权code失效排查过程及解决记录
微信·uni-app