我越来越接近LatLng,如下所示:
mFarLeft = mMapView.getProjection().getVisibleRegion().farLeft;
mFarRight = mMapView.getProjection().getVisibleRegion().farRight;
mNearLeft = mMapView.getProjection().getVisibleRegion().nearLeft;
mNearRight = mMapView.getProjection().getVisibleRegion().nearRight;
现在,我如何计算这个远点和近点之间的距离? 是否有任何方法可以在KM和Feet中获得距离?
根据Android farLeft
,字段farRight
,LatLng
等实际上是documentation对象。但是,有一个字段latLngBounds
,它代表包括可见区域的最小边界框。这个边界对象本身有两个LatLng
字段用于框的东北角和西南角。使用Haversine公式,我们可以计算此框角落之间的距离。例如,如果您想计算边界框的高度,我们可以尝试:
public static double haversine(double lat1, double lon1, double lat2, double lon2) {
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.pow(Math.sin(dLat / 2),2) + Math.pow(Math.sin(dLon / 2),2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.asin(Math.sqrt(a));
return 6372.8 * c; // in kilometers
// if you want to return feet, then use 6372.8 * 3280.84 instead
}
public static void main(String[] args) {
LatLng ne = mMapView.getProjection().getVisibleRegion().latLngBounds.northeast;
LatLng sw = mMapView.getProjection().getVisibleRegion().latLngBounds.southwest;
double latLow = sw.latitude;
double latHigh = ne.latitude;
double longitude = sw.longitude;
// now compute the "height" of the bounding box
// note that the longitude value is the same
double height = haversine(latLow, longitude, latHigh, longitude);
}
Google为地图提供了一个实用程序库,其中包括:
Calculate distances, areas and headings via spherical geometry
使用
SphericalUtil
中的球面几何实用程序,您可以根据纬度和经度计算距离,面积和标题。以下是该实用程序中可用的一些方法:
computeDistanceBetween()
- 返回两个纬度/经度坐标之间的距离(以米为单位)。computeHeading()
- 返回两个纬度/经度坐标之间的方位(以度为单位)。computeArea()
- 返回地球上封闭路径的面积(平方米)。interpolate()
- 返回位于两个给定点之间距离的给定部分的点的纬度/经度坐标。例如,您可以使用它来为两点之间的标记设置动画。有关该实用程序中方法的完整列表,请参阅reference documentation。
该图书馆位于maven中心。
dependencies {
compile 'com.google.maps.android:android-maps-utils:0.5+'
}
资料来源:https://developers.google.com/maps/documentation/android-api/utility/