2016-11-30 6 views
8

앱 사용자에게 현재 위치를 물어보고 해당 위치에 핀을 자동 삭제하도록했습니다. 여기에 현재 위치를 잡아 내 코드가 있지만 현재 위치에 핀을 떨어 뜨리는 방법을 이해하는 데 문제가 있습니다. //Swift MKMapView 현재 위치에 핀 주석 놓기

추가 : 어떤 주석이 첨가 될 때마다

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


} 

답변

13

당신이 당신의 핀

let newPin = MKPointAnnotation() 

위해 작성 전역 변수를이

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) 

} 

같은 didUpdateLocations 위임 방법으로 그렇게 할 수있는 사용자의 위치에 핀을 추가하고 싶은 경우에 따라서 사용자가로 이동합니다 때마다 새 위치는 이전 핀이 제거되고 새 핀이 업데이트 된 위치에 추가됩니다.

+0

이것을 구현하면 나에게 "사용하지 않은 식별자 'mapView'사용" – Kevin

+0

'mapView'는'MapView' 변수의 이름이고'MapView' 변수는'map'입니다. 내 대답에 그것을 업데이 트했습니다 – Rajat

+0

아 내가 본다. 이로 인해 오류가 수정되었습니다. 어떻게 테스트 할 수 있습니까? 지도로 실행할 때 앱의 현재 위치를 인식하지 못합니다. – Kevin

3

먼저 당신은 viewForAnnotation 지금 여기라는 사용자의 현재 위치에 핀을 추가 할 수있는 코드와 대응 방법입니다 다음 didUpdateLocations 방법에 주석을 추가 할 필요가 현재 위치에 주석

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 
} 

추가 문제가 있는지 물어보십시오.