使用地图图钉segue传递自定义数据

凯尔谢克

我一直很难弄清楚如何将映射图钉中的自定义变量传递给Swift中的另一个视图控制器。我知道在addAnnotation时可以传递坐标,标题和字幕。我想尝试传递一个自定义变量,但将其隐藏。有这样的事吗?在下面,我得到了用户的位置,进行了映射,在附近的几个位置添加了带有注释的大头针,这些注释进入了另一个视图控制器,并且仅传递了标题和副标题。任何见解都将不胜感激。

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

var mappedCity = String()
var mappedState = String()

var manager = CLLocationManager()
var annotation:MKAnnotation!
var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
var selectedAnnotation: MKPointAnnotation!

private var mapChangedFromUserInteraction = false

@IBOutlet var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.mapView.delegate = self
    self.navigationItem.titleView = searchController.searchBar
    self.definesPresentationContext = true


    if CLLocationManager.locationServicesEnabled(){
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()

   }       

}


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

    let userLocation:CLLocation = locations[0]
    let latitude = userLocation.coordinate.latitude
    let longitude = userLocation.coordinate.longitude

    let latDelta:CLLocationDegrees = 0.05
    let lonDelta:CLLocationDegrees = 0.05
    let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
    let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
    let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)

    self.mapView.setRegion(region, animated: true)
    self.mapView.showsUserLocation = true

    CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) in

        if (error != nil){

            print(error)

        }else {

            if let p = placemarks?[0]{

                let locality = p.locality ?? ""
                let administrativeArea = p.administrativeArea ?? ""


                self.mappedCity = String(locality)
                self.mappedState = String(administrativeArea)

                self.parseJSON("\(locality)", state: "\(administrativeArea)")
            }

        }



    }
 self.manager.stopUpdatingLocation()
}


func parseJSON(city: String, state: String){
    let passedCity = city
    let passedState = state
    let escapedCity = passedCity.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    let escapedState = passedState.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

    let url = NSURL(string:"http://www.API.com/api.php?city=\(escapedCity)&stateAbv=\(escapedState)")!

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithURL(url) { (items, response, error) -> Void in

        if error != nil {

            print(error)


        }else {


            if let items = items {


                do {
                    let jsonResult = try NSJSONSerialization.JSONObjectWithData(items, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

                    if jsonResult.count > 0 {

                        if let datas = jsonResult["data"] as? NSArray{

                            for data in datas{

                                if let title = data["title"] as? String {

                                    if let street = data["street"] as? String {

                                        if let city =  data["city"] as? String {

                                            if let stateAbv =  data["stateAbv"] as? String {

                                                if let zip =  data["zip"] as? String {

                                                    self.geoAddress("\(title)", street: "\(street)", city: "\(city)", state: "\(stateAbv)", zip: "\(zip)")


                                                }
                                            }
                                        }

                                    }

                                }

                            }
                        }

                    }
                } catch{}


            }


        }

    }

    task.resume()

}


func geoAddress(title: String, street: String, city: String, state: String, zip: String){
    let storeName = "\(title)"
    let location = "\(street) \(city) \(state) \(zip)"
    let geocoder = CLGeocoder();
    geocoder.geocodeAddressString(location, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
        if (error != nil) {
            print("Error \(error!)")
        } else if let placemark = placemarks?[0] {

            let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate

            let pointAnnotation:MKPointAnnotation = MKPointAnnotation()
            pointAnnotation.coordinate = coordinates
            pointAnnotation.title = storeName
            pointAnnotation.subtitle = location

            self.mapView.addAnnotation(pointAnnotation)

        }
    })
}


private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
    let view: UIView = self.mapView.subviews[0] as UIView
    //  Look through gesture recognizers to determine whether this region change is from user interaction
    if let gestureRecognizers = view.gestureRecognizers {
        for recognizer in gestureRecognizers {
            if( recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Ended ) {
                return true
            }
        }
    }
    return false
}

func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
    mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction()
    if (mapChangedFromUserInteraction) {
        // user changed map region

    }
}

func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
    if (mapChangedFromUserInteraction) {
        // user changed map region
        let center = mapView.centerCoordinate

        let mapLatitude = center.latitude
        let mapLongitude = center.longitude


        let locationmove = CLLocation(latitude: mapLatitude, longitude: mapLongitude)
        CLGeocoder().reverseGeocodeLocation(locationmove) { (placemarks, error) in

            if (error != nil){

                print(error)

            }else {

                if let p = placemarks?[0]{

                    let locality = p.locality ?? ""
                    let administrativeArea = p.administrativeArea ?? ""


                     self.mappedCity = String(locality)
                     self.mappedState = String(administrativeArea)
                     self.parseJSON("\(locality)", state: "\(administrativeArea)")
                }

            } 

        }
    }
}



func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }

    let reuseId = "pin"
    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
    if pinView == nil {
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView?.animatesDrop = false
        pinView?.canShowCallout = true
        pinView?.draggable = true
        pinView?.pinTintColor = UIColor.greenColor()
        let rightButton: AnyObject! = UIButton(type: UIButtonType.DetailDisclosure)
        pinView?.rightCalloutAccessoryView = rightButton as? UIView
    }
    else {
        pinView?.annotation = annotation
    }

    return pinView
}

func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    if control == view.rightCalloutAccessoryView {
        selectedAnnotation = view.annotation as? MKPointAnnotation
        performSegueWithIdentifier("Details", sender: self)
    }
}

func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
    if newState == MKAnnotationViewDragState.Ending {
        let droppedAt = view.annotation?.coordinate
        print(droppedAt)
    }
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

   if (segue.identifier == "Details"){
   let myDetails = segue.destinationViewController as! DetailViewController
     myDetails.mytitle = selectedAnnotation.title
     myDetails.mysubtitle = selectedAnnotation.subtitle

    }

}


func updateSearchResultsForSearchController(searchController: UISearchController) {


}


}
苏里亚·苏邦蒂兰(Surya Subenthiran)

Subclass“ MKPointAnnotation”类,然后将custom property添加到其中。

class MyAnnotation : MKPointAnnotation {
    var customProperty : String?
}

并且您可以使用MyAnnotation代替MKPointAnnotation像下面

 let pointAnnotation:MyAnnotation = MyAnnotation()
 pointAnnotation.coordinate = coordinates
 pointAnnotation.title = storeName
 pointAnnotation.subtitle = location
 pointAnnotation.customProperty = "your value"
 self.mapView.addAnnotation(pointAnnotation)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

通过自定义segue传递数据

来自分类Dev

谷歌地图自定义图钉

来自分类Dev

使用 javascript 将自定义位置图钉添加到样式化的 Google 地图

来自分类Dev

自定义地图图钉图像Objective-C

来自分类Dev

如何在Apple Watch的地图视图中添加自定义地图图钉?

来自分类Dev

MKMapView自定义图钉图像在放大/缩小地图时会失去准确性

来自分类Dev

如何使地图图钉(自定义)图像出现在中心点

来自分类Dev

Bing地图上带有Angular指令内容的自定义图钉

来自分类Dev

使用Bundle传递自定义数据列表

来自分类Dev

不会添加自定义图钉图像

来自分类Dev

不会添加自定义图钉图像

来自分类Dev

使用JAXB解组自定义地图

来自分类Dev

使用自定义值验证地图

来自分类Dev

Google地图:使用自定义按钮

来自分类Dev

使用JAXB解组自定义地图

来自分类Dev

用地图值替换自定义对象列表中的值

来自分类Dev

C#Windows Phone-具有相关数据的自定义图钉

来自分类Dev

自定义关系Segue

来自分类Dev

是否可以使用地图v2的默认ZoomControls放大/缩小自定义的ZoomLevel(例如0.5x)?

来自分类Dev

如何使用Google Cluster Manager自定义默认图钉标记?

来自分类Dev

如何使用图像标记创建自定义可绘制图钉

来自分类Dev

使用自定义数据方法的自定义QStandardItemModel

来自分类Dev

Highcharts在React TypeScript中用于地图的自定义数据?

来自分类Dev

使用segue传递数据

来自分类Dev

如何将自定义地图和自定义数据添加到Highmaps?

来自分类Dev

无法使用地图获取 useState 数据

来自分类Dev

添加自定义Google Map标记/图钉(颜色)

来自分类Dev

使用Laravel使用地理区域进行自定义SQL查询

来自分类Dev

快速将自定义注释图钉图像更新为标准注释图钉

Related 相关文章

  1. 1

    通过自定义segue传递数据

  2. 2

    谷歌地图自定义图钉

  3. 3

    使用 javascript 将自定义位置图钉添加到样式化的 Google 地图

  4. 4

    自定义地图图钉图像Objective-C

  5. 5

    如何在Apple Watch的地图视图中添加自定义地图图钉?

  6. 6

    MKMapView自定义图钉图像在放大/缩小地图时会失去准确性

  7. 7

    如何使地图图钉(自定义)图像出现在中心点

  8. 8

    Bing地图上带有Angular指令内容的自定义图钉

  9. 9

    使用Bundle传递自定义数据列表

  10. 10

    不会添加自定义图钉图像

  11. 11

    不会添加自定义图钉图像

  12. 12

    使用JAXB解组自定义地图

  13. 13

    使用自定义值验证地图

  14. 14

    Google地图:使用自定义按钮

  15. 15

    使用JAXB解组自定义地图

  16. 16

    用地图值替换自定义对象列表中的值

  17. 17

    C#Windows Phone-具有相关数据的自定义图钉

  18. 18

    自定义关系Segue

  19. 19

    是否可以使用地图v2的默认ZoomControls放大/缩小自定义的ZoomLevel(例如0.5x)?

  20. 20

    如何使用Google Cluster Manager自定义默认图钉标记?

  21. 21

    如何使用图像标记创建自定义可绘制图钉

  22. 22

    使用自定义数据方法的自定义QStandardItemModel

  23. 23

    Highcharts在React TypeScript中用于地图的自定义数据?

  24. 24

    使用segue传递数据

  25. 25

    如何将自定义地图和自定义数据添加到Highmaps?

  26. 26

    无法使用地图获取 useState 数据

  27. 27

    添加自定义Google Map标记/图钉(颜色)

  28. 28

    使用Laravel使用地理区域进行自定义SQL查询

  29. 29

    快速将自定义注释图钉图像更新为标准注释图钉

热门标签

归档