方法1
通过h5 geolocation.getCurrentPosition()获取位置信息
弊端:
- 不能静默获取,需要客户端同意授权
- 需要在https协议中使用,本地文件不行
- 需要设备有GPS功能才能准确定位
function success (position) {
console.log(position)
}
function error (error) {
console.error(error)
}
function h5Geolocation () {
if (window.navigator.geolocation) {
let position = window.navigator.geolocation.getCurrentPosition(
success,
error
)
} else {
alert('该浏览器不支持定位')
}
}
方法2
通过腾讯地图服务端API获取位置信息
弊端:
- 通过ip定位,位置信息不准确
优点:
- 静默获取位置信息
function qqMapGeolocation () {
$.ajax({
type: 'get',
async: true,
url: 'https://apis.map.qq.com/ws/location/v1/ip',
data: {
key: '这里输入腾讯地图key',
output: 'jsonp'
},
dataType: 'jsonp',
success: function (result) {
console.log(JSON.stringify(result))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest, textStatus, errorThrown)
}
})
}
方法3
通过腾讯地图前端组件获取位置信息
弊端和原生的方法一样
引入cdn
<script src="https://mapapi.qq.com/web/mapComponents/geoLocation/v/geolocation.min.js"></script>
var geolocation = new qq.maps.Geolocation(
'这里输入腾讯地图key',
'输入腾讯地图referer'
)
geolocation.getLocation(success, error)
function success (position) {
console.log(position)
}
function error (error) {
console.error(error)
}
更多方法
https://lbs.qq.com/webApi/component/componentGuide/componentGeolocation
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API