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

后端 未结 1 1217
青春惊慌失措
青春惊慌失措 2021-01-02 08:16

I am working with mapkit. I want the map to zoom to show the user\'s location and the annotated point, instead of just zooming to the user\'s current location.

Curre

相关标签:
1条回答
  • 2021-01-02 08:59

    It just jumps right back to the user's location, because didUpdateLocations method is called many times. There are two solutions.

    1) Use requestLocation

    If you use requestLocation method instead of startUpdatingLocation, didUpdateLocations method is called only once

    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) Use flag

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题