使用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>