【问题标题】:how to automatically zoom mapView to show overlay如何自动缩放mapView以显示覆盖
【发布时间】:2019-11-05 09:10:44
【问题描述】:

我可以在 mapView 上绘制多边形,但是我需要找到多边形并手动缩放它。有没有办法自动完成这个过程,比如调整中心的多边形?我浏览了互联网并阅读了一些相关文章,其中大部分是基于折线和点的。任何形式的帮助都将不胜感激,因为我正在寻找解决方案一段时间。提前致谢。

使用以下方法在 mapView 上绘制多边形:-

func drawFence(coordinates: UnsafePointer<CLLocationCoordinate2D>, count: Int) {
        let makePoly = MKPolygon(coordinates: coordinates, count: count)
        mapview.addOverlay(makePoly)
    }

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    guard let polyOverlay = overlay as? MKPolygon else { return MKOverlayRenderer() }
    let polyRender = MKPolygonRenderer(polygon: polyOverlay)
    polyRender.fillColor = #colorLiteral(red: 0.9764705882, green: 0.09803921569, blue: 0.2588235294, alpha: 0.6)
    polyRender.strokeColor = #colorLiteral(red: 0.9764705882, green: 0.09803921569, blue: 0.2588235294, alpha: 1)
    polyRender.lineWidth = 2
    return polyRender
}

【问题讨论】:

  • 试试这将缩放/平移以适应所有覆盖有一点缓冲区: if let first = mapView.overlays.first { let rect = mapView.overlays.reduce(first.boundingMapRect, combine: {MKMapRectUnion ($0, $1.boundingMapRect)}) mapView.setVisibleMapRect(rect, edgePadding: UIEdgeInsets(top: 50.0, left: 50.0, bottom: 50.0, right: 50.0), 动画: true) }
  • @DhavalRaval 我之前尝试过这段代码,并且没有名为“MKMapRectUnion”的属性
  • @Rob 谢谢,你建议的标题很有道理,我已经相应地更改了。

标签: ios swift mapkit core-location mkpolygon


【解决方案1】:

如果您想放大特定的叠加层,您可以:

let insets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)

func zoom(for overlay: MKOverlay) {
    mapView.setVisibleMapRect(overlay.boundingMapRect, edgePadding: insets, animated: true)
}


如果您想缩放地图以显示所有叠加层,您可以这样做:

func zoomForAllOverlays() {
    guard let initial = mapView.overlays.first?.boundingMapRect else { return }

    let mapRect = mapView.overlays
        .dropFirst()
        .reduce(initial) { $0.union($1.boundingMapRect) }

    mapView.setVisibleMapRect(mapRect, edgePadding: insets, animated: true)
}

例如,添加了两个叠加层(在 NYC 和 Stamford 上),我调用了该例程,结果是:


顺便说一句,我知道问题是关于 Polygon 覆盖,但无论覆盖类型如何,该技术都有效。为演示目的创建 Circle 叠加层更简单。

【讨论】:

  • 我已经如前所述进行了必要的代码更改,它对两个叠加层都起到了作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-06
相关资源
最近更新 更多