uniapp app端使用谷歌地图选点定位

国内需要vpn 和申请谷歌地图的Maps JavaScript API 类型的 key,指引链接这里不详细介绍

一 、我们得通过webview 跳转谷歌地图 ,需要创建一个webview页面,里面跳转承载谷歌地图的html页面,如果是放在本地的话 html文件须遵守规范 放在 “项目根目录下->hybrid->html->google-map.html” 或static目录下
image.png

//跳转谷歌地图前页面,比如选择地址 
<template>
	<view @click="onSkip('/pages/mapWeb')">
		即将前往选择地址
	</view>
</template>
<script>
	export default {
		data() {
			return {}
		},
		onLoad(e) {
			//接收webview传值,能拿到经纬度 详细地址等信息
			uni.$on('googleMsg', (data) => {
				console.log('接收到值,继续业务处理', data)
			});
		},
		methods: {
			//跳转webview
			onSkip(url) {
				uni.navigateTo({
					url: url
				})
			},
		}
	}
</script>
//webview 页面  ,如果谷歌地图不是放本地 src 放线上路径即可
<template>
	<view>
		<web-view style="width: 100vw;height: 100vh;" src="../hybrid/html/google-map.html"
			@message="postMessageFun"></web-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {	}
		},
		methods: {
//监听html返回的数据
			postMessageFun(e) {
				console.log(e.detail.data[0], "77777")
			uni.$emit("googleMsg", e.detail.data[0])
			}
		}
	}
</script>
//google-map.html 页面
<!DOCTYPE html>
<html style="width: 100vw;height: 100vh;">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<script src="https://maps.googleapis.com/maps/api/js?key=你的谷歌地图key&sensor=false">
		</script>
     //引入uniapp webview才能接收到数据 监听到事件
		<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js">
		</script>
		<script>
			function onBack(data) {
				var timer = setInterval(function() {
					if (window.uni) {
						clearInterval(timer);
						uni.postMessage({
								data: data
							}),
							console.log("谷歌地图返回:",data)
							uni.navigateBack()
					}
				}, 10)

			}
			// 谷歌地址解析
			function reverseGeocode(lat, lng) {
				var geocoder = new google.maps.Geocoder();
				var latlng = new google.maps.LatLng(lat, lng);
				// 调用地理编码服务的geocode方法
				geocoder.geocode({
					'location': latlng
				}, (results, status) => {
					if (status === 'OK') {
						if (results[0]) {
							const obj = {
								address: results[0].formatted_address,
								lat: lat,
								lng: lng
							}
							console.log(results)
							// console.log('地址:', obj);
							onBack(obj)
						} else {
							console.log('未找到地址');
						}
					} else {
						console.log('逆地理编码失败:' + status);
					}
				});
			}

			function initialize() {
				function success(position) {
					console.log(position)
					var latitude = position.coords.latitude;
					var longitude = position.coords.longitude;
					var yourmap = {
						center: new google.maps.LatLng(latitude, longitude),
						zoom: 11,
						mapTypeId: google.maps.MapTypeId.ROADMAP
					};
					var map = new google.maps.Map(document.getElementById("googleMap"), yourmap);
					var marker = new google.maps.Marker({
						position: new google.maps.LatLng(latitude, longitude),
					});

					marker.setMap(map);
					var infowindow = new google.maps.InfoWindow({
						content: "当前位置!"
					});
					infowindow.open(map, marker);
					google.maps.event.addListener(map, 'click', function(e) {
						reverseGeocode(e.latLng.lat(), e.latLng.lng())
					})
				};

				function addMarker(longitude, latitude) {
					const marker = {
						id: this.markers.length + 1,
						longitude,
						latitude,
						iconPath: '/static/marker.png',
						width: 20,
						height: 20
					};
					this.markers.push(marker);
					this.mapContext.addMarkers({
						markers: this.markers,
						clear: true
					});
				}

				function error(e) {
					alert('地理位置不可用fa',e);
				};


				if ("geolocation" in navigator) {
					navigator.geolocation.getCurrentPosition(success, error);
				} else {
					alert('地理位置不可用ter');
				}
			};
			google.maps.event.addDomListener(window, 'load', initialize);
		</script>
	</head>
	<body>
		<div id="googleMap" style="width:100vw;height:100vh;"></div>
	</body>
</html>
//本段代码来源于网络 仅作自己记录方便后期查询,和给正在踩坑的友友们一个借鉴 侵删

以上就是所有获取谷歌选点定位的流程
以下是当用户输入地址 ,实现地址解析的方法

	// 解析地址
//用户输入时可以动态调用这个函数 也可以当用户输入完成,根据自己的业务逻辑调整
			getGoogleLocation(address) {
				if (!address) return
						const apiKey = '你的谷歌地图key';
				const url =`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=${apiKey}`;
				uni.request({
					url: url,
					method: 'GET',
					success: (res) => {
						console.log("res:", res)
						// 解析API响应
						const results = res.data.results;
						if (results.length > 0) {
							// 获取解析后的位置信息
							const location = results[0].geometry.location;
							const latitude = location.lat;
							const longitude = location.lng;
							this.userInfo.newAddress = address
							this.userInfo.longitude = longitude
							this.userInfo.latitude = latitude
							this.userInfo.address = address
							// 在这里可以使用解析后的位置信息进行后续操作
							console.log("Latitude:", latitude);
							console.log("Longitude:", longitude);
						} else {
							uni.showToast({
								title: '未查询到该地址,请重试',
								icon: 'none'
							})
							console.log("No results found.");
						}
					},
					fail: (err) => {
						console.log("Error:", err);
					}
				});
			},

奇葩需求: app内嵌套h5的另一套代码系统里面也需要使用谷歌地图,这怎么办呢 h5接收不到webview返回的值;原理都大差不差就得用原生js的方法来实现,下面纸列出了有变动的代码 其他的都和上面一样

//跳转谷歌地图前页面 
mounted(){
		const key = 'LocationAddress';
				const data = localStorage.getItem(key);
				localStorage.removeItem(key);
				if (typeof data !== "string") return;
				const x = JSON.parse(data);
				console.log('===x拿到返回的数据 处理业务逻辑啦', x);
}
/webview 页面 
<template>
	<view>
		<iframe id="iframe" src="../../../static/html/google-map.html"></iframe>
	</view>
</template>

<script>
	var iframe = document.getElementById('iframe');
	window.addEventListener('message', (e) => {
		console.log(e, 'eeeeee')
	}, false);
</script>
//google-map.html 页面 的返回函数改成这样
      function onBack(data) {
			localStorage.setItem('LocationAddress', JSON.stringify(data));
			history.back();
        }

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值