网页精准定位地址:Geolocation API 与百度地图 API 实战
<!DOCTYPE html>
<html>
<head>
<title>网页精准定位地址</title>
<meta charset='utf-8'>
<script type='text/javascript'>
function getLocation() {
//调用Geolocation API获取当前位置
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert('该浏览器不支持Geolocation API');
}
}
<pre><code> function showPosition(position) {
//将经纬度通过百度API转化为详细地址
var url = 'http://api.map.baidu.com/geocoder/v2/?ak=fUmCszw7O7G8rBv2MO4MLLNIA5DNWLoj&location=' + position.coords.latitude + ',' + position.coords.longitude + '&output=json';
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
var data = JSON.parse(request.responseText);
if (data.status == 0) {
document.getElementById('address').value = data.result.formatted_address;
} else {
alert('获取地址失败');
}
} else {
alert('获取地址失败');
}
}
}
request.send();
}
</script>
</code></pre>
</head>
<body>
<input type='text' id='address'>
<button onclick='getLocation()'>获取地址</button>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/oY0d 著作权归作者所有。请勿转载和采集!