HTML5 提供定位API 供开发者使用。但是该API必须在H5环境下使用,不能是浏览器模拟,另外一点注意的是chrome浏览器不支持http获取定位,在手机端如果没有开启GPS定位,直接不返回
<script type="text/javascript" >
function getLocation() {
if (navigator.geolocation) {
console.log(navigator.geolocation);
navigator.geolocation.getCurrentPosition(showPosition,showError);
// navigator.geolocation.watchPosition(showPosition,showError);
} else {
console.log('Geolocation is not supported by this browser.');
}
}
function showPosition(position) {
console.log(position);
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
console.log('User denied the request for Geolocation.');
break;
case error.POSITION_UNAVAILABLE:
console.log('Location information is unavailable.');
break;
case error.TIMEOUT:
console.log('The request to get user location timed out.');
break;
case error.UNKNOWN_ERROR:
console.log('An unknown error occurred.');
break;
}
}
getLocation();
</script>
原生接口不太灵活,我们需要在不支持GPS定位的情况下使用IP定位,这个时候可以使用腾讯地图组件,如果是微信浏览器环境需要开通地图权限
① 引入组件
<script type="text/javascript" src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>
② 初始化对象
var geolocation = new qq.maps.Geolocation("OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77", "myapp");
③ 获取位置信息
geolocation.watchPosition(showPosition,showError);
如果是IP定位,可以借助高德API获取相关信息
$.get('https://restapi.amap.com/v3/geocode/regeo?key=你的key&callback=&location='+location,{},function(res){
if (res.status==1) {
console.log(res);
}
});
如果是微信浏览器需要初始化wx API
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: res.data.appId, // 必填,公众号的唯一标识
timestamp: res.data.timestamp, // 必填,生成签名的时间戳
nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
signature: res.data.signature, // 必填,签名
jsApiList: ['getLocation'] // 必填,需要使用的JS接口列表
});
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function(res) {
alert(JSON.stringify(res, null, 4));
});
}
});
更多使用请浏览官方API
https://lbs.qq.com/webApi/component/componentGuide/componentGeolocation