How can I show my current location in maps in Xcode? - ios

I watched a few lessons on Youtube and now tried to get hands-on experience. I am pursuing a little project which involves a tabbed app where I tried on the first page to create a map with a button showing the current location. Pretty basic actually. But somehow it just doesn’t work and I don’t know what’s the issue. Someone from CodewithChris told me this “I would suggest breaking up your app into smaller components and making sure each one works before going on to the next. Try outputting your location first before plotting it on a map etc so you can localize bugs easier.” I just don’t understand what she means by smaller components. I really appreciate all the help I can get. Below is the code as good as possible. Thanks in advance for your help.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet var textFieldForAddress: UITextField!
#IBOutlet var getDirectionsButton: UIButton!
#IBOutlet var map: MKMapView!
var locationManger = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManger.delegate = self
locationManger.desiredAccuracy = kCLLocationAccuracyBest
locationManger.requestAlwaysAuthorization()
locationManger.requestWhenInUseAuthorization()
locationManger.startUpdatingLocation()
map.delegate = self
}
#IBAction func getDirectionsTapped(_ sender: Any) {
getAddress()
}
func getAddress() {
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(textFieldForAddress.text!) { (placemarks, error) in
guard let placemarks = placemarks, let location = placemarks.first?.location
else {
print("No Location Found")
return
}
print(location)
self.mapThis(destinationCord: location.coordinate)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
}
func mapThis(destinationCord : CLLocationCoordinate2D) {
let souceCordinate = (locationManger.location?.coordinate)!
let soucePlaceMark = MKPlacemark(coordinate: souceCordinate)
let destPlaceMark = MKPlacemark(coordinate: destinationCord)
let sourceItem = MKMapItem(placemark: soucePlaceMark)
let destItem = MKMapItem(placemark: destPlaceMark)
let destinationRequest = MKDirections.Request()
destinationRequest.source = sourceItem
destinationRequest.destination = destItem
destinationRequest.transportType = .automobile
destinationRequest.requestsAlternateRoutes = true
let directions = MKDirections(request: destinationRequest)
directions.calculate { (response, error) in
guard let response = response else {
if let error = error {
print("Something is wrong :(")
}
return
}
let route = response.routes[0]
self.map.addOverlay(route.polyline)
self.map.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let render = MKPolylineRenderer(overlay: overlay as! MKPolyline)
render.strokeColor = .blue
return render
}
}

If you want to show the user location and have the map track it, you need to set two properties on the map view - showsUserLocation and userTrackingMode. In order for the map to have access to the user location you must receive whenInUse authorisation from the user, using CLocationManager.
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet var textFieldForAddress: UITextField!
#IBOutlet var getDirectionsButton: UIButton!
#IBOutlet var map: MKMapView!
var locationManger = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManger.requestWhenInUseAuthorization()
map.showsUserLocation = true
map.userTrackingMode = .follow
}
If you are running on the simulator then you need to simulate a location using the Debug menu in the simulator.

Okay, this information is surprising hard to find (just getting your own location!) — even after watching tutorials I had a hard time. But basically what you're missing is mapView.showsUserLocation = true
Here's the full code, if you need it...
import UIKit
import CoreLocation
import MapKit
class RadiusMapLocationViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
let coordinate = CLLocationCoordinate2DMake(33.97823607957177, -118.43823725357653)
var locationManager : CLLocationManager = CLLocationManager()
// Authorize use of location
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
mapView.showsUserLocation = (status == .authorizedAlways)
}
// Entering region
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
showAlert(withTitle: "You've entered \(region.identifier)", message: "Happy hopping!")
}
// Exiting region
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
showAlert(withTitle: "You've exited \(region.identifier)", message: "")
}
// Creating region and notifying when exit / enter
func region(with geotification: Geotification) -> CLCircularRegion {
let region = CLCircularRegion(center: geotification.coordinate,
radius: geotification.radius,
identifier: geotification.identifier)
region.notifyOnEntry = (geotification.eventType == .onEntry)
region.notifyOnExit = !region.notifyOnEntry
return region
}
// Monitoring region, if not "error"
func startMonitoring(geotification: Geotification) {
if !CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
showAlert(withTitle:"Error", message: "Geofencing is not supported on this device!")
return
}
}
func stopMonitoring(geotification: Geotification) {
for region in locationManager.monitoredRegions {
guard let circularRegion = region as? CLCircularRegion,
circularRegion.identifier == geotification.identifier else { continue }
locationManager.stopMonitoring(for: circularRegion)
}
}
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.userTrackingMode = .follow
mapView.showsUserLocation = true
// Region of coordinate
mapView.region = MKCoordinateRegion(center: coordinate, latitudinalMeters: 800, longitudinalMeters: 800)
mapView.region = MKCoordinateRegion(center: coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000)
let title = "Marina Bar Hop"
let restaurantAnnotation = MKPointAnnotation()
restaurantAnnotation.coordinate = coordinate
restaurantAnnotation.title = title
mapView.addAnnotation(restaurantAnnotation)
let regionRadius = 300.0
let circle = MKCircle(center: coordinate, radius: regionRadius)
mapView.addOverlay(circle)
self.locationManager.requestAlwaysAuthorization()
self.locationManager.delegate = self as? CLLocationManagerDelegate
//Zoom to user location
if let userLocation = locationManager.location?.coordinate {
let viewRegion = MKCoordinateRegion(center: userLocation, latitudinalMeters: 200, longitudinalMeters: 200)
mapView.setRegion(viewRegion, animated: false)
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let circleRenderer = MKCircleRenderer(overlay: overlay)
circleRenderer.strokeColor = UIColor.red
circleRenderer.lineWidth = 1.0
return circleRenderer
}
}
I have a few additional features on here if you need them. And it sounds like maybe you want to add a pin on the user's current location? It's included in this code too. I hope this helps! :)

Related

MKLocalSearch (search.start)always goes in the error flow. (SWIFT)

I've been trying to learn swift for the past few days and just started my own project! As part of the project I wanted to show nearby cocktail bars on a map, I was able to find some nice info online and have been able to show a map with my current location. I also found info on how to find nearby locations: https://developer.apple.com/documentation/mapkit/mklocalsearch/request
Unfortunately this last one never seems to work, it just goes out of the function and does not return any locations, could anyone help me further? Below is the code of my viewcontroller with the function getNearbyLandmarks which doesn't work as intended.
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet var mapView: MKMapView!
let manager = CLLocationManager()
private var landmarks: [Landmark] = [Landmark]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.delegate = self
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
manager.stopUpdatingLocation()
render(location)
}
}
func render(_ location: CLLocation){
let coordinate = CLLocationCoordinate2D(latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude)
let span = MKCoordinateSpan(latitudeDelta: 0.01,
longitudeDelta: 0.01)
let region = MKCoordinateRegion(center: coordinate,
span: span)
mapView.delegate = self
mapView.setRegion(region,
animated: true)
let pin = MKPointAnnotation()
pin.coordinate = coordinate
pin.title = "Current location"
mapView.addAnnotation(pin)
self.getNearByLandmarks()
updateAnnotations(from: mapView)
}
func mapView(_ mapViewIcon: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var annotationView = mapViewIcon.dequeueReusableAnnotationView(withIdentifier: "custom")
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation,
reuseIdentifier: "custom")
annotationView?.canShowCallout = true
}else{
annotationView?.annotation = annotation
}
annotationView?.image = UIImage(named: "User")
return annotationView
}
private func getNearByLandmarks(){
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = "coffee"
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start{(response, error) in
if let response = response {
let mapItems = response.mapItems
self.landmarks = mapItems.map{
Landmark(placemark: $0.placemark)
}
}
}
}
private func updateAnnotations(from mapView: MKMapView){
let annotations = self.landmarks.map(LandmarkAnnotation.init)
mapView.addAnnotations(annotations)
}
}
You call getNearByLandmarks, and then immediately try to update the annotations:
self.getNearByLandmarks()
updateAnnotations(from: mapView)
but getNearByLandmarks is asynchronous, and takes some time to complete. You need to update the annotations whenever private var landmarks changes, one way is to update it in all the places that set that, like where you say
self.landmarks = mapItems.map{
Landmark(placemark: $0.placemark)
}
note you don't call updateAnnotations(from: mapView) there.
Or you could add a didSet property observer to landmarks itself so that updateAnnotations is called whenever it changes.

Drawing MKPolyline Which Follows User's Current Location

I am trying to draw a path behind the user as they move, tracking their path (like Strava or FitBit apps do when a user starts a workout). So far, the map centres on the user's location but does not start drawing when the user moves. I have tried to implement this with renderForOverlay, but it fails to do so when tested. The code is as follows:
ViewController.swift
import UIKit
import MapKit
import CoreLocation
class StartWorkoutViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var mapsView: MKMapView!
#IBOutlet weak var startButton: UIButton!
var locationManager: CLLocationManager!
var allLocations: [CLLocation] = []
#IBAction func startButton(_ sender: Any) {
// Start the workout
}
override func viewDidLoad() {
super.viewDidLoad()
// Request user's current location
locationManager = CLLocationManager()
locationManager?.requestAlwaysAuthorization()
locationManager?.desiredAccuracy = kCLLocationAccuracyBest
locationManager?.startUpdatingLocation()
locationManager?.startUpdatingHeading()
locationManager?.delegate = self
mapsView?.showsUserLocation = true
mapsView?.mapType = MKMapType(rawValue: 0)!
mapsView?.userTrackingMode = .follow
mapsView?.delegate = self
let noLocation = CLLocationCoordinate2D()
let viewRegion = MKCoordinateRegion(center: noLocation, latitudinalMeters: 100, longitudinalMeters: 100)
mapsView?.setRegion(viewRegion, animated: true)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Add location to the array and prepare to draw a line between last location and current location
print("Location Updated")
allLocations.append(locations[0])
let previousLocation = allLocations[allLocations.count - 1]
let newLocation = locations[0]
let previousCoordinates = previousLocation.coordinate
let newCoordinates = newLocation.coordinate
var area = [previousCoordinates, newCoordinates]
let polyline = MKPolyline(coordinates: &area, count: area.count)
mapsView.addOverlay(polyline)
}
// DOES NOT WORK
func mapView(_ mapsView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.red
polylineRenderer.lineWidth = 4
return polylineRenderer
} else {
return MKPolylineRenderer()
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
// If the authorisation for the user's location has changed, ask again
if status != .authorizedAlways {
locationManager = CLLocationManager()
locationManager?.requestAlwaysAuthorization()
}
}
}
Thank you!
The problem is that you’re grabbing a location, adding it to the array, and then creating a polyline from the last location in the array, allLocations[allLocations.count - 1], (which is now the current location) to the current location (i.e. to itself).
So, grab the last item, previousCoordinate, from the array before you add the new location to it:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let currentLocation = locations.first(where: { $0.horizontalAccuracy >= 0 }) else {
return
}
let previousCoordinate = allLocations.last?.coordinate
allLocations.append(currentLocation)
if previousCoordinate == nil { return }
var area = [previousCoordinate!, currentLocation.coordinate]
let polyline = MKPolyline(coordinates: &area, count: area.count)
mapsView.addOverlay(polyline)
}
I'd also suggest, as you see above, checking for the horizontal accuracy of the location update, to make sure it’s non-negative.
Anyway, that yields:
A few other observations:
I'd suggest retiring the noLocation pattern in viewDidLoad. My above pattern doesn't require that dummy value in the array.
Another issue is that in didChangeAuthorization, you are instantiating a new CLLocationManager and not setting its properties. You are therefore losing the configuration of the original CLLocationManager in viewDidLoad. There’s no need to instantiate another one, but if you do, remember to configure it properly.

How to make the annotation appear on the Apple map via Swift?

So basically, I'm calling a Rest API to get all Bus Stops location, then put annotation of all bus stops within 5km from my current location on the map when a button is called. However, it is just not displaying, I can't seem to figure out the problem.
import UIKit
import MapKit
class MapKitViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var GPSButton: UIButton!
var stopSearchResults: [Value] = []
var Annotations: [BusStopAnnotation] = []
let queryServices = QueryService()
let locationManager:CLLocationManager = CLLocationManager()
#IBOutlet weak var mapView: MKMapView!
var currentLocation: CLLocationCoordinate2D?
var counter: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
queryServices.GetAllBusStops(){
result in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if let result = result {
self.stopSearchResults = result.value
}
}
configureLocationService()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func configureLocationService() {
locationManager.delegate = self
let status = CLLocationManager.authorizationStatus()
if status == .notDetermined {
locationManager.requestAlwaysAuthorization()
} else if status == .authorizedAlways || status == .authorizedWhenInUse {
beginLocationUpdate(locationManager: locationManager)
}
}
private func beginLocationUpdate(locationManager: CLLocationManager) {
mapView.showsUserLocation = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
private func zoomToLatestLocation(with coordinate: CLLocationCoordinate2D) {
let zoomRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000)
mapView.setRegion(zoomRegion, animated: true)
}
#IBAction func GPSTrack(_ sender: Any) {
InputAllAnnotation(busStops: stopSearchResults)
print("Searching for nearby bus stops")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did get latest location")
guard let latestLocation = locations.first else { return }
if currentLocation == nil {
zoomToLatestLocation(with: latestLocation.coordinate)
}
currentLocation = latestLocation.coordinate
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("The status changed")
if status == .authorizedAlways || status == .authorizedWhenInUse {
beginLocationUpdate(locationManager: manager)
}
}
func InputAllAnnotation(busStops: [Value]) {
for busStop in busStops{
let busStopObj = BusStopAnnotation(value: busStop)
Annotations.append(busStopObj)
let distance = busStop.GetDistance(latitude: Double(currentLocation?.latitude ?? 0), longitude: Double(currentLocation?.longitude ?? 0))
if distance < 5000 {
mapView.addAnnotation(busStopObj)
}
}
}
}
extension MapKitViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let busStopAnnotation = mapView.dequeueReusableAnnotationView(withIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier) as?
MKMarkerAnnotationView {
busStopAnnotation.animatesWhenAdded = true
busStopAnnotation.titleVisibility = .adaptive
busStopAnnotation.canShowCallout = true
return busStopAnnotation
}
return nil
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
print("The annotation was selected: \(String(describing: view.annotation?.title))")
}
}
final class BusStopAnnotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
var busStopCode: String?
init(value : Value) {
self.coordinate = value.GetLocationCoordinate2D()
self.title = value.roadName
self.subtitle = value.description
self.busStopCode = value.busStopCode
}
init(coordinate: CLLocationCoordinate2D, roadName: String?, description: String?, busStopCode: String?) {
self.coordinate = coordinate
self.title = roadName
self.subtitle = description
self.busStopCode = busStopCode
}
var region: MKCoordinateRegion {
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
return MKCoordinateRegion(center: coordinate, span: span)
}
}
You may need
self.mapView.delegate = self
import:
import UIKit
import MapKit
set class
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
outlet your map
#IBOutlet weak var map: MKMapView!
Code:
let customPin : CLLocationCoordinate2D = CLLocationCoordinate2DMake(Latitude, Longitude)
let objectAnnotation = MKPointAnnotation()
objectAnnotation.coordinate = customPin
objectAnnotation.title = "Here's your custom PIN"
self.map.addAnnotation(objectAnnotation)
extra:
to set the camera near the PIN
let theSpan:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.009, longitudeDelta: 0.009)
let pointLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(Latitude, Longitude)
let region:MKCoordinateRegion = MKCoordinateRegion(center: pointLocation, span: theSpan)
self.map.setRegion(region, animated: true)
move values depending how close/far you want the camera
let theSpan:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: HERE, longitudeDelta: HERE)

Get user location when app runs and re-center again after moving around using a button

I'm working on a project about MapKit using Swift 3. What the code below does is once I load the app the map will load in default. Then when the user presses the button it takes you to the user's location.
The way I want to fix this is I want it to load the user's location as soon as the app runs, and then when the user decides to move around the screen, she/he could hit the button and then recenter the user location again. Like how it works on Maps.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
// connecting the map from the mainBoard and refering to it as "myMap".....
#IBOutlet weak var myMap: MKMapView!
#IBAction func refLocation(_ sender: Any) {
manager.startUpdatingLocation()
}
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
let span: MKCoordinateSpan = MKCoordinateSpanMake(0.0075,0.0075)
let myLocation :CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
myMap.setRegion(region, animated: true)
}
self.myMap.showsUserLocation = true
manager.stopUpdatingLocation()
}
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
}
}
It isn't clear what you're asking.
If you want to get a single location update you can use the function func requestLocation().
You could create a location manager (and set yourself as its delegate) in your view controller's viewDidLoad and call requestLocation() once.
Then call requestLocation() again in your button action.
Make your didUpdateLocations method always recenter the map. That way you'll receive one and only one update from clicking your button, and the map will recenter as soon as the update is received.
Try this code for Swift 3
import UIKit
import MapKit
import CoreLocation
class ViewController2: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var currentLocation = CLLocation()
var currentLat: Double!
var currentLon: Double!
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
myLocation()
}
func myLocation()
{
if currentLocation.coordinate.latitude == 0.00 || currentLocation.coordinate.longitude == 0.0
{
print("no location")
}
else
{
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled()
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
let locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()
if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways)
{
currentLocation = locManager.location!
}
print("currentLongitude: \(currentLocation.coordinate.longitude)")
print("currentLatitude: \(currentLocation.coordinate.latitude)")
currentLon = currentLocation.coordinate.longitude
currentLat = currentLocation.coordinate.latitude
let span = MKCoordinateSpanMake(0.2, 0.2)
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: currentLat, longitude: currentLon), span: span)
mapView.setRegion(region, animated: true)
}
}
#IBAction func MyLocationBtnPressed(_ sender: Any)
{
let span = MKCoordinateSpanMake(0.1, 0.1)
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: currentLat, longitude: currentLon), span: span)
mapView.setRegion(region, animated: true)
}
}
You don't have to call startUpdatingLocation() again because MapView always knows userLocation.
Replace
#IBAction func refLocation(_ sender: Any) {
manager.startUpdatingLocation()
}
with
#IBAction func refLocation(_ sender: Any) {
let region: MKCoordinateRegion = MKCoordinateRegionMake(myMap.userLocation.coordinate, myMap.region.span)
mapView.setRegion(region, animated: true)
}

How do I create a simple navigation view for my iOS app using swift

I am trying to create a very simple navigation view controller for my master detail application. I am using swift (2) and have the following code:
import MapKit
import UIKit
import CoreData
import CoreLocation
class DirectionsViewController: UIViewController, CLLocationManagerDelegate,MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
var point1 = MKPointAnnotation()
var point2 = MKPointAnnotation()
var myRoute : MKRoute?
override func viewDidLoad() {
super.viewDidLoad()
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var locValue:CLLocationCoordinate2D = manager.location.coordinate
point1.coordinate = CLLocationCoordinate2DMake(locValue.latitude, locValue.longitude) //code to sync in current location
point1.title = "You are here"
point1.subtitle = "Start"
mapView.addAnnotation(point1)
// to test location - print("locations = \(locValue.latitude) \(locValue.longitude)")
point2.coordinate = CLLocationCoordinate2DMake(40.22396739999999, -74.0303199)
point2.title = "First Pentecostal Church"
point2.subtitle = "Neptune, NJ"
mapView.addAnnotation(point2)
mapView.centerCoordinate = point2.coordinate
mapView.delegate = self
//Span of the map
mapView.setRegion(MKCoordinateRegionMake(point2.coordinate, MKCoordinateSpanMake(0.7,0.7)), animated: true)
var directionsRequest = MKDirectionsRequest()
let markUser = MKPlacemark(coordinate: CLLocationCoordinate2DMake(point1.coordinate.latitude, point1.coordinate.longitude), addressDictionary: nil)
let markFPC = MKPlacemark(coordinate: CLLocationCoordinate2DMake(point2.coordinate.latitude, point2.coordinate.longitude), addressDictionary: nil)
directionsRequest.setSource(MKMapItem(placemark: markUser))
directionsRequest.setDestination(MKMapItem(placemark: markFPC))
directionsRequest.transportType = MKDirectionsTransportType.Automobile
var directions = MKDirections(request: directionsRequest)
directions.calculateDirectionsWithCompletionHandler { (response:MKDirectionsResponse!, error: NSError!) -> Void in
if error == nil {
self.myRoute = response.routes[0] as? MKRoute
self.mapView.addOverlay(self.myRoute?.polyline)
}
}
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
var myLineRenderer = MKPolylineRenderer(polyline: myRoute?.polyline!)
myLineRenderer.strokeColor = UIColor.redColor()
myLineRenderer.lineWidth = 3
return myLineRenderer
}
}
I get no response in the simulator and I am not sure where I went wrong. I believe this is swift 2. Any guidance would be appreciated.
When I try to run your code, I too don't get anything on the map, even though the locationservices is initialized and (apparently) working.
But, I do get the following warning in the console:
This app has attempted to access privacy-sensitive data without a
usage description. The app's Info.plist must contain an
NSLocationAlwaysUsageDescription key with a string value explaining to
the user how the app uses this data.
So, adding the NSLocationAlwaysUsageDescriptionto your plist file, and your will get updates from the location services.

Resources