繁体   English   中英

如何通过代码获取iPhone的当前位置?

[英]How to get the current location of iPhone through code?

你如何通过代码获取iPhone的当前位置? 我需要使用GPS跟踪位置。

开发人员网站上有(通常用于核心功能)综合文档,您可能会发现此示例很有用;

要记住的关键点是;

1)一旦开始接收位置更新,它们就会异步到达,您需要在它们进入时对它们做出响应。检查准确性和时间戳,以决定是否要使用该位置。

2)不要忘记在获得所需位置后立即停止接收更新(这可能不是第一个),否则会耗尽电池寿命。

3)返回给您的第一个位置通常是最后一个位置,并且手机将报告此位置时具有与之前修复时相同(可能很高)的准确度。 因此,您可能会得到一个声称精确到10米的修复程序,但实际上是在距离您当前位置数英里的情况下昨天收到的。 这样做的座右铭是不要忘记检查TIMESTAMP - 这会告诉您何时实际收到了位置修复。 这是一个如何检查时间戳的示例

希望有所帮助。

您正在寻找“CoreLocation”API。

这是一个教程

CLLocationManager上的这个页面有五个源代码示例

下载此示例 ,它将显示您当前的位置

如果您只需要获取设备的当前位置,则直接使用Core Location需要大量代码,因为您必须处理延迟,直到设备的GPS对当前位置有准确的修复,这需要几秒钟。 (CLLocationManager API似乎是为需要连续位置更新的应用程序构建的,例如转弯GPS导航应用程序。)

我建议你不要直接使用CLLocationManager,而是使用一个开源组件,例如INTULocationManager ,它将为你处理所有这些工作,并且很容易为设备的当前位置请求一个或多个离散请求。

完整代码如下

1拖动地图导入框架给代表

在这段代码的最后一行self.yourmapreferencename.setRegion ...

//这里的所有代码

import UIKit导入MapKit导入CoreLocation类ViewController:UIViewController,CLLocationManagerDelegate {

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

override func viewDidLoad() {
    super.viewDidLoad()

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

    }

}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{

    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.mapView.setRegion(region, animated: true)
}

}

真正的解决方案可以在这里找到。 Z5概念iOS开发代码片段

它只需要一点点编码。

- (IBAction)directions1_click:(id)sender
{
    NSString* address = @"118 Your Address., City, State, ZIPCODE";
    NSString* currentLocation = @"Current Location";
    NSString* url = [NSStringstringWithFormat: @"http://maps.google.com/maps?saddr=%@&daddr=%@",[currentLocation stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    UIApplication *app = [UIApplicationsharedApplication];
    [app openURL: [NSURL URLWithString: url]];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM