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

实例

相关推荐
行走的陀螺仪10 小时前
uni-app + Vue3编辑页/新增页面给列表页传参
前端·vue.js·uni-app
森之鸟12 小时前
uniapp——配置鸿蒙环境,进行真机调试
华为·uni-app·harmonyos
2501_9159184114 小时前
常见 iOS 抓包工具的使用,从代理抓包、设备抓包到数据流抓包
android·ios·小程序·https·uni-app·iphone·webview
handsome091616 小时前
uniapp打包的app,报This app was built with the iOS 18.1 SDK解决方案
ios·uni-app
yqcoder17 小时前
uni-app 之 下拉刷新
运维·服务器·uni-app
liu_bees19 小时前
微信小程序Canvas生成图片失败:canvas is empty问题解析
微信小程序·小程序·uni-app·vue
木子啊20 小时前
Uni-app性能优化:分包与长列表实战
性能优化·uni-app
yqcoder21 小时前
uni-app 之 设置 tabBar
运维·服务器·uni-app
家里有只小肥猫1 天前
uniApp下拉渐变头部 拿来即用
前端·javascript·uni-app
fanruitian1 天前
uniapp android开发 测试板本与发行版本
前端·javascript·uni-app