Skip to content
This repository was archived by the owner on Aug 25, 2023. It is now read-only.
This repository was archived by the owner on Aug 25, 2023. It is now read-only.

add MBTiles support #3

Closed
Closed

Description

@incanus

This should be straightforward based on RMMBTilesSource. However, linking to SQLite is a problem if we want to keep things simple for installation. Two thoughts right now:

  1. For CocoaPods, make MBTiles suppert a subspec. Linking isn't much of a big deal here anyway since it's managed.
  2. For manual install, just make a macro at the top of the file to #ifdef out the SQLite code by default. Then, if the dev wants, they can flip the macro bit and link it themselves. This gets around people having to link before use.

Activity

  1. radven commented on Oct 4, 2013

    @radven

    Being able to have offline overlays that come built into an app is essential to some of the apps we are working on. I was hoping to use MBTiles for this, and this seems like a great feature to integrate in.

  2. kontextbewusst commented on Oct 14, 2013

    @kontextbewusst

    This would indeed be a major breakthrough... having the comfort and slickness of MapKit, combined with the flexibility of offline mbtiles sources. Great!

  3. thdlx commented on Nov 8, 2013

    @thdlx

    MBTiles support would be great for my project !
    MBXMapKit is a nice approach combining the SDK map kit and Mapbox.
    Good job team !

  4. incanus commented on Nov 19, 2013

    @incanus
    ContributorAuthor

    Still not able to get to this in the near term. But to lay out the strategy I was planning:

    • Have a look inside MBXMapKit.m at

      mbxmapkit/MBXMapKit.m

      Lines 83 to 103 in a9bc909

      self.minimumZ = [_tileJSONDictionary[@"minzoom"] integerValue];
      self.maximumZ = [_tileJSONDictionary[@"maxzoom"] integerValue];
      if (_mapView.showDefaultBaseLayerMode == MBXMapViewShowDefaultBaseLayerIfPartial)
      {
      // Show default tiles only if a partial overlay.
      //
      self.canReplaceMapContent = (self.region.span.latitudeDelta >= 170 && self.region.span.longitudeDelta == 360);
      }
      else if (_mapView.showDefaultBaseLayerMode == MBXMapViewShowDefaultBaseLayerNever)
      {
      // Don't show default tiles when told not to.
      //
      self.canReplaceMapContent = YES;
      }
      else
      {
      // Show default tiles per user request.
      //
      self.canReplaceMapContent = NO;
      }
      for where the layer's min/max zooms and bounds are defined. This also relies on the region that is set in

      mbxmapkit/MBXMapKit.m

      Lines 115 to 130 in a9bc909

      - (MKCoordinateRegion)region
      {
      if ( ! _region.span.latitudeDelta || ! _region.span.longitudeDelta)
      {
      CLLocationCoordinate2D center = CLLocationCoordinate2DMake([self.tileJSONDictionary[@"center"][1] doubleValue], [self.tileJSONDictionary[@"center"][0] doubleValue]);
      CLLocationCoordinate2D nw = CLLocationCoordinate2DMake([self.tileJSONDictionary[@"bounds"][3] doubleValue], [self.tileJSONDictionary[@"bounds"][0] doubleValue]);
      CLLocationCoordinate2D se = CLLocationCoordinate2DMake([self.tileJSONDictionary[@"bounds"][1] doubleValue], [self.tileJSONDictionary[@"bounds"][2] doubleValue]);
      MKCoordinateSpan span = MKCoordinateSpanMake((nw.latitude - se.latitude), (se.longitude - nw.longitude));
      _region = MKCoordinateRegionMake(center, span);
      }
      return _region;
      }
    • The actual tile URL formulation and fetching is done in

      mbxmapkit/MBXMapKit.m

      Lines 155 to 240 in a9bc909

      - (NSURL *)URLForTilePath:(MKTileOverlayPath)path
      {
      return [NSURL URLWithString:[NSString stringWithFormat:@"https://%@.tiles.mapbox.com/v3/%@/%ld/%ld/%ld%@.png",
      [@[ @"a", @"b", @"c", @"d" ] objectAtIndex:(rand() % 4)],
      self.mapView.mapID,
      (long)path.z,
      (long)path.x,
      (long)path.y,
      (path.contentScaleFactor > 1.0 ? @"@2x" : @"")]];
      }
      - (void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData *tileData, NSError *error))result
      {
      if ( ! self.mapView)
      {
      // Don't load any tiles if we are a dummy layer.
      //
      result(nil, nil);
      }
      else
      {
      NSData *cachedData;
      // Try the caching delegate first.
      //
      if ([self.mapView.cachingDelegate respondsToSelector:@selector(mapView:loadCacheDataForMapID:tilePath:)])
      cachedData = [self.mapView.cachingDelegate mapView:self.mapView loadCacheDataForMapID:self.mapView.mapID tilePath:path];
      // Then, check our own disk cache.
      //
      if ( ! cachedData)
      cachedData = [NSData dataWithContentsOfFile:[self cachePathForTilePath:path]];
      if (cachedData)
      {
      result(cachedData, nil);
      }
      else
      {
      // Otherwise, fetch & cache for next time.
      //
      [[self.mapView.dataSession dataTaskWithURL:[self URLForTilePath:path] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
      {
      if (data)
      {
      // TODO: Possibly pay attention to HTTP response headers. Generally,
      // though, we're going to assume that the dev knows what they want
      // here given the possibility of no network access.
      if ([self.mapView.cachingDelegate respondsToSelector:@selector(mapView:saveCacheData:forMapID:tilePath:)])
      {
      // Offer to the caching delegate first.
      //
      [self.mapView.cachingDelegate mapView:self.mapView saveCacheData:data forMapID:self.mapView.mapID tilePath:path];
      }
      else
      {
      // Cache to disk in folders sorted by mapID.
      //
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void)
      {
      [data writeToFile:[self cachePathForTilePath:path] atomically:YES];
      });
      }
      // Return the new tile data.
      //
      result(data, nil);
      }
      else
      {
      // Return the fetch error directly.
      //
      result(nil, error);
      }
      }] resume];
      }
      // sweep cache periodically
      //
      if (rand() % 1000 == 0)
      {
      [self sweepCache];
      }
      }
      }
      per the new MapKit API. For MBTiles, URLForTilePath: would not be used and instead loadTileAtPath:result: would just hit the SQLite directly for the tile defined by path (i.e. the tile z/x/y).
    • Over in the SDK, you can see in https://github.com/mapbox/mapbox-ios-sdk/blob/1517baf35c30c2a64252a834e662d00e5e7158f9/MapView/Map/RMMBTilesSource.m all of the SQLite code (called via FMDB) that is used to open the MBTiles, get the min/max zoom and bounds, and pull out tile data. In this case, the class forms whole UIImage objects from it, whereas loadTileAtPath:result: in MapKit would just act on the NSData directly.
    • There is probably some work to be done around the threading model based on how MapKit works vs. how the iOS SDK (via CATiledLayer) does, but since the existing SQLite code uses the FMDatabaseQueue serial queue API for thread safety, a first cut should work pretty well.
  5. willsnookrz commented on Nov 22, 2013

    @willsnookrz

    I've had some success playing with offline tiles on the MapKit side (i.e. not involving MBXMapKit) by subclassing MKTileOverlay. Here are the main things you'll need to do to make the API work:

    Get an MKMapView set up in a view controller that implements MKMapViewDelegate protocol. The view controller should be set as the MKMapView's delegate.

    In the view controller, implement - (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay so that it will return a [[MKTileOverlayRenderer alloc] initWithTileOverlay:overlay] when it gets called with your subclassed MKTileOverlay as the overlay.

    Subclass MKTileOverlay with the following important bits:

    - (MKMapRect)boundingMapRect
    {
        // This works to test with, but you should figure out the actual bounding box
        return MKMapRectWorld;
    }
    
    - (BOOL)isGeometryFlipped
    {
        // Default coordinate system is upside down relative to an MBTiles from TileMill, so flip it
        return YES;
    }
    
    - (void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData *tileData, NSError *error))result
    {
        // Find your MBTiles file and open it with sqlite, FMDB, or whatever
        // Figure out if path represents a valid tile in your MBTiles file
        // Assuming it does, make this query to get the tile...
        NSString *query = [NSString stringWithFormat:@"select tile_data from tiles where zoom_level = %ld and tile_column = %ld and tile_row = %ld",(long)path.z,(long)path.x,(long)path.y];
        // Based on what comes back from your query, initialize these objects appropriately...
        NSData *myTileData;
        NSError *myErrorStatus;
        // Invoke the argument block to complete the asynchronous load...
        result(myTileData, myErrorStatus);
    }
    

    Back in your view controller, in viewDidLoad or someplace, do something kinda like this to add your overlay to the MKMapView:

    _tileOverlay = [[MBTilesOverlay alloc] initWithURLTemplate:nil];
    //_tileOverlay.canReplaceMapContent = YES;
    [_mapView addOverlay:_tileOverlay];
    
  6. incanus commented on Feb 18, 2014

    @incanus
    ContributorAuthor

    I like the approach over in #20 of doing this with defines for the folks that really need it. Leaving this open until this is addressed and integrated either in #20 directly or the aggregate #38 pull.

  7. added this to the 0.2.0 milestone on Feb 18, 2014
  8. modified the milestones: 0.3.0, 0.2.0 on Feb 26, 2014
  9. tkrajacic commented on Apr 14, 2014

    @tkrajacic
    Contributor

    The ability to use vector-mbtiles would be awesome, though I am not sure how easy this would be to implement within this confined project. As far as I understand, there would have to be some mechanism to render those on-the-fly then. Would something like this be feasible?

  10. incanus commented on Apr 21, 2014

    @incanus
    ContributorAuthor

    Would something like this be feasible?

    Yes, but this is a separate from MBTiles proper -- MBTiles is more the transport medium than the rendering. We're looking into vector rendering now.

  11. radven commented on May 1, 2014

    @radven

    Is "this can wait" referring to vector rendering, or MBTiles overall?

    The ability to have offline maps bundled with an app seems to be a pretty central feature to MBXMapKit, at least how I envision using it.

    Thoughts? Is there another more preferred way than MBTiles suggested?

  12. 21 remaining items

  13. tkrajacic commented on Jun 28, 2014

    @tkrajacic
    Contributor

    @wsnook My changes are on my fork ready for inspection. (issue3-mbtiles branch)
    Give it a spin and tell me if you would prefer a different approach.

    The ideas behind my changes were:

    • Reduce number of calls to sqlite API by using the same connection to the same mbtiles file.
    • Use a serial dispatch queue to access an mbtiles databse in a background thread without needing locks.
    • Use the same method structure to retrieve data from the database as is used for the offline cache variant. I had the idea that the worker-block could be used if the data needs preprocessing in the future like an image filter or (and there my imagination went probably a bit too wild) if the tiles might not contain image data but ::drumrolling:: vector data that needs to be rendered into images first.
  14. incanus commented on Jun 30, 2014

    @incanus
    ContributorAuthor
    • Reduce number of calls to sqlite API by using the same connection to the same mbtiles file.
    • Use a serial dispatch queue to access an mbtiles databse in a background thread without needing locks.

    This is starting to sound like FMDB reinvention territory. This is the library we use over the SDK for serial queued SQLite calls to great effect. If we are going to go this route, I think we should look into using that well-tested library than continuing to build up custom SQLite handling.

  15. tkrajacic commented on Jun 30, 2014

    @tkrajacic
    Contributor

    @incanus I would agree if I would actually have done it in such an abstract way, but I think my implementation is far simpler and less abstract than FMDB.

  16. incanus commented on Jun 30, 2014

    @incanus
    ContributorAuthor

    Ok, fair enough. Just wanted to put it on the radar. I haven't looked at @tkrajacic's code in depth yet.

  17. tkrajacic commented on Jun 30, 2014

    @tkrajacic
    Contributor

    I'll happily improve my code to your suggestions. I'm sure there is still many things to improve on. I also looked at FMDB months ago but I found it overly complex at that time for this particular purpose.

    @wsnook Please point out any rough edges and I'll get on it asap.

  18. tkrajacic commented on Jun 30, 2014

    @tkrajacic
    Contributor

    Yeah, #110 should include everything. the only thing is, that I had some 1,5MB mbtiles testfile in there and as far as I understand, it is still there in the history.
    That's why I wrote the obscure comment on the pull request. You'll have to decide if this is acceptable or not.

  19. ghost added a commit that references this issue on Jul 1, 2014
  20. modified the milestone: on Jan 23, 2015
  21. tkrajacic commented on Feb 2, 2015

    @tkrajacic
    Contributor

    Still watching here indeed! ;)

    Thanks for making this available!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions