首页 > 解决方案 > 如何在定义的范围内显示标记?

问题描述

该应用程序有一个带有标记的地图,标记的可见性设置为 false,我希望当设备处于任何标记的特定范围时显示标记,结果将该标记设置为可见。我认为它与方法 location.distanceTo(anotherLocation) 有关,然后在距离小于以米为单位的预定义距离时显示位置。但我无法完成这项工作。
这是从数组列表中将标记添加到地图上的方法。

        for(MyLatLngData location : locations){
         mMap.addMarker(new MarkerOptions()
                    .position(location.getLatLng())
                    .title(location.getTitle())
                    .visible(false));
        }

这是我使用 MyLatLngData 对象将数据存储在数据库中的数组中的方法。

    void storeDataInArrays() {
        Cursor cursor = databaseHelper.readAllData();
        if (cursor.getCount() == 0) {
            Toast.makeText(this, "No data", Toast.LENGTH_SHORT).show();
        } else {
            while (cursor.moveToNext()) {
                // remove all previous list adds.
                locations.add(new MyLatLngData(
                        cursor.getString(0),
                        cursor.getString(1),
                        cursor.getDouble(2),
                        cursor.getDouble(3)));
            }
        }
    }

如何使用 distanceTo 方法考虑所有位置以及如何将第一个位置设置为 fusedLocationProvider 的当前位置。

作为补充,我希望保存标记的状态,以便设置为可见的状态将保持可见。

非常感谢任何感谢,我希望有人可以帮助我,因为我的编程技能仍在磨练中。

标签: javaandroidgoogle-mapsgoogle-maps-markers

解决方案


如果您使用location.distanceTo(anotherLocation)方法,则需要为 的每个新坐标重新计算距离location。但是,location.distanceTo(anotherLocation)您可以确定当前附近区域的纬度/经度界限(min_lat/min_lon - max_lat/max_lon),location并从具有条件б的数据库行中进行选择,例如:

Cursor myCursor = db.rawQuery("SELECT * FROM markers WHERE lon >= min_lon AND lon <= max_lon AND lat >= min_lat AND lat <= max_lat", null);

要确定区域的纬度/经度界限(min_lat/min_lon - max_lat/max_lon),您可以使用以下答案

private LatLng getDestinationPoint(LatLng source, double brng, double dist) {
    dist = dist / 6371;
    brng = Math.toRadians(brng);

    double lat1 = Math.toRadians(source.latitude), lon1 = Math.toRadians(source.longitude);
    double lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) +
                            Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
    double lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
                                    Math.cos(lat1),
                                    Math.cos(dist) - Math.sin(lat1) *
                                    Math.sin(lat2));
    if (Double.isNaN(lat2) || Double.isNaN(lon2)) {
        return null;
    }
    return new LatLng(Math.toDegrees(lat2), Math.toDegrees(lon2));
}

...

LatLng northEast = getDestinationPoint(location, 45, your_distance);
LatLng southWest = getDestinationPoint(location, 225, your_distance);

min_lat = southWest.latitude;
min_lon = southWest.longitude;

max_lat = northEast.latitude;
max_lon = northEast.longitude;

推荐阅读