Google Maps iOS SDK:地图上东西点之间的距离

Luc*_*lla 5 ios google-maps-sdk-ios

如何计算地图东点和西点之间的距离(以米为单位)?假设用户改变了滚动地图的位置,然后我用mapView:didChangeCameraPosition:delegate方法捕捉到了移动,但我不知道如何计算距离.

Sax*_*uce 10

这是一个辅助函数,可用于计算两个坐标之间的距离:

double getDistanceMetresBetweenLocationCoordinates(
    CLLocationCoordinate2D coord1, 
    CLLocationCoordinate2D coord2)
{
    CLLocation* location1 = 
        [[CLLocation alloc] 
            initWithLatitude: coord1.latitude 
            longitude: coord1.longitude];
    CLLocation* location2 = 
        [[CLLocation alloc] 
            initWithLatitude: coord2.latitude 
            longitude: coord2.longitude];

    return [location1 distanceFromLocation: location2];
}
Run Code Online (Sandbox Code Playgroud)

更新:

这取决于您在地图的"东"和"西"的含义,因为地图可能会旋转或倾斜.即使它没有倾斜或旋转,由于地球的曲率,地图的顶部和底部之间的地图宽度将以米为单位(靠近赤道的边缘将比边缘更宽)离赤道更远的地方).你变化越大,差异越小.

但是假设你想要在地图的左下角和右下角之间以米为单位,你可以使用:

GMSMapView* mapView = ...;

CLLocationCoordinate2D bottomLeftCoord = 
    mapView.projection.visibleRegion.nearLeft;
CLLocationCoordinate2D bottomRightCoord = 
    mapView.projection.visibleRegion.nearRight;
double distanceMetres = getDistanceMetresBetweenLocationCoordinates(
    bottomLeftCoord, bottomRightCoord);
Run Code Online (Sandbox Code Playgroud)

如果要考虑旋转/倾斜,可以将可见区域包裹在a中GMSCoordinateBounds,然后计算东南角和西南角之间的距离,例如:

GMSMapView* mapView = ...;

GMSCoordinateBounds* bounds = [[GMSCoordinateBounds alloc] 
    initWithRegion: mapView.projection.visibleRegion];
CLLocationCoordinate2D southWest = bounds.southWest;
CLLocationCoordinate2D southEast = CLLocationCoordinate2DMake(
    bounds.southWest.latitude, bounds.northEast.longitude);
double distanceMetres = getDistanceMetresBetweenLocationCoordinates(
    southWest, southEast);
Run Code Online (Sandbox Code Playgroud)

然而,这可能比屏幕上实际可见的区域更宽,因为GMSCoordinateBounds可见区域的四边形包裹在轴对齐的边界框中.

另一种选择是在地图视图的框架的每一侧选择点,然后使用地图视图的投影将它们转换为纬度/经度,例如:

GMSMapView* mapView = ...;

CGPoint middleLeftPoint = CGPointMake(
    0, mapView.frame.size.height / 2);
CGPoint middleRightPoint = CGPointMake(
    mapView.frame.size.width, mapView.frame.size.height / 2);

CLLocationCoordinate2D middleLeftCoord = 
    [mapView.projection coordinateForPoint: middleLeftPoint];
CLLocationCoordinate2D middleRightCoord = 
    [mapView.projection coordinateForPoint: middleRightPoint];

double distanceMetres = getDistanceMetresBetweenLocationCoordinates(
    middleLeftCoord, middleRightCoord);
Run Code Online (Sandbox Code Playgroud)


cbo*_*wns 5

Google Maps iOS SDK 包含一堆几何帮助器

你想要这个功能:

GMSGeometryDistance (CLLocationCoordinate2D from, CLLocationCoordinate2D to) -> CLLocationDistance
Run Code Online (Sandbox Code Playgroud)

“返回地球上两个坐标之间的大圆距离(以米为单位)。这是球体上两个坐标之间的最短距离。两个坐标都必须有效。”