问题
I have coordinates of a single pin on my map. I try to center my map on that pin, but I don't want to keep the pin directly in the middle of the map, but in 1/3 of the screen. I tried to do it in the following workaround:
let coordinateRegion = MKCoordinateRegionMakeWithDistance(coordinatesOfThePin, 500, 500)
mapView.setRegion(coordinateRegion, animated: true)
let frame = mapView.frame
let myPoint = CGPointMake(frame.midX, frame.midY/3)
let myCoordinate = mapView.convertPoint(myPoint, toCoordinateFromView: mapView)
let coordinateRegion2 = MKCoordinateRegionMakeWithDistance(myCoordinate, 500, 500)
mapView.setRegion(coordinateRegion2, animated: true)
but it shows random positions depending on the first position of the map. Can you help me with rewriting my code so that I could just put a pin location and get the result as follows:
-------------------
| |
| |
| X | <-- my pin in the 1/3 of the visible map area.
| |
| |
| |
| |
| |
| |
| |
| |
-------------------
回答1:
If you want the point to use the current zoom in scale, but just center on a coordinate such that it's 1/3rd the way up the screen, you could just set the centerCoordinate
and then nudge it up one sixth the latitudeDelta
of the span
:
func updateMapForCoordinate(coordinate: CLLocationCoordinate2D) {
var center = coordinate;
center.latitude -= self.mapView.region.span.latitudeDelta / 6.0;
mapView.setCenterCoordinate(center, animated: true);
}
Tweak the adjustment of the center
as you see fit, but hopefully this illustrates one simple approach. Obviously, this little trick only works if the map is has no pitch and isn't rotated.
If you want to zoom in first, you can set the camera, and then reset the centerCoordinate
:
func updateMapForCoordinate(coordinate: CLLocationCoordinate2D) {
let camera = MKMapCamera(lookingAtCenterCoordinate: coordinate, fromDistance: 1000, pitch: 0, heading: 0)
mapView.setCamera(camera, animated: false)
var center = coordinate;
center.latitude -= self.mapView.region.span.latitudeDelta / 6.0;
mapView.setCenterCoordinate(center, animated: false);
}
来源:https://stackoverflow.com/questions/37288138/how-can-i-center-my-mapview-so-that-the-selected-pin-is-not-in-the-middle-of-the