gpt4 book ai didi

Swift MKMapView 将 Pin 注解放到当前位置

转载 作者:IT王子 更新时间:2023-10-29 05:25:51 25 4
gpt4 key购买 nike

我希望能够向应用用户询问他/她的当前位置,并在该位置自动放置一个图钉。这是我获取当前位置的代码,但我无法理解如何为当前位置放置图钉。

import UIKit
import MapKit
import CoreLocation


class MapVC: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {



@IBOutlet weak var map: MKMapView!

let locationManager = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()

// User's location

locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if #available(iOS 8.0, *) {
locationManager.requestAlwaysAuthorization()
} else {
// Fallback on earlier versions
}
locationManager.startUpdatingLocation()

// add gesture recognizer
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(MapVC.mapLongPress(_:))) // colon needs to pass through info
longPress.minimumPressDuration = 1.5 // in seconds
//add gesture recognition
map.addGestureRecognizer(longPress)
}

// func called when gesture recognizer detects a long press

func mapLongPress(_ recognizer: UIGestureRecognizer) {

print("A long press has been detected.")

let touchedAt = recognizer.location(in: self.map) // adds the location on the view it was pressed
let touchedAtCoordinate : CLLocationCoordinate2D = map.convert(touchedAt, toCoordinateFrom: self.map) // will get coordinates

let newPin = MKPointAnnotation()
newPin.coordinate = touchedAtCoordinate
map.addAnnotation(newPin)


}

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




//set region on the map
self.map.setRegion(region, animated: true)



}

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


}

最佳答案

如果你想将 pin 添加到用户位置,你可以在 didUpdateLocations 委托(delegate)方法中这样做

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
mapView.removeAnnotation(newPin)

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

//set region on the map
map.setRegion(region, animated: true)

newPin.coordinate = location.coordinate
map.addAnnotation(newPin)

}

为你的pin创建一个全局变量

let newPin = MKPointAnnotation()

因此,每当用户移动到新位置时,先前的图钉将被删除,新图钉将添加到更新后的位置。

关于Swift MKMapView 将 Pin 注解放到当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40894722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com