【问题标题】:How to create a radius in google map and check if marker being fetched from the database is inside circle (Android)如何在谷歌地图中创建半径并检查从数据库中获取的标记是否在圆圈内(Android)
【发布时间】:2018-08-30 02:27:00
【问题描述】:

我想知道如何在我当前的位置创建一个半径为 800 米的半径。还有如何检查我从数据库中获取的标记是否在我的圈子内。

【问题讨论】:

    标签: android google-maps google-maps-markers


    【解决方案1】:

    对于这样的任务,我有一个静态助手类。这是我用来创建圆圈的代码:

    public static CircleOptions setMapCircleMeters(LatLng latLng, float meters){
        CircleOptions options = null;
        try {
            options = new CircleOptions();
    
            options.center(latLng);
            options.radius(meters);
            options.fillColor(Color.argb(70, 80, 80, 80));
            options.strokeWidth(2.0f);
        }
        catch (Exception ex){
            Log.e(TAG, "  CircleOptions --- " + ex.getMessage());
        }
        return options;
    }
    

    您可以轻松更改fillColorstrokeWidth 的属性以满足您的需求。

    现在,要确定某个位置是否在您要检查的距离内:

    public static boolean isInRangeMeters(LatLng pt1, LatLng pt2, double meters){
        boolean inRange = false;
        try{
            double distance = getDistanceMeters(pt1, pt2);
    
            inRange = (distance <= meters);
        }
        catch (Exception ex){
            Log.e("ERROR", ex.getMessage());
        }
        return inRange;
    }
    
    public static double getDistanceMeters(LatLng pt1, LatLng pt2){
        double distance = 0d;
        try{
            double theta = pt1.longitude - pt2.longitude;
            double dist = Math.sin(Math.toRadians(pt1.latitude)) * Math.sin(Math.toRadians(pt2.latitude))
                        + Math.cos(Math.toRadians(pt1.latitude)) * Math.cos(Math.toRadians(pt2.latitude)) 
                        * Math.cos(Math.toRadians(theta));
    
            dist = Math.acos(dist);
            dist = Math.toDegrees(dist);
            distance = dist * 60 * 1853.1596;
        }
        catch (Exception ex){
            Log.e("ERROR", ex.getMessage());
        }
        return distance;
    }
    

    【讨论】:

      【解决方案2】:

      我找到了这段代码 sn-p 关于如何在 stackoverflow 上添加半径。

      //radius in meters
          Circle circle = mMap.addCircle(new CircleOptions().center(new LatLng(latitude, longitude)).radius(800).strokeColor(Color.RED));
          circle.setVisible(true);
      

      关于如何检查从数据库中获取的标记是否在半径范围内的问题,我使用

      Location.distanceBetween()Google Maps | Calculate Distance Between 2 Locations (Android Tutorials)

      然后我添加了一个 if 语句

      if (result[0] >= 450 && result[0] <= 800) {
         Toast.makeText(this, "distance: "+ result[0] + "\nBus is inside radius", Toast.LENGTH_SHORT).show();
      }
      

      【讨论】:

        猜你喜欢
        • 2018-10-24
        • 1970-01-01
        • 2014-11-09
        • 1970-01-01
        • 1970-01-01
        • 2018-09-25
        • 1970-01-01
        • 2019-02-18
        • 1970-01-01
        相关资源
        最近更新 更多