{"id":19264914,"url":"https://github.com/merlos/mapcache","last_synced_at":"2025-04-03T03:11:32.014Z","repository":{"id":34922461,"uuid":"190116054","full_name":"merlos/MapCache","owner":"merlos","description":"Map Cache for iOS. Pod to support offline maps written in Swift","archived":false,"fork":false,"pushed_at":"2024-06-24T01:24:13.000Z","size":1941,"stargazers_count":127,"open_issues_count":20,"forks_count":31,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-03-24T06:52:09.344Z","etag":null,"topics":["cache","cocoapods","ios","ipad","iphone","map","mapcache","mapkit","mkmapview","offline","offline-maps","open-street-map","osm","osm-ios","pod","podfile","swift","swift-library","tiles"],"latest_commit_sha":null,"homepage":"http://merlos.org/MapCache","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/merlos.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-06-04T02:37:30.000Z","updated_at":"2025-01-21T19:22:04.000Z","dependencies_parsed_at":"2024-06-20T00:10:09.133Z","dependency_job_id":"96c42a49-d1f7-4969-8769-01ea8d6a8977","html_url":"https://github.com/merlos/MapCache","commit_stats":{"total_commits":194,"total_committers":10,"mean_commits":19.4,"dds":"0.17525773195876293","last_synced_commit":"592813d1759929db5a6710916b2495335546bc12"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/merlos%2FMapCache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/merlos%2FMapCache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/merlos%2FMapCache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/merlos%2FMapCache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/merlos","download_url":"https://codeload.github.com/merlos/MapCache/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246927839,"owners_count":20856198,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cache","cocoapods","ios","ipad","iphone","map","mapcache","mapkit","mkmapview","offline","offline-maps","open-street-map","osm","osm-ios","pod","podfile","swift","swift-library","tiles"],"created_at":"2024-11-09T19:42:48.489Z","updated_at":"2025-04-03T03:11:31.988Z","avatar_url":"https://github.com/merlos.png","language":"Swift","readme":"# MapCache Swift\n\n\u003cp\u003e\u003cdiv style=\"text-align:center\"\u003e\u003cimg src=\"https://github.com/merlos/MapCache/raw/master/images/MapCache.png\"\u003e\u003c/div\u003e\n\u003c/p\u003e\n\n[![CI Status](https://travis-ci.com/merlos/MapCache.svg?branch=master)](https://travis-ci.org/github/merlos/MapCache)\n[![Version](https://img.shields.io/cocoapods/v/MapCache.svg?style=flat)](https://cocoapods.org/pods/MapCache)\n[![License](https://img.shields.io/cocoapods/l/MapCache.svg?style=flat)](https://cocoapods.org/pods/MapCache)\n[![Platform](https://img.shields.io/cocoapods/p/MapCache.svg?style=flat)](https://cocoapods.org/pods/MapCache)\n[![Documentation](https://www.merlos.org/MapCache/badge.svg)](http://merlos.org/MapCache)\n![Swift](https://github.com/merlos/MapCache/workflows/Swift/badge.svg)\n\nThe missing part of [MapKit](https://developer.apple.com/documentation/mapkit): A simple way to cache [map tiles](https://en.wikipedia.org/wiki/Tiled_web_map) and support offline browsing of maps.\n\nCurrent features:\n* Automatically save tiles in a disk cache as user browses the map.\n* Generation of interpolated tiles beyond maximum server zoom level (`{z}`) \n* Cache capacity. Once the cache is full it will use a LRU (Least Recently Used) algorithm.\n* Get Current cache size\n* Clear existing cache\n* Download a full region of the map (experimental)\n* Available [reference documentation](http://www.merlos.org/MapCache)\n\n\n## Installation\nMapCache is available through [CocoaPods](https://cocoapods.org). To install it, simply add the following line to your `Podfile`:\n\n```ruby\n#Podfile\npod 'MapCache'\n```\n\nThen in the folder where you have the `Podfile` run the command \n```shell\npod install\n```\n\n\n## How to use MapCache?\nIn the view controller where you have a `MKMapView`, import `MapCache`:\n\n```swift\nimport MapCache\n```\n\nThen, within the ViewController add:\n\n```swift\n// ViewController.swift\nclass ViewController: UIViewController {\n  @IBOutlet weak var map: MKMapView!\n\n  override func viewDidLoad() {\n    super.viewDidLoad()\n\n    //...\n\n    map.delegate = self\n\n    //...\n\n    // First setup the config of our cache. \n    // The only thing we must provide is the url template of the tile server.\n    // (All other config options are explained below in the section MapCache Configuration)\n    let config = MapCacheConfig(withUrlTemplate: \"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png\")\n\n    // initialize the cache with our config\n    let mapCache = MapCache(withConfig: config)\n\n    // We tell the MKMapView to use the cache\n    // So whenever it requires a tile, it will be requested to the \n    // cache \n    map.useCache(mapCache)\n\n    //...\n}\n```\n\nFinally, tell the map delegate to use `mapCacheRenderer`:\n\n```swift\n//ViewController.swift\n\n// Assuming that ViewController is the delegate of the map\n// add this extension:\nextension ViewController : MKMapViewDelegate {\n    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -\u003e MKOverlayRenderer {\n        return mapView.mapCacheRenderer(forOverlay: overlay)\n    }\n}\n\n```\nAfter setting up the map cache, browsed areas of the map will be kept on disk. If the user browses again, that area it will use the local version.\n\nNote that in the current version, the cache does not support expiration dates, so if you need to get an updated version of the tiles you must call `clear()` which will wipe out the whole cache.\n\n```swift\nmapCache.clear() {\n    // do something after clear\n    print(\"cache cleared!\")\n}\n```\n\nTo get current cache size:\n\n```swift\nmapCache.calculateDiskSize()\n```\n\nYou can take a look at the [**Example/ folder**](https://github.com/merlos/MapCache/tree/master/Example/MapCache) to see a complete implementation.\n\n[Reference documentation](http://www.merlos.org/MapCache) is also available.\n\n## MapCache configuration\nConfigurating the map cache is pretty straight forward. Typically, you will only need to set `urlTemplate` and, optionally, the `subdomains`.\n\nThese are the options:\n\n```swift\nvar config = MapCacheConfig()\n\n// Set the URL template.\n// For Open Street Maps you can chose: https://wiki.openstreetmap.org/wiki/Tile_servers\n// It defaults to OpenStreetMaps servers\n//\n// Below we set cartoDB Base map server (https://github.com/CartoDB/cartodb/wiki/BaseMaps-available)\nconfig.urlTemplate: \"https://${s}.basemaps.cartocdn.com/base-light/${z}/${x}/${y}.png\"\n\n\n// In the urlTemplate ${s} stands for subdomains, which allows you to balance\n// the load among the\n// different tile servers.\n// Default value is [\"a\",\"b\",\"c\"].\nconfig.subdomains = [\"a\", \"b\"]\n\n\n// Cache Name is basically is the subfolder name in which the tiles are store.\n// Default value is \"MapCache\"\nconfig.cacheName = \"Carto\"\n\n\n// Max zoom supported by the tile server\n// Default value is 19\nconfig.maximumZ = 21\n\n// Minimum zoom can also be set.\n// config.minimumZ = 0\n\n// Continues to show map tiles even beyond maximumZ\n// config.overZoomMaximumZ = true\n\n\n// Capacity of the cache in bytes. Once the cache is full it uses a LRU algorithm\n// (Least Recently Used), that is, it removes the tiles last used a lot of time ago.\n// Each time a tile is retrieved from the cache it is updated the value of last time used.\n// Default value of the capacity is unlimited.\nconfig.capacity = 200 * 1024 * 1024 // 200 Megabytes\n\n\n```\n\nIf you need to use MapCache in different controllers, be sure to use the same values in the config to avoid issues.\n\n## How does `MapCache` work behind the scenes\n\nIf you need to build something on top of MapCache, read the following.\n\nMapCache is a hack of [MapKit](https://developer.apple.com/documentation/mapkit), the map framework from Apple, used on their iOS, macOS, tvOS, and watchOS platforms.\n\n### Understanding MapCache bootstrap\n\nAs explained in _How to use MapCache?_ section, in order to bootstrap MapCache, we have to call this method:\n\n```swift\nmap.useCache(mapCache)\n```\n\nWhere map is an instance of `MKMapView`, the main class used to display a map with MapKit. What MapCache does through the `MKMapView+MapCache` extension is to add a new method `useCache` that tells `MKMapView` to display a new tile layer on top of the default layers. Because of this, while the tiles are loaded you may see  the tiles of the default Apple Maps.\n\nThis extension also adds a variable in the `MKMapView` to keep the cache config.\n\nA layer in the map is called _overlay_ in MapKit terminology. MapCache uses [tile based overlay](https://en.wikipedia.org/wiki/Tiled_web_map) implemented in the class `CachedTileOverlay`, which is a subclass of [MKTileOverlay](https://developer.apple.com/documentation/mapkit/mktileoverlay). \n\nOverlays have associated _renderers_ that are the actual classes that draw the content of an overlay on the screen. For example, there are rendererers for points, lines, polygons, and tiles. When `MapView` needs to display an overlay, it calls the delegate with the overlay it is going to render and you need to provide the renderer to use. In order to do that, We added a `mapCacheRenderer` method that returns the default [MKTileOverlayRenderer](https://developer.apple.com/documentation/mapkit/mktileoverlay) when the class of the overlay passed as the argument is of the type `CachedTileOverlay`. That is why we need to add this code on the application in the delegate of the map view (`MKMapViewDelegate`) :\n\n```swift\nextension ViewController : MKMapViewDelegate {\n    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -\u003e MKOverlayRenderer {\n        return mapView.mapCacheRenderer(forOverlay: overlay)\n    }\n}\n```\n\n### `CachedTileOverlay` and `MapCacheProtocol`\n\nAs mentioned earlier, `CachedTileOverlay` is a tile based layer that is implemented as a subclass of [MKTileOverlay](https://developer.apple.com/documentation/mapkit/mktileoverlay). Basically, the only thing that it does is to override two methods of the parent class:\n\n1.  `func url(forTilePath path: MKTileOverlayPath) -\u003e URL`. The goal of this method is to return the URL of the tile. We need to overwrite it to be able to use the tile server of our preference.    \n\n2. `func loadTile(at path: MKTileOverlayPath, result: @escaping (Data?, Error?) -\u003e Void)`. This method is the one that returns the actual Tile.\n\nIf you take a look at the [implementation of `CachedTileOverlay`](https://github.com/merlos/MapCache/blob/master/MapCache/Classes/CachedTileOverlay.swift), you will notice that it only forwards the request to the method with the same signature of a variable called `mapCache` which is an instance of a class that implements  `MapCacheProtocol` \n\n```swift\noverride public func url(forTilePath path: MKTileOverlayPath) -\u003e URL {\n    return mapCache.url(forTilePath: path)\n}\n```\n\nThe [`MapCacheProtocol definition`](https://github.com/merlos/MapCache/blob/master/MapCache/Classes/MapCacheProtocol.swift) is pretty simple, as it just requires to have a config variable instance of a `MapCacheConfig` and an implementation of the two methods that are called from `CachedTileOverlay`:\n\n```swift\npublic protocol MapCacheProtocol {\n\n    var config: MapCacheConfig { get set }\n\n    func url(forTilePath path: MKTileOverlayPath) -\u003e URL\n\n    func loadTile(at path: MKTileOverlayPath, result: @escaping (Data?, Error?) -\u003e Void)\n    \n}\n```\n\nIf you need to create a custom implementation of the cache, you need to create a class that implements this protocol and initialize the cache using  `map.useCache(myCustomCacheImplementationInstance)`. The implementation provided by the library is on the `MapCache` class.\n\nSomething that may also be useful is the `DiskCache` class.\n\nIf you need further information you can take a look at \n\n### [Reference documentation of MapCache](http://www.merlos.org/MapCache/).\n\n\n## Development\n\nClone the repo\n\n```shell\ngit clone https://github.com/merlos/MapCache\n```\n\nWith Xcode Open the file `Example/MapCache.xcworkspace`\n\nTo check if the pod is ready to be released run the command in the root folder folder \n\n```shell\npod lib lint MapCache.podspec\n```\n\n### Generate the documentation\n\nThis project uses [jazzy](https://github.com/realm/jazzy) for generating the [reference documentation](http://www.merlos.org/MapCache/))\n\nTo install jazzy\n```\ngem install jazzy --verbose\n```\n\nIn the root folder of the project run\n\n```shell\njazzy\n```\n\nIt will generate the html in `docs/`\n\n## You may also like\n\n* **[Open GPX Tracker](https://github.com/merlos/iOS-Open-GPX-Tracker)**. A free source iOS App to create [GPX](https://en.wikipedia.org/wiki/GPS_Exchange_Format) tracks\n* **[Core GPX](https://github.com/vincentneo/CoreGPX)** A swift library for managing GPX files by [Vincent Neo](https://github.com/vincentneo)\n\n## License - MIT\n\nCopyright (c) 2019-2020 Juan M. Merlos [@merlos](http://twitter.com/merlos) and contributors.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmerlos%2Fmapcache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmerlos%2Fmapcache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmerlos%2Fmapcache/lists"}