vue搭建的H5项目集成了谷歌地图,安卓手机进入地图一切正常,苹果手机进入地图,无法获取当前定位,必须刷新一下页面,才能获取定位,有什么办法可以解决
引用 皆我百晓生 小程序回复内容作答:
有几种方法可以尝试解决苹果端获取定位第一次失败的问题:
添加定位权限请求
在项目中使用HTML5的Geolocation API获取用户定位之前,首先需要请求用户的定位权限。在Vue.js中可以使用vue-geolocation或vue-browser-geolocation等插件来实现,或者直接使用原生的navigator.geolocation API。
延迟获取定位
可以使用setTimeout延迟一段时间再获取定位,因为有时候获取定位需要一些时间来初始化,在一开始的时候可能无法立即获取到定位。
添加定位超时处理
在获取定位的时候可以设置一个超时时间,当超过指定时间后停止获取定位并提示用户手动刷新页面。
使用原生API
对于Apple设备,可以考虑使用原生的API来获取定位信息,如使用cordova-plugin-geolocation插件或React Native的Geolocation API。
以上方法可能有助于解决苹果端获取定位第一次失败的问题,可以根据具体情况选择合适的方法进行尝试。
【相关推荐】
<template>
<gmap-map :center="centers" :zoom="11" style="width: 300px; height: 300px" @click="updateMaker">
<gmap-marker :position="position" :draggable="true" @dragend="updateMaker"/>
</gmap-map>
</template>
<script>
import axios from 'axios';
import { gmapApi } from 'vue2-google-maps'
export default {
props: {
position: {
type: Object,
default: () => {
return {
lat: 43.648509660046656,
lng: -79.3789402652274
}
}
}
},
data() {
return {
place: null
};
},
computed: {
google: gmapApi, // 获取官方的OBject 使用官方API的时候可以用
centers() {
return {
lat: this.position.lat,
lng: this.position.lng
}
}
},
created() {},
mounted() {
},
methods: {
updateMaker: function(event) {
console.log('updateMaker, ', event.latLng.lat(), event.latLng.lng());
this.position = {
lat: event.latLng.lat(),
lng: event.latLng.lng()
}
this.pointToAddress(this.position.lat, this.position.lng, this.pushAddress)
},
pushAddress(res) {
this.$emit('mark', res, this.position)
},
pointToAddress(lat, lng, backcall) {
// 实例化Geocoder服务用于解析地址
var geocoder = new this.google.maps.Geocoder();
// 地理反解析
geocoder.geocode({ location: new this.google.maps.LatLng(lat, lng) }, function geoResults(results, status) {
if (status === this.google.maps.GeocoderStatus.OK) {
backcall(results[0].formatted_address);
} else {
console.log(':error ' + status);
}
});
}
}
};
</script>
<style lang="scss" scoped>
</style>
以上 gmap-marker 是定位点组件,支持传入坐标展示定位点。pointToAddress方法支持获取你选的点的地理位置信息,当然这个方法是vue2-google-maps自己封装的,你也可以自己封装,比他这个好用,具体方式参考
谷歌地图API文档