如何在多个位置放置引脚mapkit swift
问题描述:
我正尝试使用字符串数组将引脚添加到映射。但它只显示一个引脚不显示地图上的第二个引脚。如何在多个位置放置引脚mapkit swift
func getDirections(enterdLocations:[String]) {
let geocoder = CLGeocoder()
// array has the address strings
for (index, item) in enterdLocations.enumerated() {
geocoder.geocodeAddressString(item, completionHandler: {(placemarks, error) -> Void in
if((error) != nil){
print("Error", error)
}
if let placemark = placemarks?.first {
let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
let dropPin = MKPointAnnotation()
dropPin.coordinate = coordinates
dropPin.title = item
self.myMapView.addAnnotation(dropPin)
self.myMapView.selectAnnotation(dropPin, animated: true)
}
})
}
}
和我通话功能
@IBAction func findNewLocation()
{
var someStrs = [String]()
someStrs.append("6 silver maple court brampton")
someStrs.append("shoppers world brampton")
getDirections(enterdLocations: someStrs)
}
答
你只有一个针回来,因为你仅配置了一个let geocoder = CLGeocoder()
所以只是动议到for
循环,它会像这样:
func getDirections(enterdLocations:[String]) {
// array has the address strings
var locations = [MKPointAnnotation]()
for item in enterdLocations {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(item, completionHandler: {(placemarks, error) -> Void in
if((error) != nil){
print("Error", error)
}
if let placemark = placemarks?.first {
let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
let dropPin = MKPointAnnotation()
dropPin.coordinate = coordinates
dropPin.title = item
self.myMapView.addAnnotation(dropPin)
self.myMapView.selectAnnotation(dropPin, animated: true)
locations.append(dropPin)
//add this if you want to show them all
self.myMapView.showAnnotations(locations, animated: true)
}
})
}
}
我添加了位置var locations
数组,它将保存所有注释,以便您可以使用self.myMapView.showAnnotations(locations, animated: true)
来显示所有注释...所以r如果不需要,请留意
谢谢。你能帮我画出阵列中的引脚之间的路线吗? –
看看类似这样的内容:https://www.hackingwithswift.com/example-code/location/how-to-find-directions-using-mkmapview-and-mkdirectionsrequest – Ladislav