MapKit框架详细解析(十八) —— 基于MapKit使用Indoor Maps来绘制建筑物内部的地图的简单示例(二)

版本记录

版本号 时间
V1.0 2020.10.12 星期一

前言

MapKit框架直接从您的应用界面显示地图或卫星图像,调出兴趣点,并确定地图坐标的地标信息。接下来几篇我们就一起看一下这个框架。感兴趣的看下面几篇文章。
1. MapKit框架详细解析(一) —— 基本概览(一)
2. MapKit框架详细解析(二) —— 基本使用简单示例(一)
3. MapKit框架详细解析(三) —— 基本使用简单示例(二)
4. MapKit框架详细解析(四) —— 一个叠加视图相关的简单示例(一)
5. MapKit框架详细解析(五) —— 一个叠加视图相关的简单示例(二)
6. MapKit框架详细解析(六) —— 添加自定义图块(一)
7. MapKit框架详细解析(七) —— 添加自定义图块(二)
8. MapKit框架详细解析(八) —— 添加自定义图块(三)
9. MapKit框架详细解析(九) —— 地图特定区域放大和创建自定义地图annotations(一)
10. MapKit框架详细解析(十) —— 地图特定区域放大和创建自定义地图annotations(二)
11. MapKit框架详细解析(十一) —— 自定义MapKit Tiles(一)
12. MapKit框架详细解析(十二) —— 自定义MapKit Tiles(二)
13. MapKit框架详细解析(十三) —— MapKit Overlay Views(一)
14. MapKit框架详细解析(十四) —— MapKit Overlay Views(二)
15. MapKit框架详细解析(十五) —— 基于MapKit和Core Location的Routing(一)
16. MapKit框架详细解析(十六) —— 基于MapKit和Core Location的Routing(二)
17. MapKit框架详细解析(十七) —— 基于MapKit使用Indoor Maps来绘制建筑物内部的地图的简单示例(一)

源码

1. Swift

首先看下工程组织结构

下面就是sb中的内容

接着就是源码了

1. LabelAnnotation.swift
import MapKit
import UIKit

class LabelAnnotation: MKAnnotationView {
  var label: UILabel
  var point: UIView

  override var annotation: MKAnnotation? {
    didSet {
      if let title = annotation?.title {
        label.text = title
      } else {
        label.text = nil
      }
    }
  }

  override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
    label = UILabel(frame: .zero)
    point = UIView(frame: .zero)
    super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

    label.font = UIFont.preferredFont(forTextStyle: .caption1)
    addSubview(label)

    label.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
      label.leadingAnchor.constraint(equalTo: leadingAnchor),
      label.trailingAnchor.constraint(equalTo: trailingAnchor),
      label.bottomAnchor.constraint(equalTo: bottomAnchor)
    ])

    let radius: CGFloat = 5.0
    point.layer.cornerRadius = radius
    point.layer.borderWidth = 1.0
    point.layer.borderColor = UIColor(named: "AnnotationBorder")?.cgColor
    addSubview(point)

    point.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
      point.widthAnchor.constraint(equalToConstant: radius * 2),
      point.heightAnchor.constraint(equalToConstant: radius * 2),
      point.topAnchor.constraint(equalTo: topAnchor),
      point.centerXAnchor.constraint(equalTo: label.centerXAnchor),
      point.bottomAnchor.constraint(equalTo: label.topAnchor)
    ])

    centerOffset = CGPoint(x: 0, y: label.font.lineHeight / 2 )
    calloutOffset = CGPoint(x: 0, y: -radius)
    canShowCallout = true
    translatesAutoresizingMaskIntoConstraints = false
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  override var backgroundColor: UIColor? {
    get {
      return point.backgroundColor
    }
    set {
      point.backgroundColor = newValue
    }
  }
}
2. PointAnnotation.swift
import Foundation
import MapKit

class PointAnnotation: MKAnnotationView {
  override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
    super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

    frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: 10, height: 10)
    layer.cornerRadius = 5
    layer.borderWidth = 1.0
    layer.borderColor = UIColor(named: "AnnotationBorder")?.cgColor
    canShowCallout = true
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}
3. IMDFError.swift
import Foundation

enum IMDFError: Error {
  case invalidType
  case invalidData
}
4. Archive.swift
import Foundation

struct Archive {
  let directory: URL

  init(directory: URL) {
    self.directory = directory
  }

  enum File {
    case address
    case amenity
    case anchor
    case building
    case detail
    case fixture
    case footprint
    case geofence
    case kiosk
    case level
    case manifest
    case occupant
    case opening
    case relationship
    case section
    case unit
    case venue

    var filename: String {
      return "\(self).geojson"
    }
  }

  func fileURL(for file: File) -> URL {
    return directory.appendingPathComponent(file.filename)
  }
}
5. IMDFDecoder.swift
import Foundation
import MapKit

class IMDFDecoder {
  private let geoJSONDecoder = MKGeoJSONDecoder()
  func decode(_ imdfDirectory: URL) throws -> Venue {
    let archive = Archive(directory: imdfDirectory)

    // Decode all the features that need to be rendered.
    let venues = try decodeFeatures(Venue.self, from: .venue, in: archive)
    let levels = try decodeFeatures(Level.self, from: .level, in: archive)
    let units = try decodeFeatures(Unit.self, from: .unit, in: archive)
    let openings = try decodeFeatures(Opening.self, from: .opening, in: archive)
    let amenities = try decodeFeatures(Amenity.self, from: .amenity, in: archive)

    // Associate levels to venues.
    if venues.isEmpty {
      throw IMDFError.invalidData
    }
    let venue = venues[0]
    venue.levelsByOrdinal = Dictionary(grouping: levels) { level in
      level.properties.ordinal
    }

    // Associate Units and Opening to levels.
    let unitsByLevel = Dictionary(grouping: units) { unit in
      unit.properties.levelId
    }

    let openingsByLevel = Dictionary(grouping: openings) { opening in
      opening.properties.levelId
    }

    // Associate each Level with its corresponding Units and Openings.
    for level in levels {
      if let unitsInLevel = unitsByLevel[level.id] {
        level.units = unitsInLevel
      }
      if let openingsInLevel = openingsByLevel[level.id] {
        level.openings = openingsInLevel
      }
    }

    // Associate Amenities to the Unit in which they reside.
    let unitsById = units.reduce(into: [UUID: Unit]()) {
      $0[$1.id] = $1
    }

    for amenity in amenities {
      guard let pointGeometry = amenity.geometry[0] as? MKPointAnnotation else {
        throw IMDFError.invalidData
      }

      if let name = amenity.properties.name?.bestLocalizedValue {
        amenity.title = name
        amenity.subtitle = amenity.properties.category.capitalized
      } else {
        amenity.title = amenity.properties.category.capitalized
      }

      for unitID in amenity.properties.unitIds {
        let unit = unitsById[unitID]
        unit?.amenities.append(amenity)
      }

      amenity.coordinate = pointGeometry.coordinate
    }

    // Occupants (and certain other IMDF features) do not directly contain geometry. Instead, they reference a separate `Anchor` which
    // contains geometry. Occupants should be associated with Units.
    try decodeOccupants(units: units, in: archive)

    return venue
  }

  private func decodeOccupants(units: [Unit], in archive: Archive) throws {
    let occupants = try decodeFeatures(Occupant.self, from: .occupant, in: archive)
    let anchors = try decodeFeatures(Anchor.self, from: .anchor, in: archive)
    let unitsById = units.reduce(into: [UUID: Unit]()) {
      $0[$1.id] = $1
    }
    let anchorsById = anchors.reduce(into: [UUID: Anchor]()) {
      $0[$1.id] = $1
    }

    // Resolve the occupants location based on the referenced Anchor, and associate them
    // with their corresponding Unit.
    for occupant in occupants {
      guard let anchor = anchorsById[occupant.properties.anchorId] else {
        throw IMDFError.invalidData
      }

      guard let pointGeometry = anchor.geometry[0] as? MKPointAnnotation else {
        throw IMDFError.invalidData
      }
      occupant.coordinate = pointGeometry.coordinate

      if let name = occupant.properties.name.bestLocalizedValue {
        occupant.title = name
        occupant.subtitle = occupant.properties.category.capitalized
      } else {
        occupant.title = occupant.properties.category.capitalized
      }

      guard let unit = unitsById[anchor.properties.unitId] else {
        continue
      }

      // Associate occupants to units.
      unit.occupants.append(occupant)
      occupant.unit = unit
    }
  }

  private func decodeFeatures<T: IMDFDecodableFeature>(_ type: T.Type, from file: Archive.File, in archive: Archive) throws -> [T] {
    let fileURL = archive.fileURL(for: file)
    let data = try Data(contentsOf: fileURL)
    let geoJSONFeatures = try geoJSONDecoder.decode(data)
    guard let features = geoJSONFeatures as? [MKGeoJSONFeature] else {
      throw IMDFError.invalidType
    }

    let imdfFeatures = try features.map { try type.init(feature: $0) }
    return imdfFeatures
  }
}
6. StylableFeatures.swift
import Foundation
import MapKit

protocol StylableFeature {
  var geometry: [MKShape & MKGeoJSONObject] { get }
  func configure(overlayRenderer: MKOverlayPathRenderer)
  func configure(annotationView: MKAnnotationView)
}

extension StylableFeature {
  func configure(overlayRenderer: MKOverlayPathRenderer) {}
  func configure(annotationView: MKAnnotationView) {}
}
7. MapViewController.swift
import UIKit
import MapKit

class MapViewController: UIViewController {
  @IBOutlet weak var mapView: MKMapView!

  let locationManager = CLLocationManager()
  let decoder = IMDFDecoder()
  var venue: Venue?

  private var levels: [Level] = []
  private var currentLevelFeatures: [StylableFeature] = []
  private var currentLevelOverlays: [MKOverlay] = []
  private var currentLevelAnnotations: [MKAnnotation] = []

  override func viewDidLoad() {
    super.viewDidLoad()
    setupMapView()
    loadRazeHQIndoorMapData()
    showDefaultMapRect()
    showFeatures(for: 1)
    startListeningForLocation()
  }

  func setupMapView() {
    mapView.delegate = self
    mapView.register(PointAnnotation.self, forAnnotationViewWithReuseIdentifier: "PointAnnotationView")
    mapView.register(LabelAnnotation.self, forAnnotationViewWithReuseIdentifier: "LabelAnnotationView")
    mapView.pointOfInterestFilter = .none
  }

  func loadRazeHQIndoorMapData() {
    guard let resourceURL = Bundle.main.resourceURL else { return }

    let imdfDirectory = resourceURL.appendingPathComponent("Data")
    do {
      venue = try decoder.decode(imdfDirectory)
    } catch let error {
      print(error)
    }
  }

  private func showFeatures(for ordinal: Int) {
    guard venue != nil else {
      return
    }

    // 1
    currentLevelFeatures.removeAll()
    mapView.removeOverlays(currentLevelOverlays)
    mapView.removeAnnotations(currentLevelAnnotations)
    currentLevelAnnotations.removeAll()
    currentLevelOverlays.removeAll()

    // 2
    if let levels = venue?.levelsByOrdinal[ordinal] {
      for level in levels {
        currentLevelFeatures.append(level)
        currentLevelFeatures += level.units
        currentLevelFeatures += level.openings

        let occupants = level.units.flatMap { unit in
          unit.occupants
        }

        let amenities = level.units.flatMap { unit in
          unit.amenities
        }

        currentLevelAnnotations += occupants
        currentLevelAnnotations += amenities
      }
    }

    // 3
    let currentLevelGeometry = currentLevelFeatures.flatMap { feature in
      feature.geometry
    }

    currentLevelOverlays = currentLevelGeometry.compactMap { mkOverlay in
      mkOverlay as? MKOverlay
    }

    mapView.addOverlays(currentLevelOverlays)
    mapView.addAnnotations(currentLevelAnnotations)
  }

  func showDefaultMapRect() {
    guard
      let venue = venue,
      let venueOverlay = venue.geometry[0] as? MKOverlay
      else { return }

    mapView.setVisibleMapRect(
      venueOverlay.boundingMapRect,
      edgePadding: UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20),
      animated: false)
  }

  func startListeningForLocation() {
    locationManager.requestWhenInUseAuthorization()
  }

  @IBAction func segmentedControlValueChanged(_ sender: UISegmentedControl) {
    showFeatures(for: sender.selectedSegmentIndex)
  }
}

// MARK: - MKMapViewDelegate

extension MapViewController: MKMapViewDelegate {
  func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    guard
      let shape = overlay as? (MKShape & MKGeoJSONObject),
      let feature = currentLevelFeatures.first( where: { $0.geometry.contains( where: { $0 == shape }) })
      else { return MKOverlayRenderer(overlay: overlay) }

    let renderer: MKOverlayPathRenderer
    switch overlay {
    case is MKMultiPolygon:
      renderer = MKMultiPolygonRenderer(overlay: overlay)
    case is MKPolygon:
      renderer = MKPolygonRenderer(overlay: overlay)
    case is MKMultiPolyline:
      renderer = MKMultiPolylineRenderer(overlay: overlay)
    case is MKPolyline:
      renderer = MKPolylineRenderer(overlay: overlay)
    default:
      return MKOverlayRenderer(overlay: overlay)
    }

    // Configure the overlay renderer's display properties in feature-specific ways.
    feature.configure(overlayRenderer: renderer)

    return renderer
  }

  func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if let stylableFeature = annotation as? StylableFeature {
      if stylableFeature is Occupant {
        let annotationView = mapView.dequeueReusableAnnotationView(
          withIdentifier: "LabelAnnotationView",
          for: annotation)
        stylableFeature.configure(annotationView: annotationView)
        return annotationView
      } else {
        let annotationView = mapView.dequeueReusableAnnotationView(
          withIdentifier: "PointAnnotationView",
          for: annotation)
        stylableFeature.configure(annotationView: annotationView)
        return annotationView
      }
    }

    return nil
  }

  func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
    guard
      let venue = venue,
      let location = userLocation.location
      else { return }

    // Display location only if the user is inside this venue.
    var isUserInsideVenue = false
    let userMapPoint = MKMapPoint(location.coordinate)
    for geometry in venue.geometry {
      guard let overlay = geometry as? MKOverlay else {
        continue
      }

      if overlay.boundingMapRect.contains(userMapPoint) {
        isUserInsideVenue = true
        break
      }
    }

    guard isUserInsideVenue else {
      return
    }

    // If the device knows which level the user is physically on, automatically switch to that level.
    if let ordinal = location.floor?.level {
      showFeatures(for: ordinal)
    }
  }
}

后记

本篇主要讲述了基于MapKit使用Indoor Maps来绘制建筑物内部的地图的简单示例,感兴趣的给个赞或者关注~~~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,013评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,205评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,370评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,168评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,153评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,954评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,271评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,916评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,382评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,877评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,989评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,624评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,209评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,199评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,418评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,401评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,700评论 2 345