I am trying to show the mkmapview to the users current location. They will display only city name. But they are not specify the exact users current location. I want to display the users exact location. Please give me any idea how to zoom the users current location.
GPSlocationAPPDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.locationManager=[[CLLocationManager alloc]init];
if([CLLocationManager locationServicesEnabled])
{
self.locationManager.delegate=self;
self.locationManager.distanceFilter=1;
[self.locationManager startUpdatingLocation];
}
self.viewController = [[AnimationViewController alloc] initWithNibName:#"AnimationViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
double miles=12.0;
double scalingFactor= ABS( cos(2 * M_PI * newLocation.coordinate.latitude /360.0) );
MKCoordinateSpan span;
span.latitudeDelta=miles/69.0;
span.longitudeDelta=miles/(scalingFactor*69.0);
MKCoordinateRegion region;
region.span=span;
region.center=newLocation.coordinate;
[self.viewController.mapView setRegion:region animated:YES];
self.viewController.mapView.showsUserLocation=YES;
}
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLLocationAccuracyKilometer;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
coordinate = [location coordinate];
latitude = coordinate.latitude;
longitude = coordinate.longitude;
mapview.region = MKCoordinateRegionMakeWithDistance(coordinate, 10000, 10000);
Other option to get the user location is adding observer to mapview in viewDidLoad method like this
-(void)viewDidLoad
{
[super viewDidLoad]
//register the observer
[self.mapView.userLocation addObserver:self
forKeyPath:#"location"
options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
context:NULL];
}
and whenever this observer will call just do this
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
MKCoordinateRegion region;
region.center = self.mapView.userLocation.coordinate;
//Adjust span as you like
MKCoordinateSpan span;
span.latitudeDelta = 1;
span.longitudeDelta = 1;
region.span = span;
[self.mapView setRegion:region animated:YES];
}
Steps:
1) In ViewWillAppear
[self.mapView setMapType:MKMapTypeStandard];
[self.mapView setZoomEnabled:YES];
[self.mapView setScrollEnabled:YES];
[self.mapView setDelegate:self];
locationManager = [[CLLocationManager alloc] init] ;
BOOL locationAllowed = [CLLocationManager locationServicesEnabled];
if (locationAllowed == NO){
//GPS DISABLED.
}
else{
if(IS_IOS8_OR_LATER){
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
2) Declare MKCoordinateRegion In your viewController.h
MKCoordinateRegion region;
3) In didUpdateToLocation:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"current Latitude is %f",newLocation.coordinate.latitude);
NSLog(#"current Longitude is %f",newLocation.coordinate.longitude);
region.span.longitudeDelta *= 0.05;
region.span.latitudeDelta *= 0.05;
region.center.latitude = newLocation.coordinate.latitude;
region.center.longitude = newLocation.coordinate.longitude;
[self.mapView setRegion:region animated:YES];
[locationManager stopUpdatingLocation];
}
You can set latitudeDelta and longitudeDelta value to customised your zooming details. Increase means zoom and decrease means zoom out.
First in set showsUserLocation in viewDidLoad: like bellow..
mapView.showsUserLocation = YES;
and then in didUpdateToLocation: set Region with span with new location like bellow...
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
MKCoordinateRegion region;
region.center = newLocation.coordinate;
MKCoordinateSpan span;
span.latitudeDelta=0.04;
span.longitudeDelta=0.04;
region.span=span;
region.center = currentLocation;
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region]; // Set `regionThatFits:` with `region` like bellow...
}
self.mapView.showsUserLocation = YES;
MKCoordinateRegion region;
region.center = self.mapView.userLocation.coordinate;
MKCoordinateSpan span;
span.latitudeDelta = 20;
span.longitudeDelta = 20;
region.span = span;
[self.realtorMapView setRegion:region animated:YES];
Related
Trying to track user location using MKMapView.
Using below code
-(void)viewDidLoad{
myMapView.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
arrDate = [[NSMutableArray alloc]init];
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
[self.locationManager requestWhenInUseAuthorization];
}
#endif
myMapView.showsUserLocation = YES;
[myMapView setMapType:MKMapTypeStandard];
[myMapView setZoomEnabled:YES];
[myMapView setScrollEnabled:YES];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//[self.locationManager startUpdatingLocation];
//View Area
MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = self.locationManager.location.coordinate.latitude;
region.center.longitude = self.locationManager.location.coordinate.longitude;
region.span.longitudeDelta = 0.005f;
region.span.longitudeDelta = 0.005f;
[myMapView setRegion:region animated:YES];
}
-(IBAction)start{
if (self.locationManager == nil) {
self.locationManager = [[CLLocationManager alloc] init];
}
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.activityType = CLActivityTypeFitness;
// Movement threshold for new events.
self.locationManager.distanceFilter = 8; // meters
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locationss
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(myMapView.userLocation.location.coordinate, 900, 900);
[myMapView setRegion:[myMapView regionThatFits:region] animated:YES];
}
Problem
when i want zoom out/in or moving map to other location while updating the location. it is not working and moving back to present user location.
how can i solve this problem ?
In your #interface add a control flag:
#property (nonatomic, readwrite) BOOL userScrolling;
In your #implementation add/override these bits of code:
- (void)viewDidLoad {
[super viewDidLoad];
// Other set-up code here...
// Used for detecting manual panning/zooming of the map
UIPanGestureRecognizer* panRec = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(didManipulateMap:)];
UIPinchGestureRecognizer* pinchRec = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(didManipulateMap:)];
[panRec setDelegate:self];
[pinchRec setDelegate:self];
[myMapView addGestureRecognizer:panRec];
[myMapView addGestureRecognizer:pinchRec];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
- (void)didManipulateMap:(UIGestureRecognizer*)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateBegan)
_userScrolling = YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locationss {
if (!_userScrolling) {
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(myMapView.userLocation.location.coordinate, 900, 900);
[myMapView setRegion:[myMapView regionThatFits:region] animated:YES];
}
}
- (IBAction)locateMeButtonPressed:(id)button {
_userScrolling = NO;
[self.locationManager startUpdatingLocation];
}
That should do it.
I tried to search lot for this, but i didn't get exact answer what i want.
my question is
Can I send user's current location to server when app is running as well as in background.
For example: In my app i want to store the user's current location in every 2min and then send his current location to server.as well as if user move 50 meters within less than 2min then also.
How can i do this ? Can i send location updates to the server in background mode as well as foreground mode? if yes then how?
I tried like following way:
self.locations = [[NSMutableArray alloc] init];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = 10;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[self.locationManager requestAlwaysAuthorization];
[self.locationManager startUpdatingLocation];
...
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
// Add another annotation to the map.
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = newLocation.coordinate;
[self.map addAnnotation:annotation];
// Also add to our map so we can remove old values later
[self.locations addObject:annotation];
// Remove values if the array is too big
while (self.locations.count > 1)
{
annotation = [self.locations objectAtIndex:0];
[self.locations removeObjectAtIndex:0];
// Also remove from the map
[self.map removeAnnotation:annotation];
}
if (UIApplication.sharedApplication.applicationState == UIApplicationStateActive)
{
// determine the region the points span so we can update our map's zoom.
double maxLat = -91;
double minLat = 91;
double maxLon = -181;
double minLon = 181;
for (MKPointAnnotation *annotation in self.locations)
{
CLLocationCoordinate2D coordinate = annotation.coordinate;
if (coordinate.latitude > maxLat)
maxLat = coordinate.latitude;
if (coordinate.latitude < minLat)
minLat = coordinate.latitude;
if (coordinate.longitude > maxLon)
maxLon = coordinate.longitude;
if (coordinate.longitude < minLon)
minLon = coordinate.longitude;
}
MKCoordinateRegion region;
region.span.latitudeDelta = (maxLat + 90) - (minLat + 90);
region.span.longitudeDelta = (maxLon + 180) - (minLon + 180);
_latitude1=[NSString stringWithFormat:#"Latitude:%f",newLocation.coordinate.latitude];
_longitude1=[NSString stringWithFormat:#"Longitude:%f",newLocation.coordinate.longitude];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.fetchtokenString1 = [NSString stringWithString:_latitude1];
appDelegate.fetchedriveridString1 = [NSString stringWithString:_longitude1];
NSLog(#"%#",_latitude1);
NSLog(#"%#",_longitude1);
// the center point is the average of the max and mins
region.center.latitude = minLat + region.span.latitudeDelta / 2;
region.center.longitude = minLon + region.span.longitudeDelta / 2;
// Set the region of the map.
[self.map setRegion:region animated:YES];
}
else
{
NSLog(#"App is backgrounded. New location is %#", newLocation);
}
Thanks in advance..
Check this when your app is running in foreground.
How can I get current location from user in iOS
Check this to send location when your app is in background.
Sending Latitude and Longitude to Server when app is in background
after getting latitude and longitude, send by using AFNetworking framework.
OR
If you need from scratch if you dont know how to get location then follow the below steps to get latitude and longitude.
Add this below two string types in your info.pList
Then add CoreLocation Framework in your project.
Import it to your ViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController<CLLocationManagerDelegate>
#property(nonatomic, retain) CLLocationManager *locationManager;
#end
Then do below one in your ViewController.m
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
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];
}
-(void)viewWillAppear:(BOOL)animated {
NSLog(#"latitude: %f, longitude: %f",self.locationManager.location.coordinate.latitude,self.locationManager.location.coordinate.longitude);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
Log will show the latitude and longitude.
I've cannot change the camera's value in the Google Maps API. So that it displays the users position as soon as you open the app, using CoreLocation and passing those values into the camera. I've had a look at some tutorials online, but I haven't managed to solve it yet.
I've tried to make a method that observes when the GPS coordinates have been found and then pass them to the camera. But it still shows 0,0.
#implementation HMSBViewController{
CLLocationManager *_locationManager;
}
#synthesize mapView;
- (NSString *)deviceLocation
{
NSString *theLocation = [NSString stringWithFormat:#"latitude: %f longitude: %f", _locationManager.location.coordinate.latitude, _locationManager.location.coordinate.longitude];
return theLocation;
}
- (void)viewDidLoad
{
mapView.delegate = self;
//[mapView addObserver:self forKeyPath:#"myLocation" options:0 context:nil];
//mapView.settings.myLocationButton = YES;
mapView.myLocationEnabled = YES;
_locationManager = [[CLLocationManager alloc] init];
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; // Setting the accuracy to the best possible
if([_locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
[_locationManager requestAlwaysAuthorization];
}
[_locationManager startUpdatingLocation];
}
- (void)viewWillAppear{
[mapView addObserver:self forKeyPath:#"myLocation" options:0 context:nil];
}
- (void)loadView{
CLLocation *myLocation = mapView.myLocation;
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(myLocation.coordinate.latitude, myLocation.coordinate.longitude);
marker.title = #"Current Location";
marker.map = mapView;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:_locationManager.location.coordinate.latitude
longitude:_locationManager.location.coordinate.longitude
zoom:1];
mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = mapView;
NSLog(#"%f, %f", _locationManager.location.coordinate.latitude, _locationManager.location.coordinate.longitude);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if([keyPath isEqualToString:#"myLocation"]) {
CLLocation *location = [object myLocation];
CLLocationCoordinate2D target = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
[mapView animateToLocation:target];
#try {
[mapView removeObserver:self forKeyPath:#"myLocation"];
} #catch(id exception){
;
}
}
}
Any suggestions would be much appreciated!
You need to set the locationManager delegate and then use the delegate method
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
to retrieve the location. Once you have the location, then call your map function to populate Google
I have been trying to fake my location in the iOS simulator but the methods I have been reading about are not working. I have used the debugger to set my fake location, and have made a custom location in Debug->Location->Custom Location, yet I still log 0.000 0.000 for lat and long.
I'm using this code to find current location.
- (IBAction)currentLocationButtonPressed:(UIButton *)sender
{
//Search for pubs and bars in current location.
//Push to tableViewController
NSLog(#"current location Pressed.");
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyBest; // Best accuracy
[locationManager startUpdatingLocation];
NSLog(#"%#",[self deviceLocation]);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSLog(#"Latitude: %f Longitude: %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
}
}
- (NSString *)deviceLocation {
return [NSString stringWithFormat:#"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
}
The delegate is set and I am requesting authorization.
- (void)viewDidLoad {
[super viewDidLoad];
searchLocationTextField.delegate = self;
locationManager.delegate = self;
locationManager = [[CLLocationManager alloc]init];
[locationManager requestWhenInUseAuthorization]; // For foreground access
[locationManager requestAlwaysAuthorization]; // For background access
}
Set locationManager delegate to after allocating it.
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
locationManager:didUpdateToLocation:fromLocation: delegate method is deprecated, use locationManager:didUpdateLocations: instead.
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currentLocation = [locations lastObject];
NSLog(#"Latitude: %f Longitude: %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
}
I want to show the current location of the user on the map and zoom on to it.
I tried as follows:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
NSLog(#"Init MapViewController");
[self initMap];
}
return self;
}
-(void) initMap
{
_mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
_mapView.delegate = self;
_mapView.showsUserLocation = YES;
[self.view addSubview:_mapView];
CLLocationCoordinate2D currentLocation;
currentLocation.latitude = _mapView.userLocation.coordinate.latitude;
currentLocation.longitude= _mapView.userLocation.coordinate.longitude;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(currentLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
[_mapView setRegion:viewRegion animated:YES];
}
Then in the simulator it shows a location in the sea. I set the location to London in the simulator.
Just do This:
#property (strong, nonatomic) CLLocationManager *locationManager;
In viewdidload:
self.locationManager = [[CLLocationManager alloc] init] ;
self.locationManager.delegate = (id)self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation ;
[self.locationManager setDistanceFilter:10.0f] ;
[self.locationManager startUpdatingLocation];
And in your location manager
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
[self.locationManager stopUpdatingLocation];
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = YourMapView.userLocation.location.coordinate.latitude;
zoomLocation.longitude= YourMapView.userLocation.location.coordinate.longitude;
// 2
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*1609.344, 0.5*1609.344);
// 3
[YourMapView setRegion:viewRegion animated:YES];
}
I needed to listen to changes for the user location. Because in the view didload the location isn't known.
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
MKCoordinateRegion region;
region.center = self.mapView.userLocation.coordinate;
MKCoordinateSpan span;
span.latitudeDelta = 1; // Change these values to change the zoom
span.longitudeDelta = 1;
region.span = span;
[self.mapView setRegion:region animated:YES];
}
and this in the viewdidload:
[self.mapView.userLocation addObserver:self
forKeyPath:#"location"
options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
context:nil];