我已经在swift中创建了单个视图应用程序。我将MKMapView放在main.storyboard上的viewController上。然后我导入了
import MapKit
MapVC中的。在viewDidLoad函数中
mapView.delegate=self
我做了扩展MKMapViewDelegate
extension MapVC :MKMapViewDelegate{
func centerMapOnUserLocation() {
guard let coordinate = locationManager.location?.coordinate else {return}
let coordinateRegion = MKCoordinateRegionMakeWithDistance(coordinate, regionRadius*0.2, regionRadius*0.2)
mapView.setRegion(coordinateRegion, animated: true)
}
}
然后我跑了项目我给了我当前位置的地图。
不工作 1-用于丢弃用户当前位置的引脚和缩放。 我导入了
import CoreLocation
var locationManager=CLLocationManager()
let authorizationStatus=CLLocationManager.authorizationStatus()
let regionRadius:Double=1000
在viewDidLoad函数中
locationManager.delegate=self
configureLocationService()
我制作了CLLocationManagerDelegate
extension MapVC:CLLocationManagerDelegate{
func configureLocationService() {
if authorizationStatus == .notDetermined{
//app doesnt know whether it is approved or denied
locationManager.requestAlwaysAuthorization()
//request authorization so location is used always where app opened or not
}
else
{ //is determined means :1-already apporoved 2- already denied dont need to do any thing just return
return
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
centerMapOnUserLocation()
}
}
不工作 2-I在main.storybaord的viewcontroller中放置了MKMapView左下角的按钮,其功能是将当前用户位置放在视图控制器的中心
@IBAction func centerMapBtnWasPressed(_ sender: Any) {
if authorizationStatus == .authorizedAlways || authorizationStatus == .authorizedWhenInUse
{
centerMapOnUserLocation()
}
}
我如何获取当前用户位置的图钉并获取有关当前用户和位置的缩放地图,并将地图置于当前用户位置的中心位置?
您可以从此link
下载该项目答案 0 :(得分:0)
添加图钉:
let annotation = MKPointAnnotation() // add it globally so you can remove to update location
func addPin(coord: CLLocationCoordinate2D) {
mapView.removeAnnotation(annotation)
let centerCoordinate = CLLocationCoordinate2D(latitude: coord.latitude, longitude:coord.longitude)
annotation.coordinate = centerCoordinate
annotation.title = "My Pin"
mapView.addAnnotation(annotation)
centerZoom(annotation)
}
放大:
func centerZoom(myPoint: MKPointAnnotation) {
let mapCenter = myPoint.coordinates
let span = MKCoordinateSpanMake(0.1, 0.1)
let region = MKCoordinateRegionMake(mapCenter, span)
mapView.region = region
}
您可以通过添加此委托方法的位置管理员获取位置更新:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let loc: CLLocationCoordinate2D = locations.first!.coordinate
addPin(loc)
}
或者您可以将MapView委派给视图控制器并使用此委托方法:
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
addPin(userLocation.coordinate)
}