簡體   English   中英

如何在MKMap中獲取Zipcode。 (swift3.0)

[英]How to get the Zipcode in MKMap. (swift3.0)

如何獲取MKMap視圖的zipcode。 (swift 3.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 = ":/?&=;+!@#$()',*" 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()


    }



}

只需按照Google Places API中的指南操作即可

他們會逐步說明如何使用Google Places API來獲取有關您當前或地圖上任何其他位置的詳細信息。 API返回的對象包括郵政編碼等屬性。

希望有所幫助

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM