网页如何实现调用地理位置Geolocation api和百度fUmCszw7O7G8rBv2MO4MLLNIA5DNWLoj实现和小程序一样的精准定位地址显示在输入框里。编写一个完整的html或php代码
以下是一个调用Geolocation API和百度API实现精准定位地址的HTML代码:
<!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");
}
}
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>
</head>
<body>
<input type="text" id="address">
<button onclick="getLocation()">获取地址</button>
</body>
</html>
在上述代码中,当用户点击“获取地址”按钮时,会先调用Geolocation API获取当前位置,然后将经纬度通过百度API转化为详细地址,最后将该地址显示在输入框中。需要注意的是,这里需要替换代码中的百度API密钥
原文地址: http://www.cveoy.top/t/topic/hv8E 著作权归作者所有。请勿转载和采集!