Skip to content

Instantly share code, notes, and snippets.

@ryanhanwu
Last active November 4, 2022 11:43
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryanhanwu/4dbcdbdf384f5a3cca1f to your computer and use it in GitHub Desktop.
Save ryanhanwu/4dbcdbdf384f5a3cca1f to your computer and use it in GitHub Desktop.
Calculate Google Map length in meters with zoom level in #Objective-C (converted from #JavaScript) #iOS #Swift
- (void)mapView:(GMSMapView*)mapView idleAtCameraPosition:(GMSCameraPosition*)position
{
CLLocationCoordinate2D topLeft = mapView.projection.visibleRegion.farLeft;
CLLocationCoordinate2D bottomLeft = mapView.projection.visibleRegion.nearLeft;
double lat = fabs(topLeft.latitude - bottomLeft.latitude);
double mpp = cos(lat * M_PI / 180) * 2 * M_PI * 6378137 / (256 * pow(2, mapView.camera.zoom));
double distance = mpp * mapView.frame.size.width;
[[SearchManager shareInstance] distance: distance];
}
var metersPerPixel = Math.cos(lat * Math.PI/180) * 2 * Math.PI * 6378137 / (256 * Math.pow(2, zoom));
@chrischute
Copy link

Swift answer for 2019

/// Radius of the visible region shown on the map (in meters)
private var visibleRadius: Double {
    // Get CLLocation for top-left of map
    let topLeft = CGPoint.zero
    let topLeftCoordinate = mapView.projection.coordinate(for: topLeft)
    let topLeftLocation = CLLocation(latitude: topLeftCoordinate.latitude,
                                       longitude: topLeftCoordinate.longitude)
    
    // Get CLLocation for bottom-right of map
    let bottomRight = CGPoint(x: mapView.bounds.width, y: mapView.bounds.height)
    let bottomRightCoordinate = mapView.projection.coordinate(for: bottomRight)
    let bottomRightLocation = CLLocation(latitude: bottomRightCoordinate.latitude,
                                         longitude: bottomRightCoordinate.longitude)
    
    // Radius is half of distance from top-left to bottom-right
    return Double(bottomRightLocation.distance(from: topLeftLocation) / 2)
}

@paultas
Copy link

paultas commented Aug 7, 2020

@chrischute thank you, works perfect

@chrischute
Copy link

👍

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