实际上,keithbhunter 的代码很慢,因为除了更新区域的速度超过了加载速度之外,地图还在改变高度,这会导致额外的开销!
我更新了代码,使其运行顺畅。
使用此代码,我所做的是保持地图视图的大小相同,而是移动中心点以补偿滑动视图的高度。
要使此代码正常工作,您必须修改 keithbhunter 的设置,以便将 mapView 的底部约束完全固定到超级视图的底部(而不是滑动视图(因此 mapView 始终与超级视图大小相同)。其余的设置是一样的。
也可以使用变量自定义缩放量maxMetersDistance
我在这里,始终以埃菲尔铁塔为中心
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var slidingView: UIView!
@IBOutlet weak var slidingViewHeight: NSLayoutConstraint!
var maxMetersDistance:CGFloat = 10000.0; // customize this to set how far the map zooms out of the interest area
override func viewDidLoad() {
super.viewDidLoad()
let pan = UIPanGestureRecognizer(target: self, action: "viewDidPan:")
self.slidingView.addGestureRecognizer(pan)
firstTimeCenter()
}
func firstTimeCenter(){
var coordinate = CLLocationCoordinate2D(latitude: 48.8582, longitude: 2.2945)
let region = MKCoordinateRegionMakeWithDistance(coordinate, Double(maxMetersDistance), Double(maxMetersDistance))
self.mapView.setRegion(region, animated: true)
}
func reloadMap() {
let height = CGFloat(self.slidingViewHeight.constant)
var regionDistance = (maxMetersDistance / self.view.frame.height) * height
regionDistance = maxMetersDistance - regionDistance
var coordinate = CLLocationCoordinate2D(latitude: 48.8582, longitude: 2.2945)
var mapRect = mapView.visibleMapRect;
var metersPerMapPoint = MKMetersPerMapPointAtLatitude(coordinate.latitude);
var metersPerPixel = CGFloat(metersPerMapPoint) * CGFloat(mapRect.size.width) / CGFloat(mapView.bounds.size.width);
var totalMeters = Double(metersPerPixel) * Double(height/2)
coordinate = self.translateCoord(coordinate, MetersLat: -totalMeters, MetersLong: 0.0)
let region = MKCoordinateRegionMakeWithDistance(coordinate, Double(regionDistance), Double(regionDistance))
self.mapView.setRegion(region, animated: false)
}
func viewDidPan(panGesture: UIPanGestureRecognizer) {
let location = panGesture.locationInView(self.view)
self.slidingViewHeight.constant = self.view.frame.size.height - location.y
self.reloadMap()
}
func translateCoord(coord:CLLocationCoordinate2D, MetersLat:Double, MetersLong:Double)->CLLocationCoordinate2D{
var tempCoord = CLLocationCoordinate2D()
var tempRegion = MKCoordinateRegionMakeWithDistance(coord, MetersLat, MetersLong);
var tempSpan = tempRegion.span;
tempCoord.latitude = coord.latitude + tempSpan.latitudeDelta;
tempCoord.longitude = coord.longitude + tempSpan.longitudeDelta;
return tempCoord;
}
}