2017-10-15 5 views
0

문자열 배열을 사용하여지도에 핀을 추가하려고합니다. 그러나 그것은 단지 하나의 핀만을 보여 주며 두번째 핀은지도에 표시하지 않습니다. 당신이 할당하기 때문에 당신은 하나의 핀 돌아여러 위치에 핀을 놓는 방법 mapkit swift

@IBAction func findNewLocation() 
{ 
    var someStrs = [String]() 
    someStrs.append("6 silver maple court brampton") 
    someStrs.append("shoppers world brampton") 
    getDirections(enterdLocations: someStrs) 
} 

답변

1

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) 
    } 
    }) 
    } 

} 

내 호출 기능을 하나의 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) ...으로 모두 표시 할 수 있습니다. 필요가 없다면 묵으십시오.

+0

고마워요. 배열에있는 핀들 사이의 경로를 그려 줄 수 있습니까? –

+0

다음을 살펴보십시오. https://www.hackingwithswift.com/example-code/location/how-to-find-directions-using-mkmapview-and-mkdirectionsrequest – Ladislav

관련 문제