基于两组地理位置坐标实现页面定向跳转的技术求助
问题描述
我正尝试编写一个PHP页面,需求如下:
- 页面将验证两组不同的坐标。第一组坐标为硬编码值,第二组坐标基于用户当前位置。
- 页面将验证用户当前位置与硬编码位置之间的距离是否在指定码数范围内。
- 若用户当前位置与硬编码位置的距离大于300码,则重定向至allow.php页面;否则重定向至denied.php页面。
我已经写了两个脚本,但无法整合实现功能,需要指导:
已编写的PHP距离计算脚本
<?php /** * Calculate the Haversine distance between two points on the Earth's surface * * @param float $lat1 The latitude of the first point * @param float $lon1 The longitude of the first point * @param float $lat2 The latitude of the second point * @param float $lon2 The longitude of the second point * @return float The distance between the two points, in kilometers */ function haversine_distance($lat1, $lon1, $lat2, $lon2) { $radius = 6371; // Earth's radius in kilometers // Calculate the differences in latitude and longitude $delta_lat = $lat2 - $lat1; $delta_lon = $lon2 - $lon1; // Calculate the central angles between the two points $alpha = $delta_lat / 2; $beta = $delta_lon / 2; // Use the Haversine formula to calculate the distance $a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin(deg2rad($beta)) * sin(deg2rad($beta)); $c = asin(min(1, sqrt($a))); $distance = 2 * $radius * $c; // Round the distance to four decimal places $distance = round($distance, 4); return $distance; } // Sample usage $lat1 = 42.291093498546616; $lon1 = -71.06439611612645; $lat2 = 42.2707685745094; $lon2 = -71.0237761587225; $distance = haversine_distance($lat1, $lon1, $lat2, $lon2); echo "The distance between ($lat1, $lon1) and ($lat2, $lon2) is $distance km."; ?>
已编写的前端获取坐标脚本
<!DOCTYPE html> <html> <body> <p>Click the button to get your coordinates.</p> <button onclick="getLocation()">Try It</button> <p id="demo"></p> <script> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML = "User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML = "Location information is unavailable." break; case error.TIMEOUT: x.innerHTML = "The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML = "An unknown error occurred." break; } } </script> </body> </html>
解决方案
要实现需求,需要把前端获取的坐标传给PHP后端计算距离,再根据结果执行重定向。以下是整合步骤和完整代码:
核心逻辑说明
- 前端自动获取用户坐标,通过AJAX将经纬度发送到PHP后端
- PHP接收参数后,用Haversine公式计算距离,并转换为码(1公里≈1093.61码)
- 根据距离阈值判断,返回指令给前端执行页面跳转
整合后的完整代码
前端页面(index.html)
<!DOCTYPE html> <html> <body> <p>正在获取您的位置...</p> <p id="status"></p> <script> const statusElement = document.getElementById("status"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(sendLocationToServer, showError); } else { statusElement.innerHTML = "浏览器不支持地理定位"; } } function sendLocationToServer(position) { const lat = position.coords.latitude; const lon = position.coords.longitude; // 发送坐标到PHP后端 fetch('check_location.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `user_lat=${lat}&user_lon=${lon}` }) .then(response => response.text()) .then(data => { // 根据后端指令跳转页面 if (data === 'allow') { window.location.href = 'allow.php'; } else if (data === 'denied') { window.location.href = 'denied.php'; } else { statusElement.innerHTML = data; } }) .catch(error => { statusElement.innerHTML = "请求失败:" + error.message; }); } function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: statusElement.innerHTML = "您拒绝了位置请求"; break; case error.POSITION_UNAVAILABLE: statusElement.innerHTML = "无法获取位置信息"; break; case error.TIMEOUT: statusElement.innerHTML = "位置请求超时"; break; case error.UNKNOWN_ERROR: statusElement.innerHTML = "发生未知错误"; break; } } // 页面加载后自动触发位置获取 window.onload = getLocation; </script> </body> </html>
PHP后端(check_location.php)
<?php /** * 计算两点间的Haversine距离,返回千米 */ function haversine_distance($lat1, $lon1, $lat2, $lon2) { $radius = 6371; // 地球半径(千米) $delta_lat = $lat2 - $lat1; $delta_lon = $lon2 - $lon1; $alpha = $delta_lat / 2; $beta = $delta_lon / 2; $a = sin(deg2rad($alpha)) ** 2 + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin(deg2rad($beta)) ** 2; $c = 2 * asin(min(1, sqrt($a))); $distance = 2 * $radius * $c; return round($distance, 4); } // 硬编码的目标坐标 $target_lat = 42.291093498546616; $target_lon = -71.06439611612645; // 校验前端传来的参数 if (!isset($_POST['user_lat']) || !isset($_POST['user_lon'])) { echo "缺少坐标参数"; exit; } $user_lat = (float)$_POST['user_lat']; $user_lon = (float)$_POST['user_lon']; // 计算距离并转换为码(1km = 1093.6133码) $distance_km = haversine_distance($target_lat, $target_lon, $user_lat, $user_lon); $distance_yards = $distance_km * 1093.6133; // 判断并返回结果 if ($distance_yards > 300) { echo 'allow'; } else { echo 'denied'; } ?>
注意事项
- 确保服务器支持PHP环境,且
allow.php和denied.php已创建 - 地理定位功能需要HTTPS环境(本地localhost测试不受限制)
- 可根据实际需求修改硬编码坐标和距离阈值
内容的提问来源于stack exchange,提问作者phqn2099
相关产品推荐
相关产品推荐

