Swift 3 中 MKLocalSearch 的注释 — 地图查看当前位置



这是我第一次使用Stack Overflow。我一直在尝试制作一个应用程序,该应用程序可以找到用户的当前位置并输出医生靠近用户的信息。到目前为止,我可以找到当前位置,但是,我无法为当前位置附近的医生添加注释。

这是我到目前为止的代码:

import UIKit
import MapKit
import CoreLocation
class ThirdViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var map: MKMapView!
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "doctor"
request.region = map.region
let localSearch:MKLocalSearch = MKLocalSearch(request: request)
localSearch.start(completionHandler: {(result, error) in
for placemark in (result?.mapItems)! {
if(error == nil) {
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake(placemark.placemark.coordinate.latitude, placemark.placemark.coordinate.longitude)
annotation.title = placemark.placemark.name
annotation.subtitle = placemark.placemark.title
self.map.addAnnotation(annotation)
}
else
{
print(error ?? 0)
}
}
})
}

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

}

感谢所有回复,如果您对我下次提问时应该做什么有任何建议,请将其留在下面。谢谢。

您的地图视图需要一个具有map​View(_:​view​For:​)实现的委托。否则,添加批注将没有明显效果。

要添加注释,您需要继承MKMapViewDelegate。 然后添加:mapView.delegate = self到您的初始化方法。 并实现此功能:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if !(view.annotation! is MKUserLocation) {
let customPin = view.annotation as! CustomPin //if u wanna use custom pins
configureDetailView(annotationView: view, spotPin: customPin.spotDetailsItem) //configuring view for tap
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
if !(annotation is CustomPin) {
return nil
}
let identifier = "CustomPin"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.canShowCallout = true
} else {
annotationView!.annotation = annotation
}
return annotationView
}

配置详细视图方法和其他信息,你可以在这里找到(它很麻烦)

最新更新