You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript判断当前位置是否在指定300米半径圆形范围内

实现功能需要补充的逻辑说明

你现有代码存在2个明显问题:

  • 用于获取用户坐标的var myLocationLat = position.coords.latitude;等代码写在了showPosition回调函数外部,position是异步回调的参数,外部无法访问,会直接报错。
  • 缺少经纬度球面距离计算的核心逻辑,不能直接拿经纬度数值做差值比对,因为经纬度是球面坐标,需要用Haversine公式计算地球表面两点的实际距离。

具体补充步骤:

  1. 实现距离计算函数:输入两个点的经纬度,返回两点之间的距离(单位:米)
  2. 把坐标获取、距离计算、范围判断的逻辑都放到showPosition回调函数中执行
  3. 比对计算出的距离和设置的300米阈值,输出判断结果

完整修改后的代码:

<body>
    
    <button onclick="getLocation()">Try It</button>

    <p id="demo"></p>
    
    <script>
        // 餐厅的基准坐标
        var resturantLat = 47.55522178620101;
        var resturantLon = -122.34152897937625;
        var radius = 300; // 判定半径,单位米

        var myLocation = document.getElementById("demo");

        // 获取当前位置
        function getLocation() {
          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
          } else { 
            myLocation.innerHTML = "当前浏览器不支持地理定位功能";
          }
        }
        
        // Haversine公式计算两点经纬度之间的距离,返回单位为米
        function calculateDistance(lat1, lon1, lat2, lon2) {
          const R = 6371000; // 地球半径,单位米
          const dLat = (lat2 - lat1) * Math.PI / 180;
          const dLon = (lon2 - lon1) * Math.PI / 180;
          const a = 
            Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
          const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
          const distance = R * c;
          return distance;
        }

        function showPosition(position) {
          // 获取用户当前坐标
          const myLocationLat = position.coords.latitude;
          const myLocationLon = position.coords.longitude;
          // 计算和餐厅的距离
          const distance = calculateDistance(resturantLat, resturantLon, myLocationLat, myLocationLon);
          // 判定是否在范围内
          const isInRange = distance <= radius;

          // 输出结果到页面
          myLocation.innerHTML = `
            纬度: ${myLocationLat}<br>
            经度: ${myLocationLon}<br>
            和目标点距离: ${distance.toFixed(2)}米<br>
            是否在范围内: ${isInRange ? '是' : '否'}
          `;
          
          // 可以直接返回isInRange给其他业务逻辑使用
          return isInRange;
        }
    </script>
</body>

内容的提问来源于stack exchange,提问作者Fahd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:06:04