Skip to content

Instantly share code, notes, and snippets.

@sc0rch
Created September 30, 2016 14:28
Show Gist options
  • Save sc0rch/069b6f7f477c5a8474367666e2103e19 to your computer and use it in GitHub Desktop.
Save sc0rch/069b6f7f477c5a8474367666e2103e19 to your computer and use it in GitHub Desktop.
Swift 3. OSMTileLayer for Google Maps iOS SDK. With argument retina=true in constructor, tile layer automatically doubles the tiles resolution. It makes OSM tiles more readable on retina-devices.
import Foundation
import GoogleMaps
import UIImage_ResizeMagick
/**
Custom GMSTileLayer which allows us to double tile size for OSM.
Available size of OSM tiles is 256, but for retina devices we need 512x512.
*/
class OSMTileOverlay: GMSTileLayer {
var retina: Bool = false
var retinaTileSize: Int = 512
init(retina: Bool, retinaTileSize: Int = 512) {
super.init()
self.retina = retina
self.retinaTileSize = retinaTileSize
if self.retina {
self.tileSize = self.retinaTileSize
}
}
override func requestTileFor(x: UInt, y: UInt, zoom: UInt, receiver: (GMSTileReceiver!)) {
let urlStr = "http://irs.gis-lab.info/?layers=osm&request=GetTile&z=\(zoom)&x=\(x)&y=\(y)"
var request = URLRequest(url: URL(string: urlStr)!)
request.httpMethod = "GET"
let session = URLSession.shared
session.dataTask(with: request, completionHandler: {(data, response, error) in
DispatchQueue.main.async(execute: {
if error != nil {
print("Error downloading tile")
receiver.receiveTileWith(x: x, y: y, zoom: zoom, image: kGMSTileLayerNoTile)
}
else {
if let image = UIImage(data: data!) {
if self.retina {
let doubledImage = image.resizedImage(byMagick: "\(self.retinaTileSize)x\(self.retinaTileSize)!")
receiver.receiveTileWith(x: x, y: y, zoom: zoom, image: doubledImage)
} else {
receiver.receiveTileWith(x: x, y: y, zoom: zoom, image: image)
}
} else {
receiver.receiveTileWith(x: x, y: y, zoom: zoom, image: kGMSTileLayerNoTile)
}
}
})
}).resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment