0

所以我搜索并找到了多篇关于创建唯一注释和引脚的文章,但我认为我缺少一些更基本的东西,可能使用 MKMapViewDelegate 下的 annotationView 函数。

首先,我对 Swift 编程非常陌生,所以如果这是显而易见的事情,请提前道歉。本质上,我有一个 mapView,它通过放大动画找到用户位置。然后我有一个按钮,它将按钮标题传递给 MKLocalSearch 和一个 for/in 循环,它创建我的注释并将它们添加到我的地图视图中。问题是第一次单击我的按钮时没有添加注释,我必须再次单击才能显示注释。

我已经尝试过 DispatchQueue.main.async 并尝试在此循环上设置延迟执行以允许响应完成以进行处理,这是我的 viewController 顶部的相关部分(我只包含了相关代码,我的 CLLocationManagerDelegate 有一个扩展,它可以正常工作,如前所述):

import UIKit
import CoreLocation
import MapKit

class MapViewController: UIViewController, MKMapViewDelegate {
    
    var weatherManager = WeatherManager()
    let locationManager = CLLocationManager()
    let request = MKLocalSearch.Request()
    var localSearch: MKLocalSearch?
    
    @IBOutlet weak var tempLabel: UILabel!
    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet weak var conditionImageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestLocation()
        weatherManager.delegate = self
    }
    @IBAction func foodPressed(_ sender: UIButton) {
        let allAnnotations = mapView.annotations
        mapView.removeAnnotations(allAnnotations)
        findPlace(place: (sender.titleLabel?.text)!)
        
    }
    
    func findPlace(place: String) {
        localSearch = MKLocalSearch(request: request)
        request.naturalLanguageQuery = place
        request.region = mapView.region
        self.localSearch?.start { (searchResponse, _) in
            guard let response = searchResponse else {
                return
            }
            for mapItem in response.mapItems {
                let place = MKPointAnnotation()
                place.title = mapItem.name
                place.coordinate = mapItem.placemark.coordinate
                self.mapView.addAnnotation(place)
            }
        }
    }
    
}
4

1 回答 1

0

弄清楚了。

localSearch = MKLocalSearch(request: request) 高于我的代码的区域和搜索条件语句:

localSearch = MKLocalSearch(request: request)
request.naturalLanguageQuery = place
request.region = mapView.region

正确的代码是:

request.naturalLanguageQuery = place
request.region = mapView.region
localSearch = MKLocalSearch(request: request)
于 2020-11-20T15:54:22.580 回答