國內(nèi)需要vpn 和申請谷歌地圖的Maps JavaScript API 類型的 key,指引鏈接這里不詳細(xì)介紹
一 、我們得通過webview 跳轉(zhuǎn)谷歌地圖 ,需要創(chuàng)建一個webview頁面,里面跳轉(zhuǎn)承載谷歌地圖的html頁面,如果是放在本地的話 html文件須遵守規(guī)范 放在 "項(xiàng)目根目錄下->hybrid->html->google-map.html" 或static目錄下
image.png
//跳轉(zhuǎn)谷歌地圖前頁面,比如選擇地址
<template>
<view @click="onSkip('/pages/mapWeb')">
即將前往選擇地址
</view>
</template>
<script>
export default {
data() {
return {}
},
onLoad(e) {
//接收webview傳值,能拿到經(jīng)緯度 詳細(xì)地址等信息
uni.$on('googleMsg', (data) => {
console.log('接收到值,繼續(xù)業(yè)務(wù)處理', data)
});
},
methods: {
//跳轉(zhuǎn)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: {
//監(jiān)聽html返回的數(shù)據(jù)
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才能接收到數(shù)據(jù) 監(jiān)聽到事件
<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);
// 調(diào)用地理編碼服務(wù)的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 get() {
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: "當(dāng)前位置!"
});
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>
//本段代碼來源于網(wǎng)絡(luò) 僅作自己記錄方便后期查詢,和給正在踩坑的友友們一個借鑒 侵刪
以上就是所有獲取谷歌選點(diǎn)定位的流程
以下是當(dāng)用戶輸入地址 ,實(shí)現(xiàn)地址解析的方法
// 解析地址
//用戶輸入時可以動態(tài)調(diào)用這個函數(shù) 也可以當(dāng)用戶輸入完成,根據(jù)自己的業(yè)務(wù)邏輯調(diào)整
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響應(yīng)
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
// 在這里可以使用解析后的位置信息進(jìn)行后續(xù)操作
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內(nèi)嵌套h5的另一套代碼系統(tǒng)里面也需要使用谷歌地圖,這怎么辦呢 h5接收不到webview返回的值;原理都大差不差就得用原生js的方法來實(shí)現(xiàn),下面紙列出了有變動的代碼 其他的都和上面一樣
//跳轉(zhuǎn)谷歌地圖前頁面
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拿到返回的數(shù)據(jù) 處理業(yè)務(wù)邏輯啦', 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 頁面 的返回函數(shù)改成這樣
function onBack(data) {
localStorage.setItem('LocationAddress', JSON.stringify(data));
history.back();
}