【问题标题】:How to prevent user to put his location marker to close to already existing one如何防止用户将他的位置标记靠近已经存在的位置
【发布时间】:2015-07-29 14:55:13
【问题描述】:

在我的应用中,用户使用地图来标记他们的位置。当新用户想要创建他们的位置时,我希望阻止他们将标记靠近现有标记,如果可能的话,指定标记之间的强制距离,例如 10 或 20 米。

谢谢。

【问题讨论】:

  • 你能把你试过的代码贴出来
  • 一种解决方案是使用 Haversine 公式检查标记掉落后的距离,如果太近则显示错误。在此处查看 Haversine 公式实现:stackoverflow.com/a/27943/1007510

标签: android google-maps google-api marker


【解决方案1】:

这其实很简单,你只需要检查用户点击的点是否比你需要的距离更远,然后再移除之前的Marker并添加新的。

您可以使用Location.distanceBetween()方法进行距离检查。

首先,将您的 Marker 引用创建为 Activity 的实例变量:

Marker marker;

然后,在您的 OnMapClickListener 中,添加逻辑以仅在距离大于您定义的最小距离(本例中为 20 米)时移动用户选择作为当前位置的标记:

   mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

        @Override
        public void onMapClick(LatLng point) {

            if (marker != null) {
                LatLng markerPoint = marker.getPosition();

                float[] distance = new float[2];

                Location.distanceBetween(point.latitude, point.longitude,
                        markerPoint.latitude, markerPoint.longitude, distance);

                //check if new position is at least 20 meters away from previous selection
                if( distance[0] > 20 ){
                    //remove previous Marker
                    marker.remove();

                    //place marker where user just clicked
                    marker = mMap.addMarker(new MarkerOptions().position(point).title("My Location")
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));

                }
                else{
                    //Alert the user to select a location further away from the one already selected
                    Toast.makeText(MainActivity.this, "Please select a different location.", Toast.LENGTH_SHORT).show();
                }
            }
            else {

                //No previous selection, place marker where user just clicked
                marker = mMap.addMarker(new MarkerOptions().position(point).title("My Location")
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
            }
        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    相关资源
    最近更新 更多