简体   繁体   English

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

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

How to get the zipcode for MKMap view. 如何获取MKMap视图的zipcode。 (swift 3.0) this is my code can you help me? (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()


    }



}

Just follow the Guides at Google Places API 只需按照Google Places API中的指南操作即可

They explain step by step how to use the Google Places API in order to get detailed information about your current, or any other location on the map. 他们会逐步说明如何使用Google Places API来获取有关您当前或地图上任何其他位置的详细信息。 The object returned by their API includes a property for postcode etc. API返回的对象包括邮政编码等属性。

Hope that helps 希望有所帮助

Your code already uses geocodeAddressString to get an array of placemarks from your address string. 您的代码已使用geocodeAddressString从您的地址字符串中获取地标数组。 You just need to look at the CLPlacemark structure. 您只需要查看CLPlacemark结构。 It has a property addressDictionary that contains key/value pairs that should include a zip code. 它有一个属性addressDictionary ,包含应包含邮政编码的键/值对。 print the contents of the addressDictionary and find the key that contains the zip code. 打印addressDictionary的内容并找到包含邮政编码的密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM