ITP 342 Mobile App Dev Locations and Maps
Locations and Maps Every ios device has the ability to determine where in the world it is Create a live interactive map showing any locations you like, including the user's location 2
Locations and Maps ios offers 2 frameworks to assist with locations and maps: Core Location framework provides classes that help the device determine its location and heading, and work with location-based information. Map Kit framework provides the user interface aspect of location awareness. It includes Apple Maps, which provides map views, satellite views, and hybrid views in normal 2D and a new 3D view. Map Kit offers the capability to manage map annotations like pins, and map overlays for highlighting locations, routes, or other features on a map. 3
Core Location Leverages 3 technologies GPS (Global Positioning Service) Not available on 1 st -gen iphone, ipod touches, or Wi-Fi-only ipads Works on any device with at least a 3G data connection since it will contain a GPS unit Cell ID Location Wi-Fi Positioning Service (WPS) 4
GPS GPS reads microwave signals from multiple satellites to determine the current location It is satellite-based navigation system made up of a network of 24 satellites placed into orbit by the U.S. Department of Defense It was originally intended for military applications, but in the 1980s, the government made the system available for civilian use Technically, Apple uses a version of GPS called Assisted GPS (A-GPS) Uses network resources to help improve the performance of stand-along GPS 5
Cell ID Location Gives a rough approximation of the current location based on the physical location of the cellular base station that the device is currently in contact with Since each base station can cover a fairly large area, there is a fairly large margin of error here Requires a cell radio connection, so it works on all iphones and the ipad with a 3G data connection 6
Wi-Fi Positioning Service Uses the MAC addresses from nearby Wi-Fi access points to make a guess at your location by referencing a large database of known service providers and the areas they service WPS is imprecise and can be off by many miles 7
Battery Drain All 3 methods put a noticeable drain on the battery Your app shouldn't poll for location any more often than is absolutely necessary When using Core Location, you have the option of specifying a desired accuracy By carefully specifying the absolute minimum accuracy level you need, you can prevent unnecessary battery drain The technologies are hidden from your app We don't tell it what to use It decides from the available technologies which is best for fulfilling your request 8
Core Location It respects the privacy of the user, and requires the user to provide permission to have access to the current location of the device. Location Services can be turned on or off for all apps on the device in the Settings app under the Privacy section, and can be turned on or off for each app individually. 9
Location Manager Use CLLocationManager class Create a class that conforms to the CLLocationManagerDelegate protocol Create an instance and set delegate CLLocationManager *locationmanager = [[CLLocationManager alloc] init]; locationmanager.delegate = self; SWIFT let locationmanager = CLLocationManager() locationmanager.delegate = self 10
Desired Accuracy Set the desiredaccuracy (a double in meters) Can set a number like 10 (10.0f) Try to determine location within 10 meters Or use constants kcllocationaccuracybest kcllocationaccuracybestfornavigation kcllocationaccuracynearesttenmeters kcllocationaccuracyhundredmeters kcllocationaccuracykilometer kcllocationaccuracythreekilometers locationmanager.desiredaccuracy = kcllocationaccuracybest; SWIFT locationmanager.desiredaccuracy = kcllocationaccuracybest 11
Distance Filter Set the distancefilter (a double in meters) Telling the location manager not to notify you of every change Instead to notify you only when the location changes by more than a certain amount Setting up a distance filter can reduce the amount of polling your application does Set it to an amount such as 1000 meters (1000.0f) locationmanager.distancefilter = 1000.0f; Or the constant kcldistancefilternone 12
Permissions We need to ask for user permission first before accessing their location [locationmanager requestwheninuseauthorization]; or [locationmanager requestalwaysauthorization]; Depending on whether your app tracks user location while in use or always, you need to update the description in Info.plist with keys NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription 13
Start & Stop Start the Location Manager when you are ready to start polling for location [locationmanager startupdatinglocation]; Stop the Location Manager as soon as you possibly can due to the drain on the battery [locationmanager stopupdatinglocation]; 14
Delegate The CLLocationManagerDelegate protocol defines several methods, all of them optional To get location updates, use the following method locationmanager: didupdatelocations: To get error notifications, use the following method locationmanager: didfailwitherror: 15
Update Location Location info is passed from the location manager using instances of the CLLocation class This class has 5 valuable properties The latitude and longitude are stored in a property called coordinate (in degrees) The horizontalaccuracy property describes the radius of a circle showing how confident it is in its lat & long calculations The larger the value, the less certain of the location Property called altitude that can tell you how many meters above (or below) sea level The verticalaccuracy property is an indication of how confident it is in its determination of altitude CLLocation objects also have a timestamp that tells when the location manager made the location determination 16
Error Notifications If Core Location is not able to determine your current location, it will call a second delegate method named locationmanager: didfailwitherror: The most likely cause is that the user denies access The user must authorize use of the location manager, so the first time your app wants to determine the location an alert will pop up asking if it's OK Error code is kclerrordenied The kclerrorlocationunknown code is used when it is unable to determine the location 17
User Interface Create 12 labels 6 will be filled with data Need IBOutlets Align them nicely 18
Interface Needs to import CoreLocation/CoreLocation.h Needs to adhere to the CLLocationManagerDelegate protocol 19
Create properties Implementation @property (strong, nonatomic) CLLocationManager *locationmanger; @property (strong, nonatomic) CLLocation *startpoint; @property (assign, nonatomic) CLLocationDistance distancefromstart; In the viewdidload method, set up Location Manager self.locationmanger = [[CLLocationManager alloc] init]; self.locationmanger.delegate = self; self.locationmanger.desiredaccuracy = kcllocationaccuracybest; [self.locationmanager requestwheninuseauthorization]; [self.locationmanger startupdatinglocation]; 20
Delegate Methods - (void)locationmanager:(cllocationmanager *)manager didupdatelocations:(nsarray *)locations { CLLocation *newlocation = [locations lastobject]; \u00b0 is the Unicode representation of the degree symbol NSString *latitudestring = [NSString stringwithformat:@"%g\u00b0", newlocation.coordinate.latitude]; self.latitudelabel.text = latitudestring; NSString *longitudestring = [NSString stringwithformat:@"%g\u00b0", newlocation.coordinate.longitude]; self.longitudelabel.text = longitudestring; NSString *horizontalaccuracystring = [NSString stringwithformat:@"%gm", newlocation.horizontalaccuracy]; self.horizontalaccuracylabel.text = horizontalaccuracystring; NSString *altitudestring = [NSString stringwithformat:@"%gm", newlocation.altitude]; self.altitudelabel.text = altitudestring; NSString *verticalaccuracystring = [NSString stringwithformat:@"%gm", newlocation.verticalaccuracy]; self.verticalaccuracylabel.text = verticalaccuracystring; 21
Delegate Methods if (self.startpoint == nil) { self.startpoint = newlocation; self.distancefromstart = 0; } else { self.distancefromstart = [newlocation distancefromlocation:self.startpoint]; } NSString *distancestring = [NSString stringwithformat:@"%gm", self.distancefromstart]; self.distancetraveledlabel.text = distancestring; } 22
Delegate Methods - (void)locationmanager:(cllocationmanager *)manager didfailwitherror:(nserror *)error { NSString *errortype = nil; if (error.code == kclerrordenied) errortype = @"Access Denied"; else errortype = @"Unknown Error"; } UIAlertView *alert = [[UIAlertView alloc] initwithtitle:@"error getting Location" message:errortype delegate:nil cancelbuttontitle:@"okay" otherbuttontitles:nil]; [alert show]; 23
Map Kit Use the Map Kit framework to visualize movement on a map It contains one primary view class representing a map display, which responds to user gestures Also lets us insert annotations for any locations we want to show up on our map https://developer.apple.com/library/ios/docum entation/userexperience/conceptual/location AwarenessPG/MapKit/MapKit.html 24
Select the 12 labels Interface From the top menu, select Editor à Embed In à View In the attributes inspector for this view, disable the User Interaction Enabled checkbox To lock this view's height, select Editor à Pin à Height 25
Interface Import <MapKit/MapKit.h> Using the Library, find the Map View (MKMapView) Drag onto the main view Resize to the whole screen Select Editor à Arrange à Send to Back to make is appear behind the labels Add an IBOutlet for this mapview 26
Model for Markers on Map New Objective-C class (child of NSObject) XYZMarker In its interface Import MapKit/Mapkit.h Make it a protocol of MKAnnotation Add the following properties: @property (copy, nonatomic) NSString *title; @property (copy, nonatomic) NSString *subtitle; @property (assign, nonatomic) CLLocationCoordinate2D coordinate; 27
Import XYZMarker.h View Controller At the end of viewdidload, add self.mapview.showsuserlocation = YES; Within locationmanager:didupdatelocations: Change the code to use XYZMarker for the startpoint Create a new MKCoordinateRegion which lets us tell the view which section of the map we want it to display 28
View Controller Add code within locationmanager:didupdatelocations: if (self.startpoint == nil) { self.startpoint = newlocation; self.distancefromstart = 0; XYZMarker *start = [[XYZMarker alloc] init]; start.coordinate = newlocation.coordinate; start.title = @"Start Point"; start.subtitle = @"This is where we started!"; [self.mapview addannotation:start]; MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance (newlocation.coordinate, 100, 100); [self.mapview setregion:region animated:yes]; } else { self.distancefromstart = [newlocation distancefromlocation:self.startpoint]; } 29
Map Kit Lots more stuff you can do with the Map Kit Zoom and pan the map content Mark your annotation view as draggable Display overlays on a map Ask the Maps app to display directions Configure your app to accept directions 30
Getting Directions As of ios 6, the standard Maps.app was enhanced to provide turn-by-turn navigation in addition to directions. It was also enhanced to allow other apps to open it with specific instructions on what to display. MapKit offers a directions request, which can provide directions to be used directly in an app. The directions request can return an array of polylines representing route options, with accompanying route steps that can be presented in a table view. 31
Map Kit Use the MapKit framework To open Maps.app, use the MKMapItem class, specifically the class method openmapswithitems: launchoptions: To request directions to be displayed, use the MKDirections class, specifically the class method MKDirectionsRequest 32
Test Specific Locations Test specific locations within Xcode by using GPX files GPX = GPS Exchange Format document, which can be used to communicate GPS information between devices using XML <?xml version="1.0"?> <gpx version="1.1" creator="xcode"> <wpt lat="34.020669" lon="-118.289426"> <name>viterbi School of Engineering, USC</name> </wpt> </gpx> 33
Set-up To tell Xcode to use a GPX file in debugging: Select Edit Scheme from the Scheme selection drop-down in the upper-left corner of a project window Select the Options tab Check the Allow Location Simulation check box When this is checked, a location can be selected form the drop-down next to Default Location This includes some built-in locations and any GPX files that have been added to the project 34
Run in Debug Mode When the app is run in debug mode, Core Location will return the location specified in the GPX file as the current location of the device or simulator. To change the location while debugging, select Debug, Simulate Location from the menu in Xcode and select a location. Core Location will change the location to the selected location, and will fire the locationmanager: didupdatelocations: delegate method. 35
Geocoding Geocoding is the process of finding latitude and longitude coordinates from a humanreadable address. Reverse-geocoding is the process of finding a human readable address from coordinates. Under Core Location, use the CLGeocoder class. 36
Geofencing Geofencing, also called regional monitoring, is the capability to track when a device enters or exits a specified map region. ios uses this to great effect with Siri to accomplish things like, "Remind me to pick up bread when I leave the office." ios also uses geofencing in Passbook, to help users see the passes that are relevant to them on the home screen. 37
Apple Documentation https://developer.apple.com/library/ios/docum entation/userexperience/conceptual/location AwarenessPG/CoreLocation/CoreLocation.ht ml 38