Display latitude and longitude in a UITextView that is a subview of the UIWindow: - objective-c

I'm trying to write a program that displays count, latitude and longitude in a UITextView that is a subview of the UIWindow. I couldn't make it to display the information properly on the simulator screen. Any help is appreciated!
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#interface ViewController () <CLLocationManagerDelegate>
#end
#implementation ViewController
{
CLLocationManager *locationManager;
int count;
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
count++;
CLLocation *location=locations[0];
UITextView *textview = [[UITextView alloc] initWithFrame:CGRectMake(20, 10, 280, 30)];
textview.backgroundColor=[UIColor whiteColor];
NSString *coun=[NSString stringWithFormat:#"%i",count];
NSString *lat=[NSString stringWithFormat:#"%f",location.coordinate.latitude];
NSString *lon=[NSString stringWithFormat:#"%f",location.coordinate.longitude];
textview.text =(#"%# %#-%#", coun, lat, lon);
[self.view addSubview:textview];
}
- (void)viewDidLoad {
[super viewDidLoad];
locationManager=[[CLLocationManager alloc] init];
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
locationManager.delegate=self;
[locationManager startUpdatingLocation];
[locationManager requestWhenInUseAuthorization];
}

I hope , Following info can help you:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
int count;
}
#end
and add this:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self.locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
callback function:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(#"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
store the above values of latitude and longitude in string
NSString *coun=[NSString stringWithFormat:#"%i",count];
NSString *lat=[NSString stringWithFormat:#"%f",newlocation.coordinate.latitude];
NSString *lon=[NSString stringWithFormat:#"%f",newlocation.coordinate.longitude];
and then set it to textfield:
textview.text =(#"%# %#-%#", coun, lat, lon);
You also have to add a string for the (in info.plist)
[`NSLocationAlwaysUsageDescription`]

Related

Xcode - CoreLocation not showing blue dot

For some reason when I launch my app it does everything correctly except show the user as blue dot on the map. It zooms in to the users current location, just no dot. Any help would be greatly appreciated.
I've added code and screenshots below for resources.
FrontViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface FrontViewController : UIViewController <CLLocationManagerDelegate>
{
CLLocationManager *objLocationManager;
double latitude_UserLocation, longitude_UserLocation;
}
#property (weak, nonatomic) IBOutlet MKMapView *objMapView;
#end
FrontViewController.m
#import "FrontViewController.h"
#import "SWRevealViewController.h"
#interface FrontViewController()
// Private Methods:
- (IBAction)pushExample:(id)sender;
#end
#implementation FrontViewController
#synthesize objMapView;
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadUserLocation];
//self.title = NSLocalizedString(#"Front View", nil);
SWRevealViewController *revealController = [self revealViewController];
[revealController panGestureRecognizer];
[revealController tapGestureRecognizer];
[self.navigationController.navigationBar addGestureRecognizer:revealController.panGestureRecognizer];
UIBarButtonItem *revealButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"reveal-icon.png"]
style:UIBarButtonItemStyleBordered target:revealController action:#selector(revealToggle:)];
self.navigationItem.leftBarButtonItem = revealButtonItem;
UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"BSEEK-Logo.png"]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
UIView* titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 84, 84)];
imageView.frame = titleView.bounds;
[titleView addSubview:imageView];
self.navigationItem.titleView = titleView;
}
- (IBAction)pushExample:(id)sender
{
UIViewController *stubController = [[UIViewController alloc] init];
stubController.view.backgroundColor = [UIColor whiteColor];
[self.navigationController pushViewController:stubController animated:YES];
}
- (void) loadUserLocation
{
objLocationManager = [[CLLocationManager alloc] init];
objLocationManager.delegate = self;
objLocationManager.distanceFilter = kCLDistanceFilterNone;
objLocationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
if ([objLocationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[objLocationManager requestWhenInUseAuthorization];
}
[objLocationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_6_0)
{
CLLocation *newLocation = [locations objectAtIndex:0];
latitude_UserLocation = newLocation.coordinate.latitude;
longitude_UserLocation = newLocation.coordinate.longitude;
[objLocationManager stopUpdatingLocation];
[self loadMapView];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
[objLocationManager stopUpdatingLocation];
}
- (void) loadMapView
{
CLLocationCoordinate2D objCoor2D = {.latitude = latitude_UserLocation, .longitude = longitude_UserLocation};
MKCoordinateSpan objCoorSpan = {.latitudeDelta = 0.2, .longitudeDelta = 0.2};
MKCoordinateRegion objMapRegion = {objCoor2D, objCoorSpan};
[objMapView setRegion:objMapRegion];
}
#end
Project Files
MKMapView has a showsUserLocation property. It looks like you need to turn that on.
You can set that property in code, but if your map view is created in a storyboard scene you can just check the User Location box in the storyboard editor:
Also: Make sure you have the appropriate key in your Info.plist to allow the app to access the user's location, and that you've granted the app appropriate permission on the device. (You can check in Settings->Privacy->Location Services.) If the app doesn't have permission to get the location, the map won't show it even if showsUserLocation is enabled.

how to show longitude, latitude in label of this same code

//ViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate>
#property (weak, nonatomic) IBOutlet UILabel *addresslbl;
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#end
//Viewcontroller.m
#import "ViewController.h"
#interface ViewController ()
{
CLLocationManager *locationManager;
CLLocationCoordinate2D updateLocation;
NSString *strAddress;
CLGeocoder *geocoder;
}
#end
#implementation ViewController
#define AzaveaCoordinate CLLocationCoordinate2DMake(19.167391, 73.247686)
- (void)viewDidLoad {
[super viewDidLoad];
[_mapView setRegion:MKCoordinateRegionMake(AzaveaCoordinate, MKCoordinateSpanMake(0.010, 0.010)) animated:YES];
geocoder = [[CLGeocoder alloc]init];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager requestWhenInUseAuthorization];
self.mapView.delegate = self;
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
}
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
CLLocation *location = [[CLLocation alloc]initWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
[self geocode:location];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
{
CLLocation *currentLocation = newLocation;
self.mapView.centerCoordinate = currentLocation.coordinate;
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(currentLocation.coordinate,1500,1500);
[self.mapView setRegion: region animated:true];
[self geocode:currentLocation];
}
-(void)geocode:(CLLocation *)location
{
// geocoder = [[CLGeocoder alloc]init];
[geocoder cancelGeocode];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *data, NSError *error)
{
CLPlacemark *placemark = [data lastObject];
NSDictionary * addressDict = placemark.addressDictionary;
NSArray * addressList = addressDict[#"FormattedAddressLines"];
NSString * address = [NSString stringWithFormat:#"%#,%#,%#",addressList[0],addressList[1],addressList[2]];
NSLog(#" Address is :%#",address);
self.addresslbl.text = address;
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
This is the moveable map code like ola and uber. Means when i move the map, at that time the map pin is noted, the noted pin is given me address of the that particular area like city, state, pincode etc in label, but i want only the longitude, latitude value of this address in label.
so please help me about this code. How can i get the longitude latitude value in ?
Assuming that the label that you want to is self.addresslbl, change this method:
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
CLLocation *location = [[CLLocation alloc]initWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
[self geocode:location];
}
To:
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
self.addresslbl.text = [NSString stringWithFormat:#"%f, %f", mapView.centerCoordinate.longitude, mapView.centerCoordinate.latitude];
}

Append Google Maps URL with Current Location

I am trying to compose an email with a Google Maps link using Core Location and MessageUI. Presently my code produces this string: https://maps.google.com?saddr=Current+Location&daddr=0.000000,0.000000.
I would like to append the device's longitude and latitude with the URL.
Here is my implementation:
#import "ViewController.h"
#interface ViewController () <CLLocationManagerDelegate>
#end
#implementation ViewController{
NSString *currentLongitude;
NSString *currentLatitude;
NSString *googleMapsURL;
CLLocationManager *locationManager_;
}
- (void)viewDidLoad {
[super viewDidLoad];
locationManager_ = [[CLLocationManager alloc] init];
locationManager_.delegate = self;
locationManager_.distanceFilter = kCLDistanceFilterNone;
locationManager_.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager_ requestAlwaysAuthorization];
[locationManager_ startUpdatingLocation];
}
- (IBAction)composeMailButton:(id)sender {
NSString *bodyHeader = #"Here are you directions:";
NSString *mailBody = [NSString stringWithFormat:#"%#\n%#", bodyHeader, googleMapsURL];
MFMailComposeViewController *emailComposer = [[MFMailComposeViewController alloc] init];
[emailComposer setSubject:#"Google Maps Directions"];
[emailComposer setMessageBody:mailBody isHTML:NO];
[emailComposer setToRecipients:#[#"castro.michael87#gmail.com"]];
[emailComposer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentViewController:emailComposer animated:YES completion:nil];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *newLocation = [locations lastObject];
NSString *googleMapsURL = [[NSString alloc] initWithFormat:#"https://maps.google.com?saddr=Current+Location&daddr=%1.6f,%1.6f",newLocation.coordinate.latitude, newLocation.coordinate.longitude];
}
I am guessing that I have not correctly implemented the locationManager. Any input is very much appreciated!
First, you need to make use that you added the NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription in your info.plist file.
Second, your viewController need to implement the <CLLocationManagerDelegate>
#interface ViewController ()<CLLocationManagerDelegate>
Third, setup your locationManager in your viewDidLoad method.
locationManager_ = [[CLLocationManager alloc] init];
locationManager_.delegate = self;
locationManager_.distanceFilter = kCLDistanceFilterNone;
locationManager_.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager_ requestAlwaysAuthorization];
[locationManager_ startUpdatingLocation];
Fourth, implement the -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations method:
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *newLocation = [locations lastObject];
NSString *googleMapsURL = [[NSString alloc] initWithFormat:#"https://maps.google.com?saddr=Current+Location&daddr=%1.6f,%1.6f",newLocation.coordinate.latitude, newLocation.coordinate.longitude];
NSLog(#"%#", googleMapsURL);
}
Finally, if you test in simulator, you need to simulate a location:
Code Snippet: https://gist.github.com/ziyang0621/b1be760596da54873f81

Use of undeclared identifier 'locationManager'

I'm trying to follow this tutorial:
http://www.appcoda.com/how-to-get-current-location-iphone-user/
Everything is fine till I add this line:
locationManager = [[CLLocationManager alloc] init];
Then I get the error.
I also get errors for these lines: (Xcode suggests I use "_LongitudeLabel"?
if (currentLocation != nil) {
longitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
latitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
Any idea what's wrong? Does the tutorial have errors or have I done something wrong?
Thanks!
This is ViewController.m file:
#import "ViewController.h"
#implementation MyLocationViewController {
CLLocationManager *locationManager;
}
#end
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)getCurrentLocation:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
latitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
#end
This is ViewController.h file:
// ViewController.h
// MyLocationDemo
//
// Created by Ian Nicoll on 12/11/14.
// Copyright (c) 2014 Ian Nicoll. All rights reserved.
//
#import <CoreLocation/CoreLocation.h>
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *LatitudeLabel;
#property (weak, nonatomic) IBOutlet UILabel *LongitudeLabel;
#property (weak, nonatomic) IBOutlet UILabel *addressLabel;
- (IBAction)getCurrentLocation:(id)sender;
#end
#interface MyLocationViewController : UIViewController <CLLocationManagerDelegate>
#end
The first issue is an error on your part. You declared locationManager in MyLocationViewController but try to initialize it in the viewDidLoad of ViewController, where it of course does not exist.
The second issue is an issue with the instructions. When you declare an #property, the default behavior is to create an instance variable with an underscore in front of it.
So #property (weak, nonatomic) IBOutlet UILabel *LatitudeLabel; can be accessed as self.latitudeLabel (which goes through the setter/getter) or just _latitudeLabel which accesses the ivar directly. The latter is probably what you want.
Ok so the build now is Succeeded (though I'm not 100& sure I got things right) but now I get a warning for this line: locationManager.delegate = self; - Assigning to 'id'from incompatible type 'ViewControler *const_strong'
Would you know how to fix this warning?
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController {
CLLocationManager *locationManager;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)getCurrentLocation:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
_LongitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
_LatitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
#end

Geofencing in Xcode 4, didEnterRegion gives multiple callbacks

I'm trying to create an app in Xcode 4 based on geofencing. The app will notify the user when entering a region with certain center coordinates and a certain radius given in meters. All my regions are saved in a p-list. However I get multiple callbacks and more locations than I want gets called (i.e. locations not even in the right location gets called. Below you can see our code. I have also added a kml-layer which you can ignore because it has nothing to do with the fencing. My p-list is an array and contains of 20 items with the type dictionary and the keys are title, latitude, longitude and radius. The radius is set to 50 meters.
ViewController.h
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#implementation ViewController
#synthesize coordinateLabel;
#synthesize mapView;
CLLocationManager *_locationManager;
NSArray *_regionArray;
- (void)viewDidLoad
{
[super viewDidLoad];
[self initializeMap];
[self initializeLocationManager];
NSArray *geofences = [self buildGeofenceData];
[self initializeRegionMonitoring:geofences];
[self initializeLocationUpdates];
}
- (void)viewDidUnload
{
[self setCoordinateLabel:nil];
[self setMapView:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)initializeMap {
CLLocationCoordinate2D initialCoordinate;
initialCoordinate.latitude = 41.88072;
initialCoordinate.longitude = -87.67429;
[self.mapView setRegion:MKCoordinateRegionMakeWithDistance(initialCoordinate, 400, 400) animated:YES];
self.mapView.centerCoordinate = initialCoordinate;
[self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
}
- (void)initializeLocationManager {
// Check to ensure location services are enabled
if(![CLLocationManager locationServicesEnabled]) {
[self showAlertWithMessage:#"You need to enable location services to use this app."];
return;
}
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
}
- (void) initializeRegionMonitoring:(NSArray*)geofences {
if (_locationManager == nil) {
[NSException raise:#"Location Manager Not Initialized" format:#"You must initialize location manager first."];
}
if(![CLLocationManager regionMonitoringAvailable]) {
[self showAlertWithMessage:#"This app requires region monitoring features which are unavailable on this device."];
return;
}
for(CLRegion *geofence in geofences) {
[_locationManager startMonitoringForRegion:geofence];
}
}
- (NSArray*) buildGeofenceData {
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"regions" ofType:#"plist"];
_regionArray = [NSArray arrayWithContentsOfFile:plistPath];
NSMutableArray *geofences = [NSMutableArray array];
for(NSDictionary *regionDict in _regionArray) {
CLRegion *region = [self mapDictionaryToRegion:regionDict];
[geofences addObject:region];
}
return [NSArray arrayWithArray:geofences];
}
- (CLRegion*)mapDictionaryToRegion:(NSDictionary*)dictionary {
NSString *title = [dictionary valueForKey:#"title"];
CLLocationDegrees latitude = [[dictionary valueForKey:#"latitude"] doubleValue];
CLLocationDegrees longitude =[[dictionary valueForKey:#"longitude"] doubleValue];
CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
CLLocationDistance regionRadius = [[dictionary valueForKey:#"radius"] doubleValue];
return [[CLRegion alloc] initCircularRegionWithCenter:centerCoordinate
radius:regionRadius
identifier:title];
}
- (void)initializeLocationUpdates {
[_locationManager startUpdatingLocation];
}
#pragma mark - Location Manager - Region Task Methods
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
NSLog(#"Entered Region - %#", region.identifier);
[self showRegionAlert:#"Entering Region" forRegion:region.identifier];
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
NSLog(#"Exited Region - %#", region.identifier);
[self showRegionAlert:#"Exiting Region" forRegion:region.identifier];
}
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
NSLog(#"Started monitoring %# region", region.identifier);
}
#pragma mark - Location Manager - Standard Task Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.coordinateLabel.text = [NSString stringWithFormat:#"%f,%f",newLocation.coordinate.latitude, newLocation.coordinate.longitude];
}
#pragma mark - Alert Methods
- (void) showRegionAlert:(NSString *)alertText forRegion:(NSString *)regionIdentifier {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:alertText
message:regionIdentifier
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
}
- (void)showAlertWithMessage:(NSString*)alertText {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Location Services Error"
message:alertText
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
#end
ViewController.m
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#implementation ViewController
#synthesize coordinateLabel;
#synthesize mapView;
#synthesize kmlParser;
CLLocationManager *_locationManager;
NSArray *_regionArray;
- (void)viewDidLoad
{
[super viewDidLoad];
[self initializeMap];
[self initializeLocationManager];
NSArray *geofences = [self buildGeofenceData];
[self initializeRegionMonitoring:geofences];
[self initializeLocationUpdates];
// Locate the path to the route.kml file in the application's bundle
// and parse it with the KMLParser.
NSString *path = [[NSBundle mainBundle] pathForResource:#"urbanPOIsthlm" ofType:#"kml"];
NSURL *url = [NSURL fileURLWithPath:path];
kmlParser = [[KMLParser alloc] initWithURL:url];
[kmlParser parseKML];
// Add all of the MKOverlay objects parsed from the KML file to the map.
NSArray *overlays = [kmlParser overlays];
[mapView addOverlays:overlays];
// Add all of the MKAnnotation objects parsed from the KML file to the map.
NSArray *annotations = [kmlParser points];
[mapView addAnnotations:annotations];
// Walk the list of overlays and annotations and create a MKMapRect that
// bounds all of them and store it into flyTo.
MKMapRect flyTo = MKMapRectNull;
for (id <MKOverlay> overlay in overlays) {
if (MKMapRectIsNull(flyTo)) {
flyTo = [overlay boundingMapRect];
} else {
flyTo = MKMapRectUnion(flyTo, [overlay boundingMapRect]);
}
}
for (id <MKAnnotation> annotation in annotations) {
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
}
}
// Position the map so that all overlays and annotations are visible on screen.
mapView.visibleMapRect = flyTo;
}
- (void)viewDidUnload
{
[self setCoordinateLabel:nil];
[self setMapView:nil];
//DERAS alltså KML!!!
[kmlParser release];
///
[super viewDidUnload];
}
/////Deras alltså KML!!!
#pragma mark MKMapViewDelegate
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
return [kmlParser viewForOverlay:overlay];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
return [kmlParser viewForAnnotation:annotation];
}
//////////
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)initializeMap {
CLLocationCoordinate2D initialCoordinate;
initialCoordinate.latitude = 59.3353733;
initialCoordinate.longitude = 18.0712647;
[self.mapView setRegion:MKCoordinateRegionMakeWithDistance(initialCoordinate, 400, 400) animated:YES];
self.mapView.centerCoordinate = initialCoordinate;
[self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
}
- (void)initializeLocationManager {
// Check to ensure location services are enabled
if(![CLLocationManager locationServicesEnabled]) {
[self showAlertWithMessage:#"You need to enable location services to use this app."];
return;
}
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
}
- (void) initializeRegionMonitoring:(NSArray*)geofences {
if (_locationManager == nil) {
[NSException raise:#"Location Manager Not Initialized" format:#"You must initialize location manager first."];
}
if(![CLLocationManager regionMonitoringAvailable]) {
[self showAlertWithMessage:#"This app requires region monitoring features which are unavailable on this device."];
return;
}
for(CLRegion *geofence in geofences) {
[_locationManager startMonitoringForRegion:geofence
desiredAccuracy:kCLLocationAccuracyBest];
}
}
- (NSArray*) buildGeofenceData {
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"regions" ofType:#"plist"];
_regionArray = [NSArray arrayWithContentsOfFile:plistPath];
NSMutableArray *geofences = [NSMutableArray array];
for(NSDictionary *regionDict in _regionArray) {
CLRegion *region = [self mapDictionaryToRegion:regionDict];
[geofences addObject:region];
}
return [NSArray arrayWithArray:geofences];
}
- (CLRegion*)mapDictionaryToRegion:(NSDictionary*)dictionary {
NSString *title = [dictionary valueForKey:#"title"];
CLLocationDegrees latitude = [[dictionary valueForKey:#"latitude"] doubleValue];
CLLocationDegrees longitude =[[dictionary valueForKey:#"longitude"] doubleValue];
CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
//CLLocationDistance regionRadius = 50.000;
CLLocationDistance regionRadius = [[dictionary valueForKey:#"radius"] doubleValue]; //<--STOD DOUBLE ISTÄLLET
return [[CLRegion alloc] initCircularRegionWithCenter:centerCoordinate
radius:regionRadius
identifier:title];
}
- (void)initializeLocationUpdates {
[_locationManager startUpdatingLocation];
}
#pragma mark - Location Manager - Region Task Methods
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
NSLog(#"Entered Region - %#", region.identifier);
[self showRegionAlert:#"Entering Region" forRegion:region.identifier];
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
NSLog(#"Exited Region - %#", region.identifier);
[self showRegionAlert:#"Exiting Region" forRegion:region.identifier];
}
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
NSLog(#"Started monitoring %# region", region.identifier);
}
#pragma mark - Location Manager - Standard Task Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.coordinateLabel.text = [NSString stringWithFormat:#"%f,%f",newLocation.coordinate.latitude, newLocation.coordinate.longitude];
}
#pragma mark - Alert Methods
- (void) showRegionAlert:(NSString *)alertText forRegion:(NSString *)regionIdentifier {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:alertText
message:regionIdentifier
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
}
- (void)showAlertWithMessage:(NSString*)alertText {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Location Services Error"
message:alertText
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
#end
Appdelegate.h
#import <UIKit/UIKit.h>
#class ViewController;
#interface AppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
ViewController *viewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet ViewController *viewController;
#end
Appdelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#implementation AppDelegate
//DERAS ALLTSÅ KML!!
#synthesize window;
#synthesize viewController;
//
//Deras alltså KML!!
#pragma mark -
#pragma mark Application lifecycle
//
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
//Deras alltså KML!!
[window addSubview:viewController.view];
//
return YES;
}
//Deras alltså KML!!!
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
//
#end