MapKit框架詳細(xì)解析(十八) —— 基于MapKit使用Indoor Maps來繪制建筑物內(nèi)部的地圖的簡單示例(二)

版本記錄

版本號 時間
V1.0 2020.10.12 星期一

前言

MapKit框架直接從您的應(yīng)用界面顯示地圖或衛(wèi)星圖像,調(diào)出興趣點(diǎn),并確定地圖坐標(biāo)的地標(biāo)信息汽馋。接下來幾篇我們就一起看一下這個框架。感興趣的看下面幾篇文章。
1. MapKit框架詳細(xì)解析(一) —— 基本概覽(一)
2. MapKit框架詳細(xì)解析(二) —— 基本使用簡單示例(一)
3. MapKit框架詳細(xì)解析(三) —— 基本使用簡單示例(二)
4. MapKit框架詳細(xì)解析(四) —— 一個疊加視圖相關(guān)的簡單示例(一)
5. MapKit框架詳細(xì)解析(五) —— 一個疊加視圖相關(guān)的簡單示例(二)
6. MapKit框架詳細(xì)解析(六) —— 添加自定義圖塊(一)
7. MapKit框架詳細(xì)解析(七) —— 添加自定義圖塊(二)
8. MapKit框架詳細(xì)解析(八) —— 添加自定義圖塊(三)
9. MapKit框架詳細(xì)解析(九) —— 地圖特定區(qū)域放大和創(chuàng)建自定義地圖annotations(一)
10. MapKit框架詳細(xì)解析(十) —— 地圖特定區(qū)域放大和創(chuàng)建自定義地圖annotations(二)
11. MapKit框架詳細(xì)解析(十一) —— 自定義MapKit Tiles(一)
12. MapKit框架詳細(xì)解析(十二) —— 自定義MapKit Tiles(二)
13. MapKit框架詳細(xì)解析(十三) —— MapKit Overlay Views(一)
14. MapKit框架詳細(xì)解析(十四) —— MapKit Overlay Views(二)
15. MapKit框架詳細(xì)解析(十五) —— 基于MapKit和Core Location的Routing(一)
16. MapKit框架詳細(xì)解析(十六) —— 基于MapKit和Core Location的Routing(二)
17. MapKit框架詳細(xì)解析(十七) —— 基于MapKit使用Indoor Maps來繪制建筑物內(nèi)部的地圖的簡單示例(一)

源碼

1. Swift

首先看下工程組織結(jié)構(gòu)

下面就是sb中的內(nèi)容

接著就是源碼了

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來繪制建筑物內(nèi)部的地圖的簡單示例蕾总,感興趣的給個贊或者關(guān)注~~~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市琅捏,隨后出現(xiàn)的幾起案子生百,更是在濱河造成了極大的恐慌,老刑警劉巖柄延,帶你破解...
    沈念sama閱讀 211,561評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蚀浆,死亡現(xiàn)場離奇詭異,居然都是意外死亡搜吧,警方通過查閱死者的電腦和手機(jī)市俊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,218評論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來滤奈,“玉大人摆昧,你說我怎么就攤上這事⊙殉蹋” “怎么了绅你?”我有些...
    開封第一講書人閱讀 157,162評論 0 348
  • 文/不壞的土叔 我叫張陵伺帘,是天一觀的道長。 經(jīng)常有香客問我勇吊,道長曼追,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,470評論 1 283
  • 正文 為了忘掉前任汉规,我火速辦了婚禮礼殊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘针史。我一直安慰自己晶伦,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,550評論 6 385
  • 文/花漫 我一把揭開白布啄枕。 她就那樣靜靜地躺著婚陪,像睡著了一般。 火紅的嫁衣襯著肌膚如雪频祝。 梳的紋絲不亂的頭發(fā)上泌参,一...
    開封第一講書人閱讀 49,806評論 1 290
  • 那天,我揣著相機(jī)與錄音常空,去河邊找鬼沽一。 笑死,一個胖子當(dāng)著我的面吹牛漓糙,可吹牛的內(nèi)容都是我干的铣缠。 我是一名探鬼主播,決...
    沈念sama閱讀 38,951評論 3 407
  • 文/蒼蘭香墨 我猛地睜開眼昆禽,長吁一口氣:“原來是場噩夢啊……” “哼蝗蛙!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起醉鳖,我...
    開封第一講書人閱讀 37,712評論 0 266
  • 序言:老撾萬榮一對情侶失蹤捡硅,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后盗棵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體病曾,經(jīng)...
    沈念sama閱讀 44,166評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,510評論 2 327
  • 正文 我和宋清朗相戀三年漾根,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鲫竞。...
    茶點(diǎn)故事閱讀 38,643評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡辐怕,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出从绘,到底是詐尸還是另有隱情寄疏,我是刑警寧澤是牢,帶...
    沈念sama閱讀 34,306評論 4 330
  • 正文 年R本政府宣布,位于F島的核電站陕截,受9級特大地震影響驳棱,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜农曲,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,930評論 3 313
  • 文/蒙蒙 一社搅、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧乳规,春花似錦形葬、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,745評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至冻辩,卻和暖如春猖腕,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背恨闪。 一陣腳步聲響...
    開封第一講書人閱讀 31,983評論 1 266
  • 我被黑心中介騙來泰國打工倘感, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人凛剥。 一個月前我還...
    沈念sama閱讀 46,351評論 2 360
  • 正文 我出身青樓侠仇,卻偏偏與公主長得像,于是被迫代替她去往敵國和親犁珠。 傳聞我的和親對象是個殘疾皇子逻炊,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,509評論 2 348