H5里面获取坐标定位信息比较靠谱的方法
2022-09-26 本文已影响0人
周星星的学习笔记
前段时间,要做一个功能,就是抽奖的时候防刷,用到地理位置检测,尝试了好多种方式感觉都不太靠谱,终于用了腾讯地图定位组件之后,感觉真的很好用,记录一下。
一、使用方法
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>前端定位模块</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
<style>
* {
margin: 0;
padding: 0;
border: 0;
}
body {
position: absolute;
width: 100%;
height: 100%;
text-align: center;
}
#pos-area {
background-color: #009DDC;
margin-bottom: 10px;
width: 100%;
overflow: scroll;
text-align: left;
color: white;
}
#demo {
padding: 8px;
font-size: small;
}
#btn-area {
height: 100px;
}
button {
margin-bottom: 10px;
padding: 12px 8px;
width: 42%;
border-radius: 8px;
background-color: #009DDC;
color: white;
}
</style>
<script type="text/javascript" src="https://mapapi.qq.com/web/mapComponents/geoLocation/v/geolocation.min.js"></script>
</head>
<body>
<div id="pos-area">
<p id="demo">点击下面的按钮,获得对应信息:<br /></p>
</div>
<div id="btn-area">
<button onClick="geolocation.getLocation(showPosition, showErr, options)">获取精确定位信息</button>
<button onClick="geolocation.getIpLocation(showPosition, showErr)">获取粗糙定位信息</button>
<button onClick="showWatchPosition()">开始监听位置</button>
<button onClick="showClearWatch()">停止监听位置</button>
</div>
<script type="text/JavaScript">
var geolocation = new qq.maps.Geolocation("your key", "myapp");
document.getElementById("pos-area").style.height = (document.body.clientHeight - 110) + 'px';
var positionNum = 0;
var options = {timeout: 8000};
function showPosition(position) {
positionNum ++;
document.getElementById("demo").innerHTML += "序号:" + positionNum;
document.getElementById("demo").appendChild(document.createElement('pre')).innerHTML = JSON.stringify(position, null, 4);
document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;
};
function showErr() {
positionNum ++;
document.getElementById("demo").innerHTML += "序号:" + positionNum;
document.getElementById("demo").appendChild(document.createElement('p')).innerHTML = "定位失败!";
document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;
};
function showWatchPosition() {
document.getElementById("demo").innerHTML += "开始监听位置!<br /><br />";
geolocation.watchPosition(showPosition);
document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;
};
function showClearWatch() {
geolocation.clearWatch();
document.getElementById("demo").innerHTML += "停止监听位置!<br /><br />";
document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;
};
</script>
</body>
</html>
二、结果返回
{ "module":"geolocation",
"nation": "中国",
"province": "广东省",
"city":"深圳市",
"district":"南山区",
"adcode":"440305", //行政区ID,六位数字, 前两位是省,中间是市,后面两位是区,比如深圳市ID为440300
"addr":"深圳大学杜鹃山(白石路北250米)",
"lat":22.530001, //火星坐标(gcj02),腾讯、Google、高德通用
"lng":113.935364,
"accuracy":13 //误差范围,以米为单位
}