【问题标题】:Swift MKMapView Drop a Pin Annotation to Current LocationSwift MKMapView 将引脚注释放到当前位置
【发布时间】:2017-04-15 03:38:10
【问题描述】:

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

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.
}


}

【问题讨论】:

    标签: swift mkmapview


    【解决方案1】:

    如果您想将 pin 添加到用户位置,您可以在 didUpdateLocations 这样的委托方法中执行此操作

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

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

    【讨论】:

    • 当我实现这个时,它给了我错误“使用未解析的标识符'mapView'”
    • mapViewMapView 的变量名称,将其替换为MapView 变量map ,我也在我的回答中更新了它
    • 啊,我明白了。这已修复错误。我该如何测试呢?当我使用地图运行它时,它无法识别应用程序的当前位置。
    • 首先你需要在你的plist中添加'NSLocationAlwaysUsageDescription',在didUpdateLocation方法上添加断点并检查该方法是否被调用
    • 我已经在我的plist中添加了NSLocationAlwaysUsageDescription,并且我添加了断点,但是我没有注意到有变化,所以我认为该方法没有被调用。
    【解决方案2】:

    首先您需要在didUpdateLocations 方法中添加注释,然后每当添加任何注释时,都会调用viewForAnnotation,因此这里是在用户当前位置添加引脚的代码和相应方法:

    //在当前位置添加注释

     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            //Get Current Location
            let location = locations.last! as CLLocation
            let userLocation:CLLocation = locations[0] as CLLocation
            let myAnnotation: MKPointAnnotation = MKPointAnnotation()
            myAnnotation.coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude)
            myAnnotation.title = "Current location"
            map.addAnnotation(myAnnotation)
    }
    

    //将图像添加到用户当前位置图钉

        func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    
       guard !(annotation is MKUserLocation) else {
                let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "userLocation")
                annotationView.image = UIImage(named:"anyimage.png")
                return annotationView
            }
    return nil
    }
    

    如有其他问题,请随时询问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      相关资源
      最近更新 更多