iosmktileoverlay

Difficulty In Subclassing MKTileOverlay


I am trying to subclass MKTileOverlay, but am having issues with it not finding property canReplaceMap on object. What am I doing wrong? I go to New, create new class, Subclass of MKTileOverlay and add in the methods the tutorials all say to add, but these simple properties aren't getting found!


Solution

  • Here is the custom class extension for MKTileOverlay that I've been using to overlay the map in MapKit:

    class CustomTileOverlay : MKTileOverlay
    {
        var mapLocation: MKMapPoint
        var mapSize: MKMapSize
    
        init(urlTemplate: String, location: MKMapPoint, size: MKMapSize)
        {
            mapLocation = location
            mapSize = size
    
            super.init(urlTemplate: urlTemplate)
        }
    
        override var boundingMapRect: MKMapRect {
            get {
                return MKMapRect(origin: mapLocation, size: mapSize)
            }
        }
    }
    

    The reason for doing an extension is to be able to adjust the boundingMapRect since that's read only in the base class (so if you don't need to adjust it, don't sub-class MKTileOverlay).

    Here's the setup for using the Custom Class. I'm pulling the values from a CoreData record I set up for the tile set, but you could hardwire those or get them from wherever fits your app. Since I have polylines overlaying the tiles, I need the last line to be sure the tiles are under the lines, so if you don't have both you won't need that line.

        [Declaration...]
    
        private var tileLayer: CustomTileOverlay?
    
        [Later in the code...]
    
        let rectangle = overlayMap.getMapRectangle()  // Why I need to sub-class
        let mapURL = "file://" + overlayMap.getMapPath() + "/{z}/{x}/{y}.png"
        tileLayer = CustomTileOverlay(urlTemplate: mapURL, location: rectangle.origin, size: rectangle.size)
        tileLayer?.minimumZ = overlayMap.getMinimumZoom()
        tileLayer?.maximumZ = overlayMap.getMaximumZoom()
        tileLayer?.canReplaceMapContent = true
        tileLayer?.tileSize = overlayMap.getTileSize()
        self.mapView.add(tileLayer!)
        self.mapView.insert(tileLayer!, at: 0)  // Set to lowest z-level to ensure polylines are above map tiles