JavaScript 获取用户经纬度并显示地址 - 使用百度地图API
<!DOCTYPE html>
<html>
<head>
<title>获取用户经纬度并显示地址</title>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert('Geolocation is not supported by this browser.');
}
}
<pre><code> function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var coordinates = latitude + ',' + longitude;
// 使用经纬度获取准确位置的代码
// 这里可以使用第三方的地图API,比如百度地图API、谷歌地图API等
// 以下示例使用百度地图API
var url = 'https://api.map.baidu.com/geocoder/v2/?ak=YOUR_API_KEY&location=' + coordinates + '&output=json';
fetch(url)
.then(response => response.json())
.then(data => {
var address = data.result.formatted_address;
document.getElementById('location').innerHTML = '当前位置:' + address;
})
.catch(error => {
console.log(error);
});
}
</script>
</code></pre>
</head>
<body>
<button onclick="getLocation()">获取经纬度</button>
<p id="location"></p>
</body>
</html>
<p>请替换YOUR_API_KEY为你的百度地图API密钥。</p>
原文地址: https://www.cveoy.top/t/topic/mT5i 著作权归作者所有。请勿转载和采集!