In my swift
application I'm using MapKit
and I'm adding some annotations to the map.
Currently, thanks to this question: Trying to get the span size in meters for an iOS MKCoordinateSpan I managed to create a functionality that centers my map on the annotation when user presses it. This is the code for it:
let span = mapView.region.span
let centerView = mapView.region.center
let loc1 = CLLocation(latitude: centerView.latitude - span.latitudeDelta * 0.5, longitude: centerView.longitude)
let loc2 = CLLocation(latitude: centerView.latitude + span.latitudeDelta * 0.5, longitude: centerView.longitude)
let loc3 = CLLocation(latitude: centerView.latitude, longitude: centerView.longitude - span.longitudeDelta * 0.5)
let loc4 = CLLocation(latitude: centerView.latitude, longitude: centerView.longitude + span.longitudeDelta * 0.5)
let metersInLatitude = loc1.distance(from: loc2)
let metersInLongitude = loc3.distance(from: loc4)
let center:CLLocationCoordinate2D = (MyCustomAnnotation?.coordinate)!
let coordinateRegion = MKCoordinateRegionMakeWithDistance(center, metersInLatitude, metersInLongitude)
mapView.setRegion(coordinateRegion, animated: true)
and that works fine - every time when user clicks on any MyCustomAnnotation
, it will center the map while keeping the current zoom level.
I want to change this code a little, so it centers the map on the point only when the point is close to one of four edges of the screen. When the annotation point is somewhere close to the center of the screen - we should not center the map. How can I do it? I thought about checking (somehow) the difference between MyCustomAnnotation?.coordinate
and the area set by those four points loc1
, loc2
, loc3
, loc4
, but I'm not sure how to handle it. Can you help me with that?