获取手机当前位置经纬度 - HTML & JavaScript 示例
<!DOCTYPE html>
<html>
<head>
<title>获取手机当前位置经纬度</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
<pre><code>function showPosition(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
// 发送POST请求将经纬度传递给后台处理
$.post("/getaddress", {latitude: latitude, longitude: longitude}, function(data) {
alert("当前手机所在地址的经纬度是:" + data.latitude + ", " + data.longitude);
});
}
</code></pre>
</script>
</head>
<body>
<button onclick="getLocation()">获取经纬度</button>
</body>
</html>
<p>本示例展示了如何使用HTML和JavaScript编写一个网页,通过POST请求获取当前手机所在地址的经纬度,并在点击按钮后弹窗显示结果。首先,我们使用<code>navigator.geolocation.getCurrentPosition()</code>方法获取设备位置信息。然后,通过POST请求将经纬度数据发送给后台处理。这里使用jQuery的<code>$.post()</code>方法发送POST请求,请求URL为<code>"/getaddress"</code>,发送数据为<code>{latitude: latitude, longitude: longitude}</code>。最后,在回调函数中弹窗显示获取到的经纬度。</p>
<p>请注意,<code>"/getaddress"</code>只是一个示意的URL,需要将其替换为你自己的后台处理URL。在后台处理程序中解析POST请求,并使用适当的方法获取地址信息。</p>
原文地址: https://www.cveoy.top/t/topic/qFJ2 著作权归作者所有。请勿转载和采集!