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

时间:2015-10-09 17:37:14

标签: ios swift annotations mapkit

我正在使用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
}

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

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

1 个答案:

答案 0 :(得分:10)

它只是直接跳回用户的位置,因为多次调用didUpdateLocations方法。有两种解决方案。

1)使用requestLocation

如果您使用requestLocation方法而不是startUpdatingLocation,则只会调用didUpdateLocations方法一次

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
    }
}