<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>移动端获取用户地理位置</title>
<script type="text/javascript" src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="./js/getPosition.js"></script>
</head>
<body>
<p>页面加载弹窗获取用户地理位置</p>
</body>
</html>
<script>
//获取当前位置的经纬度
function getCoordinate(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
let latitude = position.coords.latitude
let longitude = position.coords.longitude
getProAndCity(latitude,longitude)
},
function (e) {
throw(e.message);
}
)
}
}
// 通过当前经纬度和百度map查找对应省市
function getProAndCity(latitude,longitude){
$.ajax({
url: ‘http://api.map.baidu.com/geocoder/v2/?ak=wWYw0yCb8ntXmSgTxTx40vKR&callback=renderReverse&location=‘ + latitude + ‘,‘ + longitude + ‘&output=json&pois=1‘,
type: "get",
dataType: "jsonp",
jsonp: "callback",
success: function (data) {
alert(data.result.addressComponent.province);
alert(data.result.addressComponent.city);
alert(data.result.addressComponent.district);
if (typeof callback == "function") {
callback(data);
}
} ,
error:function(){
alert(‘err‘)
}
});
}
getCoordinate()
</script>
<style>
html,body{
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
p{
font-size: 14px;
}
</style>
有些机型没效果,在改