首页 > 解决方案 > 如何启用 MapKit 楼层?

问题描述

我正在尝试在我的苹果应用程序中显示楼层。我知道在苹果地图中有一些选定的地方,比如机场或购物中心,可以看到这个楼层。我需要做到这一点。只需要显示可用的楼层。如您在图片中看到的,在图像的右侧有5F,4F,3F,2F等。我已经在网上搜索过,但仍然没有任何线索。

在此处输入图像描述

标签: swiftmapkit

解决方案


您需要使用 MKOverlay。您可以将每个楼层作为叠加层添加到您的 MKMapView 中,并显示用户选择的任何楼层,隐藏其他楼层。

这是制作叠加层的示例:

import MapKit

class MapOverlay: NSObject, MKOverlay {
  var coordinate: CLLocationCoordinate2D
  var boundingMapRect: MKMapRect

  override init() {
    let location = CLLocationCoordinate2D(latitude: 75.3307, longitude: -152.1929) // change these for the position of your overlay
    let mapSize = MKMapSize(width: 240000000, height: 200000000) // change these numbers for the width and height of your image
    boundingMapRect = MKMapRect(origin: MKMapPoint(location), size: mapSize)
    coordinate = location
    super.init()
  }
}

class MapOverlayRenderer: MKOverlayRenderer {
  let overlayImage: UIImage
  init(overlay: MKOverlay, image: UIImage) {
    self.overlayImage = image
    super.init(overlay: overlay)
  }

  override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
    guard let imageReference = overlayImage.cgImage else { return }

    let rect = self.rect(for: overlay.boundingMapRect)
    context.scaleBy(x: 1.0, y: -1.0)
    context.translateBy(x: 0.0, y: -rect.size.height)
    context.draw(imageReference, in: rect)
  }
}

然后将其添加到您的地图中:

let mapOverlay = MapOverlay()
mapView.addOverlay(mapOverlay)

并且不要忘记代表:

mapView.delegate = self

extension ViewController: MKMapViewDelegate {
  func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    return MapOverlayRenderer(overlay: overlay, image: UIImage(named: "overlayImage")!)
  }
}

推荐阅读