how can I center my map on the annotation view only when it is close to the edge of the screen?
Asked Answered
Z

1

1

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?

Zoril answered 23/10, 2016 at 18:7 Comment(0)
A
1

I would not compare the location of your annotation to all four edges, but check the distance from the center location.

let distance = center.distanceFromLocation(annotationLocation)

If this distance is bigger than a certain radius, the annotation is close to one of the edges.

if distance > radius {
    //center annotation
}

The radius can be calculated from the region span.

let radius = min(region.span.longitudeDelta, region.span.latitudeDelta) * 0.3
Ankeny answered 26/10, 2016 at 19:12 Comment(2)
Why is the multiplication with 0.3?Gilbart
that’s just a factor which you can defineAnkeny

© 2022 - 2024 — McMap. All rights reserved.