Лучший способ сделать это - определить ширину экрана, отображаемую картой.Вы можете сделать это, используя пролет mapView, как на картах regionDidChangeAnimated
:
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
// Get the span and the center coordinate of the mapview
let span = mapView.region.span
let center = mapView.centerCoordinate
// Create two points on the left and right side of the region
let rightSide = CLLocationCoordinate2D(latitude: center.latitude + (span.latitudeDelta / 2), longitude: center.longitude)
let leftSide = CLLocationCoordinate2D(latitude: center.latitude - (span.latitudeDelta / 2), longitude: center.longitude)
// Calculate the distance between these two points (don't forget to convert to meters!)
let distance = calculateDistanceBetween(firstLoc: leftSide, secondGeoPoint: rightSide) * 1609.34
// Switch case the distance to handle zooming logic
switch distance {
case _ where distance < 1000:
// Handle logic for if the on screen width distance is < 1000 meters
case _ where distance < 5000:
// Handle logic for if the on screen width distance is < 5000 meters
default:
// Handle logic for if the on screen width distance is > 5000 meters
}
}
Где расстояние между любыми двумя GPS-координатами можно найти с помощью:
// Calculates the distance between two locations, returned in miles
func calculateDistanceBetween(firstLoc: CLLocationCoordinate2D, secondLoc: CLLocationCoordinate2D) -> Double {
// Convert lat's and long's into radians
let firstLatR = firstLoc.latitude * Double.pi / 180
let firstLongR = firstLoc.longitude * Double.pi / 180
let secondLatR = secondLoc.latitude * Double.pi / 180
let secondLongR = secondLoc.longitude * Double.pi / 180
// Calculate and return the distance
return 2 * 3963.1 * asin((pow(sin((secondLatR - firstLatR) / 2), 2) + cos(firstLatR) * cos(secondLatR) * pow(sin((secondLongR - firstLongR) / 2), 2)).squareRoot())
}
ЭтоСтоит отметить, что приведенное выше уравнение предполагает, что земля является идеальной сферой.Это должно быть более чем достаточно точно для вашего приложения.Проблема с нахождением истинного уровня «масштабирования» для карты состоит в том, что расстояние карты на ширине экрана (расстояние градуса долготы) изменяется в зависимости от вашей широты .