移动端H5(高德/百度/H5/公众号)获取地理定位汇总

使用uniapp示例代码

1.选择模板路径

2.在模板template.h5.html中引入

<script src="https://api.map.baidu.com/api?v=3.0&ak=自己的key&s=1" type="text/javascript" charset="utf-8"></script>
  
    <script type="text/javascript">
        window._AMapSecurityConfig = {
          securityJsCode: "自己的key",
        };
    </script>
    <script src="https://webapi.amap.com/maps?v=1.4.15&key=自己的key&plugin=AMap.Geocoder,AMap.Geolocation,AMap.Autocomplete,AMap.PlaceSearch,AMap.MarkerClusterer"></script>

<template>
	<view class="p-3">
		<view id="demo"> 经纬度:{{location}}</view>
		<view class="d-flex-center-between py-3">
			<button type="primary" plain="true" class="flex-1 mx-1" @click="gaodeLocation">高德</button>
			<button type="primary" plain="true" class="flex-1 mx-1" @click="baiduLocation">百度</button>
			<button type="primary" class="flex-1 mx-1" @click="navigatorLocation">H5</button>
			<button type="primary" disabled class="flex-1 mx-1" @click="wxLocation">公众号</button>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				location: ''
			}
		},
		onLoad() {

		},
		onReady() {
			
		},
		methods: {
			// 第三方API高德定位
			gaodeLocation() {
				var geolocation = new AMap.Geolocation();
				geolocation.getCurrentPosition(function(status, result) {
					alert('高德定位' +status+ JSON.stringify(result))
				});
			},
			// 第三方API百度定位
			baiduLocation() {
				var geolocation = new BMap.Geolocation();
				geolocation.getCurrentPosition((r) => {
					if (r) {
						alert('百度定位' + JSON.stringify(r))
						this.location = r.point.lng + ',' + r.point.lat
					}
				})
			},

			// HTML5 Geolocation(地理定位)用于定位用户的位置。

			// Internet Explorer 9+, Firefox, Chrome, Safari 和 Opera 支持Geolocation(地理定位).
			// 注意: Geolocation(地理定位)对于拥有 GPS 的设备,比如 iPhone,地理定位更加精确。
			navigatorLocation() {
				if (navigator.geolocation) {
					// alert("该浏览器支持获取地理位置。")
					navigator.geolocation.getCurrentPosition((position) => {
						let lng = position.coords.longitude;
						let lat = position.coords.latitude;
						alert(`HTML5(地理定位)lng:${lng},lat:${lat}`)
					}, (error) => {
						let msg;
						switch (error.code) {
							case 1:
								msg = "用户拒绝对获取地理位置的请求。"
								break;
							case 2:
								msg = "位置信息是不可用的。"
								break;
							case 3:
								msg = "请求用户地理位置超时。"
								break;
							case 4:
								msg = "未知错误。"
								break;
						}
						alert("获取地理位置失败。" + msg)
					})
				} else {
					alert("该浏览器不支持获取地理位置。")
				}
			},
			//js-sdk
			wxLocation() {
				alert("查看微信公众平台接口文档。")
			},
		}
	}
</script>

<style>

</style>

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值