Skip to content

Commit

Permalink
grid tile utils for zooms and regions
Browse files Browse the repository at this point in the history
  • Loading branch information
bosborn committed Aug 19, 2022
1 parent f6e56ab commit 2d5d947
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
5 changes: 5 additions & 0 deletions grid-ios/GridConstants.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,9 @@ public struct GridConstants {
*/
public static let EAST_CHAR = "E"

/**
* Mercator radius
*/
public static let MERCATOR_RADIUS = 85445659.44705395

}
59 changes: 59 additions & 0 deletions grid-ios/tile/TileUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//

import MapKit
import sf_ios

/**
* Tile Utils
Expand Down Expand Up @@ -135,4 +136,62 @@ public class TileUtils {
return toGridPoint(toCoordinate(point))
}

/**
* Get the current zoom level of the map view
*
* @param mapView map view
*
* @return current zoom level
*/
public static func currentZoom(_ mapView: MKMapView) -> Double {

let longitudeDelta = mapView.region.span.longitudeDelta
let width = mapView.bounds.size.width
let scale = longitudeDelta * GridConstants.MERCATOR_RADIUS * Double.pi / (SF_WGS84_HALF_WORLD_LON_WIDTH * width)
var zoom = Double(GridConstants.MAX_MAP_ZOOM_LEVEL) - log2(scale)
if (zoom < 0){
zoom = 0
}

return zoom
}

/**
* Get the current rounded zoom level of the map view
*
* @param mapView map view
*
* @return current zoom level
*/
public static func currentRoundedZoom(_ mapView: MKMapView) -> Int {
return Int(round(currentZoom(mapView)))
}

/**
* Get a coordinate region for the coordinate at the zoom level in the map view
*
* @param coordinate location coordinate
* @param zoom zoom level
* @param mapView map view
*
* @return coordinate region
*/
public static func coordinateRegion(_ coordinate: CLLocationCoordinate2D, _ zoom: Double, _ mapView: MKMapView) -> MKCoordinateRegion {

let scale = pow(2, Double(GridConstants.MAX_MAP_ZOOM_LEVEL) - zoom)

let width = mapView.bounds.size.width
let longitudeDelta = scale * SF_WGS84_HALF_WORLD_LON_WIDTH * width / (GridConstants.MERCATOR_RADIUS * Double.pi)

let height = mapView.bounds.size.height
let latitudeDelta = scale * SF_WGS84_HALF_WORLD_LAT_HEIGHT * height / (GridConstants.MERCATOR_RADIUS * Double.pi)


let span = MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta)

let region = MKCoordinateRegion(center: coordinate, span: span)

return region
}

}

0 comments on commit 2d5d947

Please sign in to comment.