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

实例

相关推荐
行云流水6262 小时前
uniapp pinia实现数据持久化插件
前端·javascript·uni-app
zhangyao9403302 小时前
uniapp动态修改 顶部导航栏标题和右侧按钮权限显示隐藏
前端·javascript·uni-app
2501_916007475 小时前
iOS 压力测试的工程化体系,构建高强度、多维度、跨工具协同的真实负载测试流程
android·ios·小程序·uni-app·cocoa·压力测试·iphone
紫麦熊6 小时前
react+ts+vite+tailwind+shadcn
1024程序员节
日日行不惧千万里6 小时前
MediaMTX详解
1024程序员节
2501_916008897 小时前
API接口调试全攻略 Fiddler抓包工具、HTTPS配置与代理设置实战指南
前端·ios·小程序·https·fiddler·uni-app·webview
2501_915921439 小时前
iOS 开发者工具推荐,构建从调试到性能优化的多维度生产力工具链(2025 深度工程向)
android·ios·性能优化·小程序·uni-app·iphone·webview
金融小师妹10 小时前
基于LSTM-GARCH模型:三轮黄金周期特征提取与多因子定价机制解构
人工智能·深度学习·1024程序员节
00后程序员张11 小时前
全面解析网络抓包工具使用:Wireshark和TCPDUMP教程
网络·ios·小程序·uni-app·wireshark·iphone·tcpdump
游戏开发爱好者811 小时前
Mac 抓包软件怎么选?从 HTTPS 调试、TCP 数据流分析到多工具协同的完整抓包方案
tcp/ip·macos·ios·小程序·https·uni-app·iphone