如何使用mapview获取纬度和经度使用swift在IOS中进行手势触摸

时间:2016-11-08 06:59:44

标签: ios swift mkmapview swift3

我叫Tony dhand。我是IOS开发的新手。目前,我正在Mkmapview工作。现在我遇到了一些问题。

我的任务是显示用户当前位置(我已完成此操作)。接下来是当用户滚动地图并长按在该地点添加标记并获得纬度经度时。并获得两个位置之间的距离。这是我的代码:

import UIKit
import MapKit

import CoreLocation

class ViewController: UIViewController ,MKMapViewDelegate , CLLocationManagerDelegate{

    let corelocationmanager = CLLocationManager()
    private var mapChangedFromUserInteraction = false

    @IBOutlet weak var mapview: MKMapView!
    override func viewDidLoad() {
            super.viewDidLoad()

        if (CLLocationManager.locationServicesEnabled()){
            self.corelocationmanager.requestAlwaysAuthorization();         self.corelocationmanager.delegate = self
            self.corelocationmanager.desiredAccuracy = kCLLocationAccuracyBest
            self.corelocationmanager.requestWhenInUseAuthorization()
            self.corelocationmanager.startUpdatingLocation()
            self.corelocationmanager.distanceFilter = kCLDistanceFilterNone;
            let coord = CLLocationCoordinate2DMake(37, -122)
            let span = MKCoordinateSpanMake(1, 1)
            mapview.region = MKCoordinateRegionMake(coord, span)
            self.view.addSubview(mapview)


            // self.mapview.sh; owsUserLocation = true

        }else{
            //   location service is disable
        }
        mapview.delegate = self;
        mapview.isUserInteractionEnabled = true;


        let theSpan:MKCoordinateSpan = MKCoordinateSpanMake(0.01 , 0.01)
        let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 45.612125, longitude: 22.948280)
        let theRegion:MKCoordinateRegion = MKCoordinateRegionMake(location, theSpan)

        mapview.setRegion(theRegion, animated: true)

        var anotation = MKPointAnnotation()
        anotation.coordinate = location
        anotation.title = "The Location"
        anotation.subtitle = "This is the location !!!"
        mapview.addAnnotation(anotation)

        let longPress = UILongPressGestureRecognizer(target: self, action: "action:")
        longPress.minimumPressDuration = 1.0
        // mapview.addGestureRecognizer(longPress)

        setCenterForMap()


    }

    func setCenterForMap() {
        var mapRect: MKMapRect = MKMapRectNull
        for loc in mapview.annotations {
            let point: MKMapPoint = MKMapPointForCoordinate(loc.coordinate)
            print( "location is : \(loc.coordinate)");
            mapRect = MKMapRectUnion(mapRect, MKMapRectMake(point.x,point.y,0,0))
        }
        if (corelocationmanager.location != nil) {
            let point: MKMapPoint = MKMapPointForCoordinate(corelocationmanager.location!.coordinate)
            print( "Cur location is : \(corelocationmanager.location!.coordinate)");
            mapRect = MKMapRectUnion(mapRect, MKMapRectMake(point.x,point.y,0,0))
        }

        mapview.setVisibleMapRect(mapRect, edgePadding: UIEdgeInsetsMake(40.0, 40.0, 40.0, 40.0), animated: true)

    }

    func action(gestureRecognizer:UIGestureRecognizer) {

        var touchPoint = gestureRecognizer.location(in: self.mapview)
        var newCoord:CLLocationCoordinate2D = mapview.convert(touchPoint, toCoordinateFrom: self.mapview)

        var newAnotation = MKPointAnnotation()
        newAnotation.coordinate = newCoord
        newAnotation.title = "New Location"
        newAnotation.subtitle = "New Subtitle"
        mapview.addAnnotation(newAnotation)

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations.last
        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: (location?.coordinate.longitude)!)

        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))

        self.mapview.setRegion(region, animated: true)
        self.corelocationmanager.stopUpdatingLocation()

        //   let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        //   print("locations = \(locValue.latitude) \(locValue.longitude)")





        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
            if (error != nil) {
                print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
                return
            }

            if (placemarks?.count)! > 0 {
                let pm = (placemarks?[0])! as CLPlacemark
                self.displayLocationInfo(placemark: pm)
            } else {
                print("Problem with the data received from geocoder")
            }
        })


    }



    func coordinateRegionForCoordinates(coords: [CLLocationCoordinate2D]) -> MKCoordinateRegion {
        var rect: MKMapRect = MKMapRectNull
        for coord in coords {
            let point: MKMapPoint = MKMapPointForCoordinate(coord)
            rect = MKMapRectUnion(rect, MKMapRectMake(point.x, point.y, 0, 0))
        }
        return MKCoordinateRegionForMapRect(rect)
    }        

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error:", error.localizedDescription)
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
            if (error != nil) {
                print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
                return
            }

            if (placemarks?.count)! > 0 {
                let pm = (placemarks?[1])! as CLPlacemark
                self.displayLocationInfo(placemark: pm)
            } else {
                print("Problem with the data received from geocoder")
            }
        })
    }

    func displayLocationInfo(placemark: CLPlacemark) {
        if placemark != nil {
            //stop updating location to save battery life
            corelocationmanager.stopUpdatingLocation()
            print(placemark.locality!)
            print(placemark.postalCode!)
            print(placemark.administrativeArea!)

        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
        let view = self.mapview.subviews[0]
        //  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 ) {

                    print("ok")
                    return true
                }
            }
        }
        return false
    }

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

            print("dhand")
        }
    }

}

请提前帮助

0 个答案:

没有答案