2017-02-15 43 views
1

如何獲取MKMap視圖的郵政編碼。 (swift 3.0) 這是我的代碼可以幫助我嗎?如何獲取MKMap中的郵編。 (swift3.0)

import UIKit 
import MapKit 
import GoogleMaps 
import Foundation 
import CoreLocation 
enum PlaceType: CustomStringConvertible { 
    case all 
    case geocode 
    case address 
    case establishment 
    case regions 
    case cities 
    var description : String { 
     switch self { 
     case .all: return "" 
     case .geocode: return "geocode" 
     case .address: return "address" 
     case .establishment: return "establishment" 
     case .regions: return "regions" 
     case .cities: return "cities" 
     } 
    } 
} 

struct Place { 
    let id: String 
    let description: String 
} 

class MapViewController: UIViewController,MKMapViewDelegate,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate,GMSMapViewDelegate { 


    @IBOutlet var topview: UIView! 
    @IBOutlet var continuebtn: UIButton! 
    @IBOutlet var la3: UILabel! 
    @IBOutlet var la2: UILabel! 
    @IBOutlet var la1: UILabel! 
    @IBOutlet var searchBar: UISearchBar! 
    @IBOutlet var tableview: UITableView! 
    @IBOutlet var mymap: MKMapView! 
    @IBOutlet var backbtn: UIButton! 

    var webservice8:NSString = "" 
    var locationManager = CLLocationManager() 
    let geocorder:CLGeocoder = CLGeocoder() 
    var places = [Place]() 
    var placeType: PlaceType = .all 
    let tapRec = UITapGestureRecognizer() 
    let appDelegate = UIApplication.shared.delegate as! AppDelegate 

    override func viewDidLoad() { 

     super.viewDidLoad() 
     print("hello map1") 
     let str = "\(appDelegate.propertylabel!)" 
     let str2 = str.lowercased() 
     la3.text = "\(str2) located in?" 
     searchBar?.becomeFirstResponder() 
     tableview?.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") 
     self.tableview?.isHidden = true 
     self.searchBar?.delegate = self 
     self.mymap?.delegate = self 
     self.mymap?.mapType = MKMapType.standard 
     var currentLocation = CLLocation() 

     locationManager = CLLocationManager() 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.requestAlwaysAuthorization() 
     locationManager.startUpdatingLocation() 



    if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){ 
      let location = CLLocation(latitude:currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude) //changed!!! 
      print("loc\(location)") 
      let latDelta = 0.05 
      let longDelta = 0.05 
      let currentLocationSpan: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta) 
      let currentLoc: CLLocationCoordinate2D = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude,currentLocation.coordinate.longitude) 
      let currentRegion: MKCoordinateRegion = MKCoordinateRegionMake(currentLoc, currentLocationSpan) 
      self.mymap.setRegion(currentRegion, animated: true) 
      let objectLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude) 
      let objectAnnotation = MKPointAnnotation() 
      objectAnnotation.coordinate = objectLocation 
      self.mymap.addAnnotation(objectAnnotation) 
      addRadiusCircle(location) 
     } 
     else 
     { 
      let alertView:UIAlertView = UIAlertView() 
      alertView.delegate=self 
      alertView.title="Error" 
      alertView.message="Sorry, but we can't determine your current location. You may need to enable Location Services within your device settings." 
      alertView.tag=1111 
      alertView.addButton(withTitle: "OK") 
      alertView.show() 
     } 
     self.continuebtn 
      .isEnabled = false 

    } 


    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
     self.view.endEditing(true) 
    } 

    func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { 
     let newLength = (searchBar.text!).characters.count + text.characters.count - range.length 
     return newLength <= 30 
    } 

    func scrollViewDidScroll(_ scrollView: UIScrollView) { 
     searchBar.resignFirstResponder() 
    } 

    func isValidName(_ fname:NSString) -> Bool { 
     print("Validate Calender: \(fname)") 
     let regx="^[a-z,A-Z]{1,10}$" 
     let emailTest = NSPredicate(format:"SELF MATCHES %@", regx) 
     let result = emailTest.evaluate(with: fname) 
     return result 
    } 

    @IBAction func BackAct(_ sender: Any) { 

      self.dismiss(animated: true, completion: nil) 

    } 


    @IBAction func ContinueAct(_ sender: Any) 

    { 

     geocorder.geocodeAddressString(self.searchBar.text!, completionHandler: {(placemarks, error) -> Void in 
      if let placemark = placemarks?[0] { 
       //    var region : MKCoordinateRegion! 
       let newLocation : CLLocationCoordinate2D = placemark.location!.coordinate 
       let location:CLLocation = CLLocation(latitude: newLocation.latitude, longitude: newLocation.longitude) 
       let annotation:MKPointAnnotation = MKPointAnnotation() 
       annotation.coordinate = newLocation 
       if self.mymap.annotations.count > 0 { 
        self.mymap.removeAnnotations(self.mymap.annotations) 
       } 
       self.mymap.addAnnotation(annotation) 
       var mr:MKMapRect = self.mymap.visibleMapRect 
       let pt:MKMapPoint = MKMapPointForCoordinate(annotation.coordinate) 
       mr.origin.x = pt.x - mr.size.width * 0.5 
       mr.origin.y = pt.y - mr.size.height * 0.5 
       self.mymap.setVisibleMapRect(mr, animated: true) 
       self.mymap.autoresizingMask = self.view.autoresizingMask 


       let latitude: NSNumber = 9.10 
       let longitude:NSNumber = 78.10 
       self.appDelegate.lat = "\(latitude)" as NSString! 
       self.appDelegate.long = "\(longitude)" as NSString! 
       print("Latitude value:\(self.appDelegate.lat)") 
       print("Longitude value:\(self.appDelegate.long)") 
       let overlays = self.mymap.overlays 
       self.mymap.removeOverlays(overlays) 
       self.addRadiusCircle(location) 


       var listadrs:NSString = self.searchBar.text! as NSString 
       self.mymap.removeAnnotations(self.mymap.annotations) 
       if self.appDelegate.hostproperty == "map" 
       { 
        print ("Success") 
        var listadrs:NSString = self.searchBar.text! as NSString 
        if(listadrs == "") 
        { 
         UserDefaults.standard.set(listadrs, forKey:"listadrs") 
         UserDefaults.standard.synchronize() 
         let myOutput2: AnyObject? = UserDefaults.standard.object(forKey: "listadrs") as AnyObject? 
         print("ass\(myOutput2)") 
         listadrs="xxx" 

        } 
        else 
        { 
         listadrs = self.searchBar.text! as NSString 
         UserDefaults.standard.set(listadrs, forKey:"listadrs") 
         UserDefaults.standard.synchronize() 
         let myOutput2: AnyObject? = UserDefaults.standard.object(forKey: "listadrs") as AnyObject? 
         print("sss\(myOutput2!)") 

         let appDelegate = UIApplication.shared.delegate as! AppDelegate 
         appDelegate.searchplace=("\(self.searchBar.text)") 
         let secondViewController1 = self.storyboard!.instantiateViewController(withIdentifier: "hostboat") 
         self.present(secondViewController1, animated: true, completion: nil) 
        } 
        UIGraphicsBeginImageContextWithOptions(self.mymap.bounds.size, false, UIScreen.main.scale) 
        self.mymap.layer.render(in: UIGraphicsGetCurrentContext()!) 
        self.appDelegate.mapimg = UIGraphicsGetImageFromCurrentImageContext() 
        UIGraphicsEndImageContext() 
       } 
       else if(listadrs == "") 
       { 
        print("Dual") 
        UserDefaults.standard.set(listadrs, forKey:"listadrs") 
        UserDefaults.standard.synchronize() 
        let myOutput2: AnyObject? = UserDefaults.standard.object(forKey: "listadrs") as AnyObject? 
        print("ad\(myOutput2)") 
        listadrs="xxx" 
        let secondViewController1 = self.storyboard!.instantiateViewController(withIdentifier: "hostboat") 
        self.present(secondViewController1, animated: true, completion: nil) 
       } 
       else 
       { 
        listadrs = self.searchBar.text! as NSString 
        UserDefaults.standard.set(listadrs, forKey:"listadrs") 
        UserDefaults.standard.synchronize() 
        let myOutput2: AnyObject? = UserDefaults.standard.object(forKey: "listadrs") as AnyObject? 
        print("adddd\(myOutput2)") 
        let appDelegate = UIApplication.shared.delegate as! AppDelegate 
        appDelegate.searchplace=("\(self.searchBar.text)") 
        let secondViewController1 = self.storyboard!.instantiateViewController(withIdentifier: "hostboat") 
        self.present(secondViewController1, animated: true, completion: nil) 
       } 
       UIGraphicsBeginImageContextWithOptions(self.mymap.bounds.size, false, UIScreen.main.scale) 
       self.mymap.layer.render(in: UIGraphicsGetCurrentContext()!) 
       self.appDelegate.mapimg = UIGraphicsGetImageFromCurrentImageContext() 
       UIGraphicsEndImageContext() 
      } 
     }) 
    } 





    func addRadiusCircle(_ location: CLLocation){ 

     self.mymap.delegate = self 
     let circle = MKCircle(center: location.coordinate, radius: 700 as CLLocationDistance) 
     self.mymap.add(circle) 
     self.continuebtn.isEnabled = true 
    } 



    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer 
    { 
     let circle = MKCircleRenderer(overlay: overlay) 
     circle.strokeColor = UIColor.white 
     circle.fillColor = UIColor(red: 0/255, green: 204/255, blue: 204/255, alpha: 0.4) 
     circle.lineWidth = 5 
     return circle 

    } 

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 
     if annotation is MKPointAnnotation { 
      let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin") 
      pinAnnotationView.pinColor = .red 
      pinAnnotationView.isDraggable = true 
      pinAnnotationView.canShowCallout = true 
      pinAnnotationView.animatesDrop = true 
      return pinAnnotationView 
     } 

     return nil 
    } 



    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) 
    { 
     switch (newState) 
     { 
     case .starting: 
      view.dragState = .dragging 
     case .ending, .canceling: 
      view.dragState = .none 
     default: break 
     } 
    } 

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { 

     geocorder.geocodeAddressString(self.searchBar.text!, completionHandler: {(placemarks , error) -> Void in 
      if let placemark = placemarks?[0]{ 

       let newLocation : CLLocationCoordinate2D = placemark.location!.coordinate 
       let location:CLLocation = CLLocation(latitude: newLocation.latitude, longitude: newLocation.longitude) 
       let annotation:MKPointAnnotation = MKPointAnnotation() 
       annotation.coordinate = newLocation 



       self.mymap?.addAnnotation(annotation) 
       var mr:MKMapRect = self.mymap.visibleMapRect 
       let pt:MKMapPoint = MKMapPointForCoordinate(annotation.coordinate) 
       mr.origin.x = pt.x - mr.size.width * 0.5 
       mr.origin.y = pt.y - mr.size.height * 0.5 
       self.mymap.setVisibleMapRect(mr, animated: true) 
       self.mymap.autoresizingMask = self.view.autoresizingMask 
       self.addRadiusCircle(location) 
      } 
     }) 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return places.count 
    } 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 
     let place = self.places[(indexPath as NSIndexPath).row] 
     cell.textLabel!.text = place.description 
     cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator 
     return cell 
    } 
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 


     self.searchBar.resignFirstResponder() 
     self.searchBar.text = self.places[(indexPath as NSIndexPath).row].description 
     tableView.isHidden = true 
     self.mymap.isHidden = false 

     geocorder.geocodeAddressString(self.searchBar.text!, completionHandler: {(placemarks, error) -> Void in 
      if let placemark = placemarks?[0] { 

       let newLocation : CLLocationCoordinate2D = placemark.location!.coordinate 
       let location:CLLocation = CLLocation(latitude: newLocation.latitude, longitude: newLocation.longitude) 
       let annotation:MKPointAnnotation = MKPointAnnotation() 
       annotation.coordinate = newLocation 
       if self.mymap.annotations.count > 0 { 
        self.mymap.removeAnnotations(self.mymap.annotations) 
       } 
       self.mymap.addAnnotation(annotation) 
       var mr:MKMapRect = self.mymap.visibleMapRect 
       let pt:MKMapPoint = MKMapPointForCoordinate(annotation.coordinate) 
       mr.origin.x = pt.x - mr.size.width * 0.5 
       mr.origin.y = pt.y - mr.size.height * 0.5 
       self.mymap.setVisibleMapRect(mr, animated: true) 
       self.mymap.autoresizingMask = self.view.autoresizingMask 


       let latitude: NSNumber = 9.10 
       let longitude:NSNumber = 78.10 
       self.appDelegate.lat = "\(latitude)" as NSString! 
       self.appDelegate.long = "\(longitude)" as NSString! 
       print("Latitude value:\(self.appDelegate.lat)") 
       print("Longitude value:\(self.appDelegate.long)") 
       let overlays = self.mymap.overlays 
       self.mymap.removeOverlays(overlays) 
       self.addRadiusCircle(location) 
      } 
     }) 
    } 
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { 
     if (searchText == "") { 
      self.places = [] 
      self.tableview.isHidden = true 
     } else { 
      self.tableview.isHidden = false 
      self.mymap.isHidden = true 
      getPlaces(searchString: searchText) 
     } 
    } 

    func getPlaces(searchString: String) { 
     var request = requestForSearch(searchString) 

     var session = URLSession.shared 
     var task = session.dataTask(with: request) { data, response, error in 
      self.handleResponse(data, response: response as? HTTPURLResponse, error: error as NSError!) 

     } 

     task.resume() 
    } 

    func handleResponse(_ data: Data!, response: HTTPURLResponse!, error: NSError!) { 
     if let error = error { 
      print("GooglePlacesAutocomplete Error: \(error.localizedDescription)") 
      return 
     } 
     if response == nil { 
      print("GooglePlacesAutocomplete Error: No response from API") 
      return 
     } 
     if response.statusCode != 200 { 
      print("GooglePlacesAutocomplete Error: Invalid status code \(response.statusCode) from API") 
      return 
     } 
     let serializationError: NSError? = error 
     let json: NSDictionary = (try! JSONSerialization.jsonObject(
      with: data, 
      options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary 
     if let error = serializationError { 
      print("GooglePlacesAutocomplete Error: \(error.localizedDescription)") 
      return 
     } 
     DispatchQueue.main.async(execute: { 
      UIApplication.shared.isNetworkActivityIndicatorVisible = false 
      if let predictions = json["predictions"] as? Array<AnyObject> { 
       self.places = predictions.map { (prediction: AnyObject) -> Place in 
        return Place(
         id: prediction["id"] as! String, 
         description: prediction["description"] as! String 
        ) 
       } 
       self.tableview.reloadData() 
       self.tableview.isHidden = false 
      } 
     }) 
    } 

    func requestForSearch(_ searchString: String) -> URLRequest { 

     let searchString = searchString.replacingOccurrences(of: "Optional", with: "") 
     let place_type = placeType.description.replacingOccurrences(of: "Optional", with: "") 
     let key_google = google_place_key.replacingOccurrences(of: "Optional", with: "") 

     print("print1\(searchString)") 
     print("print2\(place_type)") 
     print("print3\(key_google)") 

     let params = [ 
      "input": searchString, 

      "key": google_place_key 
     ] 

     print("Place url -> https://maps.googleapis.com/maps/api/place/autocomplete/json?\(query(params as [String : Any] as [String : AnyObject]))") 

     var url1 = "https://maps.googleapis.com/maps/api/place/autocomplete/json?\(query(params as [String : Any] as [String : AnyObject]))" 
     print("Place->\(url1)") 

     let url2 = url1.replacingOccurrences(of: "Optional", with: "") 
     let url3 = url2.replacingOccurrences(of: "%28", with: "") 
     let url4 = url3.replacingOccurrences(of: "%29", with: "") 

     return NSMutableURLRequest(
      url: URL(string: url4)! 
      ) as URLRequest 


    } 
    func query(_ parameters: [String: AnyObject]) -> String { 
     var components: [(String, String)] = [] 
     for key in Array(parameters.keys).sorted(by: <) { 
      let value: AnyObject! = parameters[key] 
      components += [(escape(key), escape("\(value!)"))] 
     } 
     return (components.map{"\($0)=\($1)"} as [String]).joined(separator: "&") 
    } 
    func escape(_ string: String) -> String { 
     let legalURLCharactersToBeEscaped: CFString = ":/?&=;[email protected]#$()',*" as CFString 
     return CFURLCreateStringByAddingPercentEscapes(nil, string as CFString!, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String 
    } 

    override func viewWillAppear (_ animated: Bool){ 
     super.viewWillAppear(animated); 



    } 


    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 


    } 



} 

回答

0

只需按照指示在Google Places API

他們一步如何使用谷歌API的地方,以獲得有關當前,或在地圖上的任何其他位置的詳細信息解釋一步。通過他們的API返回的對象包括郵政編碼等

希望幫助

+0

OP已經有使用Apple地理編碼獲取地標的代碼。他們需要的數據已經在內存中。沒有理由切換到Google地方信息。 –

0

你的代碼已經使用geocodeAddressString從您的地址字符串得到標數組的屬性。你只需要看看CLPlacemark結構。它有一個屬性addressDictionary,其中包含應包含郵政編碼的鍵/值對。打印addressDictionary的內容並找到包含郵政編碼的密鑰。

+0

海鄧肯我得到地址,城市和國家..我需要Zipcode。我怎樣才能得到。你能幫助我嗎?我沒有任何想法。你能用例子來解釋嗎? – Mounica