gpt4 book ai didi

arrays - 在 map View 上显示多个注释

转载 作者:行者123 更新时间:2023-11-28 15:40:41 26 4
gpt4 key购买 nike

我一直在 stackoverflow 上寻找解决方案,但我还没有成功实现它。如果有人可以给我一些关于问题所在的提示,非常感谢。这是我目前所拥有的

这是位置类

class Location: NSObject, MKAnnotation {
var title: String?
var coordinate: CLLocationCoordinate2D

init(title: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.coordinate = coordinate
}

显示所有注释的方法。

func displayAllEventsPins() {
for event in events {
let address = event.location
geocoder.geocodeAddressString(address!, completionHandler: { (placemarks: [CLPlacemark]?, error: Error?) -> Void in
if let placemark = placemarks?.first {
let eventlat = placemark.location?.coordinate.latitude
let eventlong = placemark.location?.coordinate.longitude
let annotation = MKPointAnnotation()
annotation.title = event.name
annotation.coordinate = CLLocationCoordinate2D(latitude: eventlat!, longitude: eventlong!)
self.locations.append(Location(title: annotation.title!, coordinate: annotation.coordinate))
for location in self.locations {
let pin = MKPointAnnotation()
pin.title = location.title
pin.coordinate = location.coordinate
self.mapView.addAnnotation(pin)
}
}
})
}

}

已编辑:这里的问题是 map View 上没有显示注释。我只能看到 currentlocation 引脚,没有别的。

已编辑:这是我用来删除用户当前位置 pin 的调用。

extension Search : CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
locationManager.requestLocation()

}
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//MARK: remove previous current pin for user location
mapView.removeAnnotation(newPin)

let location = locations.last! as CLLocation
let center = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
self.currentLocation = location
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpanMake(0.03, 0.03))
mapView.setRegion(region, animated: true)
newPin.coordinate = location.coordinate
mapView.addAnnotation(newPin)
}
}

这是 viewDidLoad 方法中的代码:

 override func viewDidLoad() {
super.viewDidLoad()

//MARK: Request Current Location
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.requestLocation()
displayAllEventsPins()
}

最佳答案

这应该适合您。

顺便说一句,在事件循环中循环遍历您的位置只会添加相同 pin 的副本,这对内存非常不利,这不是一件好事。

import UIKit
import MapKit
import Firebase

class ViewController: UIViewController, MKMapViewDelegate {

@IBOutlet weak var map: MKMapView!

let locationManager = CLLocationManager()

var events = Array<Event>()

var locations = Array<Location>()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

locationManager.requestWhenInUseAuthorization()

locationManager.startUpdatingLocation()

locationManager.desiredAccuracy = kCLLocationAccuracyBest

// This closure gets called once for every event in your database
getEvents { (event, pin) in

self.tableView.reloadData()

if event != nil && pin != nil {

print(event!)

self.locations.append(pin!)

self.events.append(event!)

} else {

print("Failed to get event.")
}
}
}

func getEvents(results: @escaping (_ event: Event?, _ pin:Location?)->()) {

let ref = FIRDatabase.database().reference().child("Events")

ref.observe(.childAdded, with: { (snapshot) in

guard let value = snapshot.value as? Dictionary<String,String> else { return }

guard let name = value["eventName"],
let location = value["location"],
let attending = value["attendance"],
let dateTime = value["dateTime"],
let addedByUser = value["addedByUser"] else { return }

self.getEventPlacemark(address: location, results: { (placemark) in

if let placemark = placemark {

let pin = Location(title: name, coordinate: placemark.coordinate)

var distance: Double = -1 // If user location is not avalible, this will stay at -1

if let currentLocation = self.locationManager.location?.coordinate {

distance = pin.coordinate.distance(to: currentLocation)
}

let event = Event(id: snapshot.key, name: name, location: location, dateTime: dateTime, addedByUser: addedByUser, attending: attending, distance: distance)

results(event, pin)

return
}
})
})
}

func getEventPlacemark(address:String, results: @escaping (_ placemark: MKPlacemark?)->()){

let geocoder = CLGeocoder()

geocoder.geocodeAddressString(address) { (placemarks, error) in

if let error = error {

print(error.localizedDescription)

results(nil)
}

if let placemark = placemarks?.first {

results(MKPlacemark(placemark: placemark))
}
}
}

func displayAllEvents(){

self.map.addAnnotations(self.locations)
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

if let userLocation = annotation as? MKUserLocation {

let view = (mapView.dequeueReusableAnnotationView(withIdentifier: "userLocationPin") as? MKPinAnnotationView) ?? MKPinAnnotationView(annotation: userLocation, reuseIdentifier: "userLocationPin")

view.pinTintColor = .purple

view.canShowCallout = true

return view
}

if let pin = annotation as? MKPointAnnotation {

let view = (mapView.dequeueReusableAnnotationView(withIdentifier: "pin") as? MKPinAnnotationView) ?? MKPinAnnotationView(annotation: pin, reuseIdentifier: "pin")

view.pinTintColor = .red

view.canShowCallout = true

return view
}

return nil
}
}

class Location: NSObject, MKAnnotation {

var title: String?

var coordinate: CLLocationCoordinate2D

init(title: String, coordinate: CLLocationCoordinate2D) {

self.title = title

self.coordinate = coordinate
}
}


struct Event {

var name: String

var location: String
}

extension CLLocationCoordinate2D {

func distance(to: CLLocationCoordinate2D) -> CLLocationDistance {

return MKMetersBetweenMapPoints(MKMapPointForCoordinate(self), MKMapPointForCoordinate(to))
}
}

如果你要实现我上面的代码,你需要从中删除你的代码

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

因为您不再需要手动添加 pin。

您能否尝试将其放入您的 View 中以执行加载功能并且不运行任何其他内容。这应该可以确定非洲西部。

Something to notice, if the coordinate is CLLocationCoordinate2D(latitude: 0, longitude: 0), the pin appears right down at Antartica on the date line, which is the bottom right of the map. So if for some reason your coordinate is the default 0,0, your pins might by sitting there.

let pin = MKPointAnnotation()

pin.title = "Null Island"

pin.coordinate = CLLocationCoordinate2DMake(0.000001, 0.000001)

self.map.addAnnotation(pin)

这可能是您的别针所在的位置。

enter image description here

关于arrays - 在 map View 上显示多个注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43747011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com