如何使用Mapkit View / Swift 4获取和显示位置

大家好,在本文中,我将告诉您如何使用iOS应用程序Swift 4的mapkit视图获取和显示位置。

首先,不要忘记“ import MapKit

之后,您需要将Mapkitview放入UIView并以IBOutlet的形式连接到控制器类,如下所示;

@IBOutlet弱var mapKitView:MKMapView!

我们有两个不同的变量来确定位置,分别称为lat和lng。

例如,伊斯坦布尔的Lat和LNG; lat = 41.015137 lng = 28.979530

公共静态变量lat:Double = 41.015137

公共静态变量lng:Double = 28.979530

然后,您需要使用CLLocationManager在您的viewcontroller类中,定义如下。

var locationManager:CLLocationManager!

在您的视图中,您确实需要同步mapkit委托自己的类。

覆盖func viewDidLoad(){super.viewDidLoad(){

self.mapKitView.delegate =自我

}

现在,由于使用mapkit视图函数,我们必须为UIViewController类添加扩展。

扩展UIViewController:CLLocationManagerDelegate,MKMapViewDelegate {

func locationManager(_管理器:CLLocationManager,didUpdateLocations位置:[CLLocation]){

让userLocation:CLLocation = location [0]作为CLLocation

让中心= CLLocationCoordinate2D(纬度:UIViewController.lat,经度:UIViewController.lng)

let region = MKCoordinateRegion(center:center,span:MKCoordinateSpan(latitudeDelta:0.01,longitudeDelta:0.01))self.mapKitView.setRegion(region,animation:true)//在用户当前位置放置图钉

让myAnnotation:MKPointAnnotation = MKPointAnnotation()myAnnotation.coordinate = CLLocationCoordinate2DMake(UIViewController.lat,UIViewController.lng); myAnnotation.title =“伊斯坦布尔位置” mapKitView.addAnnotation(myAnnotation)}

func locationManager(_管理器:CLLocationManager,didFailWithError错误:错误){print(“错误\(错误)”)

}

}

最后,您需要添加一个我编写的函数,该函数称为defineLocation()。 您可以在viewDidAppear()或ViewDidload中调用函数。

func defineLocation(){

locationManager = CLLocationManager()

locationManager.delegate =自身locationManager.requestWhenInUseAuthorization()locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization()

如果CLLocationManager.locationServicesEnabled(){locationManager.startUpdatingLocation()

}

}

在你的viewdidAppear();

覆盖func viewDidAppear(_动画:布尔){

确定位置()

}

希望本文对您有所帮助🙂放轻松🙂