【问题标题】:Swift - map returns to starting pointSwift - 地图返回起点
【发布时间】:2015-02-26 17:30:53
【问题描述】:

我的应用程序中有一张地图,但是当我移动地图时,我一放手,它就会返回到起点。我不希望这种情况发生..

我的 ViewController 看起来像这样:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    if (CLLocationManager.locationServicesEnabled())
    {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    let location = locations.last as CLLocation

    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.map.setRegion(region, animated: true)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

【问题讨论】:

    标签: ios swift maps


    【解决方案1】:

    CLLocationManagerstartUpdatingLocation 将用户位置的更新发送到locationManager:didUpdateLocations:

    调用此方法会导致位置管理器获取初始位置修复(可能需要几秒钟)并通过调用其 locationManager:didUpdateLocations: 方法通知您的委托。

    那么在locationManager:didUpdateLocations: 中,您使用setRegion:animated: 将地图移动到的区域是刚刚发送的位置,即用户的位置。

    【讨论】:

      【解决方案2】:

      您在 didUpdateLocations 委托方法中设置 mapView 的区域。

      一旦你开始调用startUpdatingLocation(),它就会开始不断的检索你的位置坐标,你的didUpdateLocations方法会被调用,你的mapView会被你方法中的setRegion()更新。

      您可以将位置管理器的distanceFilter 的值更改为更大的数字,这样它的更新频率就会降低。默认使用kCLDistanceFilterNone,所以你的didUpdateLocations会被所有动作调用。

      【讨论】:

      • 好吧,这对我有点帮助,但我想在用户启动应用程序时获取用户当前位置,但随后停止更新,这是如何完成的?
      • 你的问题与原来的问题完全不同,你应该再发一个帖子。如果你问在获取用户当前位置后如何停止更新 mapView,我会告诉你使用stopUpdatingLocation(),而不是告诉你做其他事情。
      【解决方案3】:

      所以看来我只需要将 locationManager.stopUpdatingLocation() 添加到 didUpdateLocations 函数中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-31
        • 1970-01-01
        • 1970-01-01
        • 2019-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多