使地图缩放到用户位置和注释 (swift 2)

Making the map zoom to user location and annotation (swift 2)

我正在使用 mapkit。我希望地图缩放以显示用户的位置和注释点,而不是仅仅缩放到用户的当前位置。

目前我有:

                            let annotation = MKPointAnnotation()
                            annotation.coordinate = CLLocationCoordinate2DMake(mapLat, mapLon)
                            annotation.title = mapTitle
                            self.map.addAnnotation(annotation)

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLoction: CLLocation = locations[0]
    let latitude = userLoction.coordinate.latitude
    let longitude = userLoction.coordinate.longitude
    let latDelta: CLLocationDegrees = 0.05
    let lonDelta: CLLocationDegrees = 0.05
    let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
    let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
    let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
    self.map.setRegion(region, animated: true)
    self.map.showsUserLocation = true
}

它只是缩放到用户的位置并锁定在该位置。当我尝试滚动时,它只是跳回到用户的位置。我究竟做错了什么?如何允许用户在不跳回当前位置的情况下在地图上缩放或移动?

我正在尝试放大以在同一视图中显示注释和用户的位置。即使注释很远,我也希望它缩放以同时显示用户和注释。

它只是直接跳回到用户所在的位置,因为didUpdateLocations方法被调用了很多次。有两种解决方法。

1) 使用requestLocation

如果您使用 requestLocation 方法而不是 startUpdatingLocationdidUpdateLocations 方法只会被调用一次

if #available(iOS 9.0, *) {
    locationManager.requestLocation()
} else {
    // Fallback on earlier versions
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLoction: CLLocation = locations[0]
    let latitude = userLoction.coordinate.latitude
    let longitude = userLoction.coordinate.longitude
    let latDelta: CLLocationDegrees = 0.05
    let lonDelta: CLLocationDegrees = 0.05
    let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
    let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
    let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
    self.map.setRegion(region, animated: true)
    self.map.showsUserLocation = true
}

2) 使用标志

var isInitialized = false

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if !isInitialized {
        // Here is called only once
        isInitialized = true

        let userLoction: CLLocation = locations[0]
        let latitude = userLoction.coordinate.latitude
        let longitude = userLoction.coordinate.longitude
        let latDelta: CLLocationDegrees = 0.05
        let lonDelta: CLLocationDegrees = 0.05
        let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
        let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
        let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
        self.map.setRegion(region, animated: true)
        self.map.showsUserLocation = true
    }
}