【发布时间】:2019-08-09 00:58:01
【问题描述】:
在 Android 版 Google 地图 v2 中,如何获取可见标记?我知道我可以使用投影并消除点 屏幕尺寸。但是我不想一一检查,如果我有很多标记,它可能会太慢。有什么简单的方法吗?还是一些现成的解决方案?如果有,是哪一个?
【问题讨论】:
标签: android google-maps-android-api-2
在 Android 版 Google 地图 v2 中,如何获取可见标记?我知道我可以使用投影并消除点 屏幕尺寸。但是我不想一一检查,如果我有很多标记,它可能会太慢。有什么简单的方法吗?还是一些现成的解决方案?如果有,是哪一个?
【问题讨论】:
标签: android google-maps-android-api-2
好的,下面是我之前用来确定用户可以看到什么然后只绘制可见标记的代码。 我认为您可以根据自己的目的调整它。
获取地图的当前矩形“视口”(注意:必须在主线程上运行)
this.mLatLngBounds = this.mMap.getProjection().getVisibleRegion().latLngBounds;
对 2 个点(左上和右下)进行排序,以便我们可以使用最小/最大逻辑
double lowLat;
double lowLng;
double highLat;
double highLng;
if (this.mLatLngBounds.northeast.latitude < this.mLatLngBounds.southwest.latitude)
{
lowLat = this.mLatLngBounds.northeast.latitude;
highLat = this.mLatLngBounds.southwest.latitude;
}
else
{
highLat = this.mLatLngBounds.northeast.latitude;
lowLat = this.mLatLngBounds.southwest.latitude;
}
if (this.mLatLngBounds.northeast.longitude < this.mLatLngBounds.southwest.longitude)
{
lowLng = this.mLatLngBounds.northeast.longitude;
highLng = this.mLatLngBounds.southwest.longitude;
}
else
{
highLng = this.mLatLngBounds.northeast.longitude;
lowLng = this.mLatLngBounds.southwest.longitude;
}
然后在我的情况下,我将这些数据保存在数据库中,因此我可以使用 >= 和
【讨论】:
您可以使用android-map-extension 库。除其他外,它还提供 List GoogleMap.getDisplayedMarkers() 方法。
【讨论】:
如果您使用 Kotlin,可以将此扩展功能添加到 GoogleMap 类
fun GoogleMap.isMarkerVisible(markerPosition: LatLng) =
projection.visibleRegion.latLngBounds.contains(markerPosition)
您只需将标记位置作为此方法的参数传递,然后对结果做任何您想做的事情。
如果您使用的是 Java,您可以在更适合您的地方声明该函数。
希望对你有帮助!
【讨论】:
您正在寻找以下任一标记: https://developers.google.com/maps/documentation/android/marker
private GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Hello world"));
或者直接画图: https://developers.google.com/maps/documentation/android/shapes
// Instantiates a new Polyline object and adds points to define a rectangle
PolylineOptions rectOptions = new PolylineOptions()
.add(new LatLng(37.35, -122.0))
.add(new LatLng(37.45, -122.0)) // North of the previous point, but at the same longitude
.add(new LatLng(37.45, -122.2)) // Same latitude, and 30km to the west
.add(new LatLng(37.35, -122.2)) // Same longitude, and 16km to the south
.add(new LatLng(37.35, -122.0)); // Closes the polyline.
// Get back the mutable Polyline
Polyline polyline = myMap.addPolyline(rectOptions);
【讨论】: