I have to do Custom MapView, I have done the mkCircle with the radius of 1000 meters with current location.
But I'm not getting how to drag the radius circle.
-(void)viewDidAppear:(BOOL)animated
{
if(![CLLocationManager locationServicesEnabled])
{
NSLog(#"You need to enable location services to use this app");
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Enable Location Services" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
return;
}
if(self.locationManager==nil)
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.pausesLocationUpdatesAutomatically=NO;
NSString *version = [[UIDevice currentDevice] systemVersion];
if([version floatValue] > 7.0f)
{
if ([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)])
{
[self.locationManager requestAlwaysAuthorization];
}
}
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter=50.0f;
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
newLocation = locations.lastObject;
coordinate = [newLocation coordinate];
NSLog(#"%f %f",coordinate.latitude,coordinate.longitude);
MKCoordinateRegion r= MKCoordinateRegionMakeWithDistance(coordinate, 400, 400);
self.mapView.region=r;
[self.mapView setCenterCoordinate:coordinate];
Annotation *annot=[[Annotation alloc]initWithTitle:#"My Location" AndCoordinate:coordinate];
[self.mapView addAnnotation:annot];
MKCircle *circle = [MKCircle circleWithCenterCoordinate:coordinate radius:1000];
circle.title = #"";
[self.mapView addOverlay:circle];
}
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
if ([overlay isKindOfClass:[MKCircle class]])
{
MKCircleRenderer *circleView = [[MKCircleRenderer alloc] initWithCircle:overlay];
circleView.strokeColor=[UIColor blackColor];
circleView.lineWidth=1.2;
circleView.alpha=1;
return circleView;
}
return nil;
}
You can implement Apple Bread crumb class for implementing route drawing.
Please check this link: https://developer.apple.com/library/archive/samplecode/Breadcrumb/Introduction/Intro.html
Related
I have made one demo for getting Current Location.
I have used .GPX file for my current Location.
I have used Delegates method of CLLocation Method.
I have Also use Key "Privacy - Location When In Use Usage Description" in my plist file.
I know this question already asked so many time but could not able to get result.
code is
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
#property (nonatomic,assign)CLLocationCoordinate2D cordinateLocation;
#property (nonatomic,strong)MKPointAnnotation *point;
#property (nonatomic,weak)IBOutlet MKMapView *mapView;
#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];
locationManager.delegate = self;
self.mapView.delegate = self;
[self updateCurrentLocation];
}
- (void)updateCurrentLocation {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
//-(void)getCurrentLocation
//{
// [locationManager requestWhenInUseAuthorization];
// locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// [locationManager startUpdatingHeading];
// [locationManager startUpdatingLocation];
//
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertController *errorAlert =[UIAlertController alertControllerWithTitle:#"Error" message:#"error reported" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertStyle = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[errorAlert addAction:alertStyle];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
CLLocation *updatedLocation = [locations lastObject];
if(updatedLocation != nil)
{
self.cordinateLocation=CLLocationCoordinate2DMake(updatedLocation.coordinate.latitude, updatedLocation.coordinate.longitude);
[manager stopUpdatingLocation];
[self setCurrentLocationFocus];
}
else{
NSLog(#"Can't access desire location");
}
}
-(void)setCurrentLocationFocus{
MKCoordinateRegion region;
region.center = self.cordinateLocation;
//Adjust span as you like
MKCoordinateSpan span;
span.latitudeDelta = 1;
span.longitudeDelta = 1;
region.span = span;
[self.mapView setRegion:region animated:YES];
///Drop the pin on Current Locatio ////
self.point = [[MKPointAnnotation alloc] init];
self.point.coordinate = self.cordinateLocation;
self.point.title = #"FlockStation";
self.point.subtitle = #"It Department";
[self.mapView addAnnotation:self.point];
//set a new camera angle
MKMapCamera *newCamera=[[MKMapCamera alloc] init];
[newCamera setCenterCoordinate:self.cordinateLocation];
[newCamera setPitch:60.0]; ///For zooming purpose///
[newCamera setHeading:90]; ///For Compass Purpose ///
[newCamera setAltitude:100.0]; ///On which height you want to see your map ///
[self.mapView setCamera:newCamera animated:YES];
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:#"NewViewController"];
[self presentViewController:viewController animated:YES completion:nil];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
// self.updatedHeading.text = [NSString stringWithFormat:#"%f",newHeading.magneticHeading];
}
Help Me guys not able to get location.Because delegates method is not calling.
Every Time it called this method.
- (void)locationManager:(CLLocationManager *)manager didFailWithError:`(NSError *)error
You need to check permission of location. then after you can call the delegate methods.
- (void)viewDidLoad {
[super viewDidLoad];
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[locationManager requestWhenInUseAuthorization];
}
if ([CLLocationManager locationServicesEnabled]){
NSLog(#"Location Services Enabled");
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
alert = [[UIAlertView alloc] initWithTitle:#"Permission Denied"
message:#"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation = newLocation;
txtlocations.text = [NSString stringWithFormat:#"%f & %f",currentLocation.coordinate.latitude, currentLocation.coordinate.longitude];
}
Tried with your code with little changes and its working fine.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self updateCurrentLocation];
}
- (void)updateCurrentLocation {
if([CLLocationManager locationServicesEnabled] &&
[CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager requestWhenInUseAuthorization];
[locationManager startMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
// show the map
} else {
// show error
}
}
I want to track the location of my ios device and notify in the app if it crosses certain kilometres.Suppose I want to notify if it crosses 1 km from current location of device. Please help I am new in iOS programming.
I am able to fetch the current location.
Please help.
Here what I am able to do.
- (void)viewDidLoad
{
[super viewDidLoad];
self.mapView.delegate=self;
// Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLLocationAccuracyBestForNavigation;//constant update of device location
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
[self.locationManager startUpdatingLocation];
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
self.userLocation = userLocation;
MKCoordinateSpan coordinateSpan; coordinateSpan.latitudeDelta = 0.3f; coordinateSpan.longitudeDelta = 0.3f;
MKCoordinateRegion regionToShow; regionToShow.center = userLocation.coordinate; regionToShow.span = coordinateSpan;
[self.mapView setRegion:regionToShow animated:YES];
MKPointAnnotation *point=[[MKPointAnnotation alloc]init];
point.coordinate=userLocation.coordinate;
point.title=#"where Am I";
point.subtitle=#"YOU are Here";
[self.mapView addAnnotation:point];
}
self.currentLocation must be an object of CLLocation.
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
CLLocationDistance dist = [self.currentLocation distanceFromLocation:userLocation.location];
if (dist == 1000.0) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Title" message:[NSString stringWithFormat:#"Message : you moved %.2f", dist] preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// your code on OK click
}]];
[self presentViewController:alert animated:TRUE completion:^{ }];
}
self.currentLocation = userLocation.location;
self.userLocation = userLocation;
}
I am new to IOS i need to show default location with my latitude and longitude(12.940358, 80.208647).
with annotation pin.
.h file:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface Map_view : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate>{
CLLocationManager *locationmgr;
CLGeocoder *geocode;
CLPlacemark *placemark;
}
#property(nonatomic,retain)IBOutlet MKMapView *map11;
.m file:
#synthesize map11;
I don't no where to put my latitude and longitude and how to use please help me.
If you want to show your location with your lat & long with Annotation With Name.
Use this code.
- (void)viewDidLoad {
[super viewDidLoad];
mapVW.showsUserLocation = YES;
CLLocation *loc = [[CLLocation alloc]initWithLatitude:12.940358 longitude:80.208647];
[mapVW setCenterCoordinate:loc.coordinate animated:YES];
CLGeocoder *ceo = [[CLGeocoder alloc]init];
[ceo reverseGeocodeLocation:loc
completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSString *cityName = placemark.locality;
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = CLLocationCoordinate2DMake(12.940358, 80.208647);
annotationPoint.title = locatedAt;
MKCoordinateRegion region;
MKCoordinateSpan span1;
span1.latitudeDelta = 0.08;
span1.longitudeDelta = 0.08;
region.span = span1;
region.center = annotationPoint.coordinate;
[mapVW setRegion:region animated:TRUE];
[mapVW regionThatFits:region];
[mapVW addAnnotation:annotationPoint];
[mapVW selectAnnotation:annotationPoint animated:NO];
}
];
}
For centering on user location, you can use the following code:
[mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];
For zooming on special locations, you should study how the regions (MKCoordinateRegion) are counted and work, count your latitude and longitude values for the region and display it using call:
[mapView setRegion:myRegion animated:YES];
Try the following code :
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 39.281516;
zoomLocation.longitude= -76.580806;
// 2
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
// 3
[_mapView setRegion:viewRegion animated:YES];
This code will set your region in your map.. Then follow the steps to add annotation in your map..
// Add an annotation
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = userLocation.coordinate; // Change coordinate as yours
point.title = #"Where am I?";
point.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:point];
Hope it helps..
use this code it will help you:
- (void)location
{
_locationManger =[[CLLocationManager alloc]init];
_locationManger.distanceFilter=kCLDistanceFilterNone;
_locationManger.desiredAccuracy=kCLLocationAccuracyHundredMeters;
[_locationManger startUpdatingLocation];
[map11 setMapType:MKMapTypeStandard];
[map11 setZoomEnabled:YES];
[map11 setScrollEnabled:YES];
MKCoordinateRegion region={ {0.0,0.0 },{0.0,0.0}};
region.center.latitude = 12.940358 ;
region.center.longitude = 80.208647;
region.span.longitudeDelta = 20.20f;
region.span.latitudeDelta = 20.20f;
[map11 setRegion:region animated:YES];
[map11 setDelegate:sender];
}
It will show your desired location as
add this code in your viewdidload
//self.locationManager replace it with your locationmgr
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
mapView.showsUserLocation = YES;
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
in viewdidappear add below code
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
CLLocationCoordinate2D userLocation = CLLocationCoordinate2DMake( self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude);
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
[annotation setCoordinate:userLocation];
[annotation setTitle:#"Your Location"];
[self.mapView addAnnotation:annotation];
//always show the name of annotation
[self.mapView selectAnnotation:annotation animated:YES];
//location 1
CLLocationCoordinate2D loc1Coord = CLLocationCoordinate2DMake(18.998250, 72.848734);//add your latitude and longitude here
MKPointAnnotation *annotation1 = [[MKPointAnnotation alloc] init];
[annotation1 setCoordinate:loc1Coord];
[annotation1 setTitle:#"title"];
[annotation1 setSubtitle:#"subtitle"];
[self.mapView addAnnotation:annotation1];
}
add this methods
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"loc"];
annotationView.canShowCallout = YES;
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
return annotationView;
}
Thats it, you can see your latitude and longitude in the map.Let me know if it is working or not?
first You have to set DELEGATE
and Import following in your .h file
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
after that make a property
#property(retain, nonatomic) CLLocationManager *locationManager;
and in ViewDidLoad
mapview.delegate = self;
and then You can do like belew
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
// Add an annotation
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = userLocation.coordinate;
point.title = #"Where am I?";
point.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:point];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - to get User Current Location.
- (void)getUserLocation{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
if([self getDeviceOSVersion].integerValue >= 8) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
}
-(NSString *)getDeviceOSVersion{
return [NSString stringWithFormat:#"%#",[UIDevice currentDevice].systemVersion];
}
#pragma mark - CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
UIAlertController *errorAlert = [UIAlertController alertControllerWithTitle:#"ERROR" message:#"There was an error retrieving your location"preferredStyle:UIAlertControllerStyleAlert ];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[errorAlert dismissViewControllerAnimated:YES completion:nil];
}];
[errorAlert addAction:ok];
[self presentViewController:errorAlert animated:YES completion:nil];
NSLog(#"Error: %#",error.description);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *currentLocation = [locations lastObject];
//currentLocation.coordinate.longitude = currentLocation.coordinate.longitude ;
// latitude = currentLocation.coordinate.latitude;
[self.locationManager stopUpdatingLocation];
}
I tired to get indexpath of my custom annotation ,
I use this code for get my indexpath
NSUInteger index =[mapView.annotations indexOfObject:view.annotation];
its not really working because in my map, i got right lat and lang but not get the true data of pinview
pusingpalagw is my subclass
here is my code:
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
// [(UIImageView *)view.leftCalloutAccessoryView setImageWithURL:[NSURL URLWithString:self.content.MERCHANT_IMAGE] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
//if ([view.annotation isKindOfClass:[pusingpalagw class]]) {
// pusingpalagw *annot = view.annotation;
//NSInteger index = [self.arrayOfAnnotations indexOfObject:annot];
NSUInteger index =[mapView.annotations indexOfObject:view.annotation];
if (!self.content) {
pusingpalagw *calloutView = [[pusingpalagw alloc] initWithFrame:CGRectMake(0.0, 0.0, 242.0, 57.0)];
self.content12 = [self.listContent objectAtIndex:index];
calloutView.titleLabel.text = self.content12.MERCHANT_NAME;
calloutView.subtitleLabel.text = self.content12.MERCHANT_NAME;
//UIView *rating2 = (UIView*)[cell2 viewWithTag:110];
_starRating = [[EDStarRating alloc]initWithFrame:CGRectMake(calloutView.viewRating.frame.origin.x-15, calloutView.viewRating.frame.origin.y,80,20)];
_starRating.backgroundColor = [UIColor clearColor];
self.starRating.starImage = [UIImage imageNamed:#"kuningstarkosong"];
self.starRating.starHighlightedImage = [UIImage imageNamed:#"kuningstarfull"] ;
_starRating.maxRating = 5.0;
_starRating.delegate = self;
_starRating.horizontalMargin = 15.0;
_starRating.editable=NO;
_starRating.rating= [self.content12.MERCHANT_RATTING floatValue];
_starRating.displayMode=EDStarRatingDisplayHalf;
[_starRating setNeedsDisplay];
[calloutView.viewRating addSubview:_starRating];
NSLog(#"keluarbintang%#",_starRating);
NSURL *url = [NSURL URLWithString:self.content12.MERCHANT_IMAGE];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *abs = [UIImage imageWithData:imageData];
[calloutView.imageMap setImage:abs];
//[calloutView.buttonDetail setTitle: #"Post" forState: UIControlStateNormal];
UIButton *buttonAja = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, calloutView.frame.size.width, calloutView.frame.size.height)];
[buttonAja setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//[buttonAja setTitle: #"Post" forState: UIControlStateNormal];
buttonAja.titleLabel.font = [UIFont systemFontOfSize:13.0];
[buttonAja addTarget:self action:#selector(goDetail:) forControlEvents:UIControlEventTouchUpInside];
[calloutView addSubview:buttonAja];
calloutView.center = CGPointMake(CGRectGetWidth(view.bounds) / 2.0, 0.0);
[view addSubview:calloutView];
}
//To get permission
if([CLLocationManager locationServicesEnabled]){
NSLog(#"Location Services Enabled");
if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
alert = [[UIAlertView alloc] initWithTitle:#"App Permission Denied"
message:#"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
//To set user Location
- (void)viewDidLoad
{
[super viewDidLoad];
self.mapView.showsUserLocation=YES;
self.mapView.delegate = self;
[self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
}
...
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion mapRegion;
mapRegion.center = mapView.userLocation.coordinate;
mapRegion.span.latitudeDelta = 0.2;
mapRegion.span.longitudeDelta = 0.2;
[mapView setRegion:mapRegion animated: YES];
}
Permission for IOS 8 Or Later :-
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
if ([CLLocationManager locationServicesEnabled] )
{
if (self.locationManager == nil )
{
self.locationManager.delegate = (id)self;
self.locationManager = [[CLLocationManager alloc] init];
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER)
{
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
#endif
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kDistanceFilter; //kCLDistanceFilterNone// kDistanceFilter;
}
[self.locationManager startUpdatingLocation];
self.mapViewForPlace.showsUserLocation = YES;
[self.locationManager setDelegate:self];
NSLog(#"Location Title Is: %#", self.mapViewForPlace.userLocation.title);
}
Add info.plist NSLocationWhenInUseUsageDescription type of string.
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
#endif
self.mapViewForPlace.showsUserLocation = YES;
self.currentLocation = [locations lastObject];
// here we get the current location
NSLog(#"Current Locations : %#",self.currentLocation);
// CLLocation* location = (CLLocation*)locations.lastObject;
// Use Apple's Geocoder to figure the name of the place
CLGeocoder* geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:self.currentLocation completionHandler: ^(NSArray* placemarks, NSError* error) {
if (error != nil) {
NSLog(#"Error in geo coder: %#", error);
}
else {
if (placemarks.count == 0) {
NSLog(#"The address couldn't be found");
}
else {
// Get nearby address
CLPlacemark* placemark = placemarks[0];
// Get the string address and store it
NSString* locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
//location.name = locatedAt;
currentLocationNameIs=locatedAt;
NSLog(#"The address is: %#", locatedAt);
}
}
}];
}
- (void) locationManager:(CLLocationManager *) manager didUpdateToLocation:(CLLocation *) newLocation fromLocation:(CLLocation *) oldLocation
{
self.currentLocation = newLocation;
self.mapViewForPlace.showsUserLocation = YES;
NSLog(#"New location Cordinate : %f %f",self.mapViewForPlace.userLocation.coordinate.latitude,self.mapViewForPlace.userLocation.coordinate.longitude);
[self.locationManager stopUpdatingLocation];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
// If it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
// Handle any custom annotations.
if ([annotation isKindOfClass:[MKPointAnnotation class]])
{
// Try to dequeue an existing pin view first.
MKAnnotationView *pinView = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:#"CustomPinAnnotationView"];
if (!pinView)
{
// If an existing pin view was not available, create one.
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"CustomPinAnnotationView"];
//pinView.animatesDrop = YES;
pinView.canShowCallout = YES;
pinView.image = [UIImage imageNamed:#"facebook30.png"];
pinView.calloutOffset = CGPointMake(0, 32);
// Add a detail disclosure button to the callout.
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
pinView.rightCalloutAccessoryView = rightButton;
// Add an image to the left callout.
UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"facebook30.png"]];
pinView.leftCalloutAccessoryView = iconView;
} else {
pinView.annotation = annotation;
}
return pinView;
}
return nil;
}
I am working on iOS app using Google Map SDK. I try to set on the CLLocationManager to get location of my device for 10 seconds and right bottom button to get my location instantly. When it comes to the implementation, the app show no response to initiate the method startUpdatingLocation to get my location. Would you please tell me the way to use locationManager to finish the aim?
The following is my working :
-(bool)isNetworkAvailable
{
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityRef address;
address = SCNetworkReachabilityCreateWithName(NULL, "www.apple.com" );
Boolean success = SCNetworkReachabilityGetFlags(address, &flags);
CFRelease(address);
bool canReach = success
&& !(flags & kSCNetworkReachabilityFlagsConnectionRequired)
&& (flags & kSCNetworkReachabilityFlagsReachable);
return canReach;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// [self getTime];
if (![CLLocationManager locationServicesEnabled]) {
NSLog(#"Please enable location services");
return;
}
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
NSLog(#"Please authorize location services");
return;
}
if([self isNetworkAvailable]){
NSLog(#"connected ");
}else {
NSLog(#"not connected ");
}
CarArray = [[NSMutableArray alloc] init];
GMSMarker *marker = [[GMSMarker alloc] init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
float latitide = [defaults floatForKey:#"lati"];
float longitude = [defaults floatForKey:#"longi"];
NSString *desp = [defaults objectForKey:#"desp"];
NSLog(#"assadsd arrived map");
if(latitide!=0.00&&longitude!=0.00) {
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(latitide, longitude);
marker.position = CLLocationCoordinate2DMake(position.latitude, position.longitude);
camera = [GMSCameraPosition cameraWithLatitude:latitide longitude:longitude zoom:12];
}else{
camera = [GMSCameraPosition cameraWithLatitude:22.2855200 longitude:114.1576900 zoom:12];
marker.position = CLLocationCoordinate2DMake(22.2855200, 114.1576900);
}
if(desp.length > 0 ){
marker.title = desp;
}
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest ;
self.locationManager.distanceFilter = 5.0f;
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
marker.snippet = #"HK";
marker.map = mapView_;
mapView_.mapType = kGMSTypeSatellite;
mapView_.delegate = self;
dispatch_async(dispatch_get_main_queue(), ^{
mapView_.myLocationEnabled = YES;
});
mapView_.settings.compassButton = YES;
mapView_.settings.myLocationButton = YES;
[mapView_ addObserver:self
forKeyPath:#"myLocation"
options:NSKeyValueObservingOptionNew
context:NULL];
self.view = mapView_;
[self.locationManager startUpdatingLocation];
NSLog(#"assadsd configured d map");
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
NSLog(#"Please authorize location services");
return;
}
NSLog(#"CLLocationManager error: %#", error.localizedFailureReason);
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"application_name", nil) message:NSLocalizedString(#"location_error", nil) delegate:nil cancelButtonTitle:NSLocalizedString(#"ok", nil) otherButtonTitles:nil];
[errorAlert show];
return;
}
-(void) handleDoubleTap {
NSLog(#"location double tap ");
}
-(UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
// CLLocationDelegate
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations{
// Optional: check error for desired accuracy
CLLocation* location = [locations lastObject];
NSLog(#"location x : %f" , location.coordinate.longitude);
NSLog(#"location y : %f" , location.coordinate.latitude);
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
[manager allowDeferredLocationUpdatesUntilTraveled:CLLocationDistanceMax timeout:10];
if (markera == nil) {
markera = [[GMSMarker alloc] init] ;
markera.position = CLLocationCoordinate2DMake( location.coordinate.latitude , location.coordinate.longitude );
markera.groundAnchor = CGPointMake(0.5f, 0.97f); // Taking into account walker's shadow
markera.map = mapView_;
}else {
markera.position = location.coordinate;
}
GMSCameraUpdate *move = [GMSCameraUpdate setTarget:location.coordinate zoom:17];
[mapView_ animateWithCameraUpdate:move];
}