【问题标题】:how to make mapview zoom to 5 mile radius of current location如何使地图视图缩放到当前位置半径 5 英里
【发布时间】:2011-06-28 20:40:37
【问题描述】:

我知道这是一个非常普遍的问题,但我没有得到这件事的确切答案。

如何使 MKMapView 默认缩放当前位置半径 5 英里。

提前致谢。

【问题讨论】:

    标签: iphone objective-c mkmapview zooming


    【解决方案1】:

    当您想放大到 5 英里半径时,请使用以下代码:

    double miles = 5.0;
    double scalingFactor = ABS( (cos(2 * M_PI * newLocation.coordinate.latitude / 360.0) ));
    
    MKCoordinateSpan span; 
    
    span.latitudeDelta = miles/69.0;
    span.longitudeDelta = miles/(scalingFactor * 69.0); 
    
    MKCoordinateRegion region;
    region.span = span;
    region.center = newLocation.coordinate;
    
    [mapView setRegion:region animated:YES];
    

    【讨论】:

    • 在我的代码中,用用户的当前位置填充“newLocation”变量,它将从当前位置放大到 5 英里半径。
    • 对于任何想知道的人来说,神奇的数字 69 是每 60 海里的英里数。一个纬度有60海里。
    • @StephenBurns 这取决于 MKMapView 的框架?
    • 这个答案确实有效,但它给出了错误的距离。正确的方法是使用下面的 Anurag 的答案。我赞成这个答案,然后开始比较我的 mapView 上的两个距离,这个是不正确的。不要使用此答案,请使用以下答案。
    【解决方案2】:
    [self.theMapView setRegion:MKCoordinateRegionMake(
                        [theConsumer.latLong.clLocation coordinate], 
                        MKCoordinateSpanMake( MAP_SPAN, MAP_SPAN ))
                     animated:YES];
    

    MKCoordinateSpanMake 的参数以度为单位,1 度在赤道处大约是 69 英里。因此 MAP_SPAN 将是 5.0/69.0

    【讨论】:

      【解决方案3】:

      使用 MapKit 中的 MKCoordinateRegionMakeWithDistance 函数。

      由于 MapKit 使用米,因此使用转换函数将英里转换为米。

      float MilesToMeters(float miles) {
          // 1 mile is 1609.344 meters
          // source: http://www.google.com/search?q=1+mile+in+meters
          return 1609.344f * miles;
      }
      

      然后在您的代码中将地图区域设置为(感谢@DylanBettermann 指出要获得 5 英里的半径,距离需要加倍)

      mapView.region = MKCoordinateRegionMakeWithDistance(
          centerCoordinate, 
          MilesToMeters(10.0f),
          MilesToMeters(10.0f)
      );
      

      swift 4 版本:

      mapView.region = MKCoordinateRegion(
                  center: centerCoordinate,
                  latitudinalMeters: MilesToMeters(10.0f),
                  longitudinalMeters: MilesToMeters(10.0f)
      )
      

      【讨论】:

      • 我不确定MKCoordinateRegionMakeWithDistance 自发布后是否发生了变化,但在 iOS 9 中,这只会为您提供 2.5 英里的半径。将直径传递给 MKCooridinateRegionMakeWithDistance 而不是半径。 (例如,MilesToMeters(10.0f) 半径为 5 英里)
      • @DylanBettermann - 感谢您指出这一点。据我所知,我认为 API 没有改变。它一直是南北或东西距离。更新了示例代码。
      猜你喜欢
      • 2011-08-25
      • 1970-01-01
      • 2017-01-16
      • 2020-12-06
      • 2016-01-06
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 2011-08-01
      相关资源
      最近更新 更多