我无法使用 MKPoint 注释添加多个引脚



我是Xcode的新手,我从来没有用swift为iPhone创建过应用程序,所以我仍然有很多麻烦。

在我的应用程序中,我想打开地图页面,并希望为每个地址显示一个图钉。为此,我创建了一个包含一些位置的 json。到目前为止,我只能访问此本地文件并使用它生成打印。但是当我尝试调用函数以在地图上创建引脚时,会出现错误。

import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var mapa: MKMapView!
var gerenciadorLocalizacao = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()
configurarGerenciadorLocalizacao()

guard let path = Bundle.main.path(forResource: "testeJSON", ofType: "json") else {return}
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
print(json)
guard let array = json as? [Any] else {return}
for user in array {
guard let userDict = user as? [String: Any] else {return}
guard let userId = userDict["id"] as? String else {return}
guard let name = userDict["nome"] as? String else {return}
guard let lat = userDict["latitude"] as? String else {return}
guard let lon = userDict["longitude"] as? String else {return}
guard let note = userDict["nota"] as? String else {return}
exibirLocalMapa(latitude: Double(lat)!, longitude: Double(lon)!, titulo: name, nota: note)
print(userId)
print(name)
print(lat)
print(lon)
print(note)
print(" ")  
}
}catch {
print(error)
}
}

func exibirLocalMapa(latitude: Double, longitude: Double, titulo: String, nota: String) {
let latitude: CLLocationDegrees = latitude
let longitude: CLLocationDegrees = longitude
let deltaLatitude: CLLocationDegrees = 0.01
let deltaLongitude: CLLocationDegrees = 0.01
let localizacao: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let areaVisualizacao: MKCoordinateSpan = MKCoordinateSpanMake(deltaLatitude, deltaLongitude)
let regiao: MKCoordinateRegion = MKCoordinateRegionMake(localizacao, areaVisualizacao)
self.mapa.setRegion(regiao, animated: true)

let anotacao = MKPointAnnotation()
//Configurar a anotação
anotacao.coordinate = localizacao
anotacao.title = titulo
anotacao.subtitle = nota
self.mapa.addAnnotation(anotacao)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func configurarGerenciadorLocalizacao(){
gerenciadorLocalizacao.delegate = self
gerenciadorLocalizacao.desiredAccuracy = kCLLocationAccuracyBest
gerenciadorLocalizacao.requestWhenInUseAuthorization()
gerenciadorLocalizacao.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status != .authorizedWhenInUse {
let alertaController = UIAlertController(title: "Permissão de Localização", message: "Necessário permissão para acesso à sua localização. Favor habilitar esta funcionalidade", preferredStyle: .alert)
let acaoConfiguracoes = UIAlertAction(title: "Abrir Configurações", style: .default, handler: {(alertaConfiguracoes) in
if let configuracoes = NSURL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.open(configuracoes as URL)
}
})
let acaoCancelar = UIAlertAction(title: "Cancelar", style: .default, handler: nil)
alertaController.addAction(acaoConfiguracoes)
alertaController.addAction(acaoCancelar)
present(alertaController, animated: true, completion: nil)
}
}
}

请按照以下步骤在地图上删除所有图钉:

  1. 您必须使用for 循环从 JSON 文件中获取所有详细信息并将其存储在数组中。

  2. 调用函数,它将使用纬度,经度,地点名称和存储数组中的注释在地图上标记注释。

祝您编码愉快!

也许您可以尝试创建自己的扩展MKPointAnnotation的类,然后将JSON的元素映射到该自定义类的数组中,最后调用mapView.addAnnotations(yourAnnotationsArrayHere(。

尝试遵循以下示例: https://www.raywenderlich.com/160517/mapkit-tutorial-getting-started

我推荐你这个网站从iOS开发开始。

最新更新