sementara
sementara

Reputation: 25

Setting map along with user current location for osx

Greeting pros,

As I know we can make a map by using google map api for IOS like the code below here.

import UIKit
import GoogleMaps
/* For cocoa:
   Import Cocoa
   Import MapKit
*/
   class ViewController: NSViewController, CLLocationManagerDelegate {

@IBOutlet var mapView: MKMapView!
var locationManager = CLLocationManager()
var didFindMyLocation = false
var strForCurLatitude = "";
var strForCurLongitude = "";
var currentLocation = locManager.location!


override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.startUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status == .authorizedWhenInUse {
        print("User allowed us to access location")
    }
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Error while get location \(error)")
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location: CLLocation? = locationManager.location
    let coordinate: CLLocationCoordinate2D? = location?.coordinate
    print(coordinate!)
    print(coordinate!.latitude)
    print(coordinate!.longitude)
    strForCurLatitude = "\(coordinate!.latitude)"
    strForCurLongitude = "\(coordinate!.longitude)"
    let camera = GMSCameraPosition.camera(withLatitude: coordinate!.latitude, longitude: coordinate!.longitude, zoom: 15)
    let mapView = GMSMapView.map(withFrame: .zero, camera: camera)
    mapView.isMyLocationEnabled = true
    self.view = mapView

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2DMake(coordinate!.latitude, coordinate!.longitude)
    marker.map = mapView
}


override var representedObject: Any? {
    didSet {
    // Update the view, if already loaded.
    }
}
}

But when I tried the similar method for osx (The difference is that I am using mapkit instead of google map), it says requestWhenInUseAuthorization()' is unavailable. I red this thread How to get user location ? [macOS] but it seems goes without clear resolved whether it is available to get current location for osx or not. So is it inaccessible to get current location for macOS/cocoa app? If it is not, then how to get current location in cocoa app?

I am pretty sure that many xcode programmers like me tried to solve this problem. Any answer you will get big appreciation tho. :)

Upvotes: 1

Views: 295

Answers (1)

Dad
Dad

Reputation: 6468

requestWhenInUseAuthorization is unavailable on macOS.

Here's the source for a NSViewController subclass that checks for location manager and the current location successfully in Xcode 10.1 on macOS 10.13.6:

import Cocoa
import MapKit
import CoreLocation

class MapViewController: NSViewController, CLLocationManagerDelegate {

    @IBOutlet weak var mapView: MKMapView!
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, 
                        didChangeAuthorization status: CLAuthorizationStatus) {
        print("location manager auth status changed to:" )
        switch status {
            case .restricted:
                print("status restricted")
            case .denied:
                print("status denied")

        case .authorized:
                print("status authorized")
                let location = locationManager.location
                print("location: \(String(describing: location))")

            case .authorizedAlways:
                print("status authorized always")
            case .notDetermined:
                print("status not yet determined")
        }


    }

    func locationManager(_ manager: CLLocationManager, 
                            didFailWithError error: Error) {
        print( "location manager failed with error \(error)" )
    }
}

works for me on macOS if you say yes to the "enable location services" prompt when you launch the app the first time.

Note you also need the NSLocationWhenInUseUsageDescription property list entry as indicated in the documentation.

console output is (slightly obfuscated):

location manager auth status changed to: status not yet determined location manager auth status changed to: status authorized location: Optional(<+4X.48,-12X.62632228> +/- 65.00m (speed -1.00 mps / course -1.00) @ 11/3/18, 11:42:48 AM Pacific Daylight Time)

Upvotes: 1

Related Questions