Ivan Le Hjelmeland
Ivan Le Hjelmeland

Reputation: 1065

Load all tiles for area in mapView

I have found a way to cache tiles with MapKit, but I haven't found any solution for loading all tiles inside an area to from the top level tiles to the bottom level tiles.

I want to cache all tiles for a rectangle area in my mapview. Is there any way to do this in Mapkit?

Upvotes: 3

Views: 1082

Answers (1)

Denis Litvin
Denis Litvin

Reputation: 355

In order to load custom tiles in MKMapView you need to subclass MKTileOverlay and override method url(forTilePath path: MKTileOverlayPath) -> URL

MKTitleOverlay contains x, y and z properties for the tile. So the implementation may look like this:

override func url(forTilePath path: MKTileOverlayPath) -> URL {
  let tilePath = Bundle.main.url(
  forResource: "\(path.y)",
  withExtension: "png",
  subdirectory: "tiles/\(path.z)/\(path.x)",
  localization: nil)!
  return tile
}

In your mapView setting function add the following:

let overlay = CustomTileOverlay()
overlay.canReplaceMapContent = true
mapView.add(overlay, level: .aboveLabels)

Also don't forget to return renderer in

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
  return MKTileOverlayRenderer(tileOverlay: overlay)
}

P.S. There is a great tutorial on raywenderlich.com on that subject:

Upvotes: 1

Related Questions