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];
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'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 am using google map api in my app and I want when run my code show me my location automatic in view.
I write my code and run but my code not working and I understand that my location method don't save my coordinate location in two variable.why???
please guide me about it.
#implementation ViewController
{
double latitudes;
double longitudes;
CLLocationManager *locationManager;
GMSMapView *mapView_;
}
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[self GetMyLocation];
// Create a GMSCameraPosition that tells the map to display the
//my friend I don't know why my two variable (latitudes,longitudes)
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitudes longitude:longitudes zoom:14];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.myLocationEnabled = YES;
[mapView_ setMapType:kGMSTypeNormal];
}
- (void) GetMyLocation{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitudes = currentLocation.coordinate.longitude;
latitudes = currentLocation.coordinate.latitude;
}
}
#end
#implementation ViewController
{
double latitudes;
double longitudes;
CLLocationManager *locationManager;
GMSMapView *mapView_;
}
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[self GetMyLocation];
// Create a GMSCameraPosition that tells the map to display the
//my friend I don't know why my two variable (latitudes,longitudes)
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:0 longitude:0 zoom:14];
mapView_ = [GMSMapView mapWithFrame:self.view.frame camera:camera];
mapView_.myLocationEnabled = YES;
[mapView_ setMapType:kGMSTypeNormal];
[self.view addSubView:mapView_];
}
- (void) GetMyLocation{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitudes = currentLocation.coordinate.longitude;
latitudes = currentLocation.coordinate.latitude;
}
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:currentLocation.coordinate.longitude longitude:currentLocation.coordinate.latitude zoom:14];
[mapView_ animateToCameraPosition:camera];
}
#end
I don´t understand why the delegate is not sent the message mapView:didUpdateUserLocation:
In viewDidLoad i ask the mapView to startUpdating with setShowUserLocation:YES. But it´s like it never accomplish this.
Any suggestions?
#import "TrackViewController.h"
#import "MainWindowViewController.h"
#class MainWindowViewController;
#implementation TrackViewController
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
NSLog(#"Init trackcontriller");
self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self){
locationManager = [[CLLocationManager alloc]init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
}
return self;
}
-(IBAction) back:(id)sender{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void) findLocation;
{
NSLog(#"findlocation");
[locationManager startUpdatingLocation];
}
-(void) foundLocation:(CLLocation *)loc
{
NSLog(#"Foundlocation");
CLLocationCoordinate2D coord = [loc coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 100, 100);
[worldView setRegion:region animated:YES];
[locationManager stopUpdatingLocation];
}
-(void)viewDidLoad
{
NSLog(#"viewDidLoad");
[worldView setShowsUserLocation:YES];
[worldView setMapType:MKMapTypeHybrid];
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
NSLog(#"mapview didupdateUserlocation");
CLLocationCoordinate2D loc = [userLocation coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 200, 200);
[worldView setRegion:region animated:YES];
}
-(void)dealloc
{
[locationManager setDelegate:nil];
}
- (void) locationManager:(CLLocationManager *) manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
// Deprecated i know
{
NSLog(#"Locationanager didupdate tolocation from location");
NSTimeInterval t = [[newLocation timestamp] timeIntervalSinceNow];
if(t<-180){
return;
}
[self foundLocation:newLocation];
}
-(void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(#"Could not find location: %#", error);
}
#end
I think that you mix up the location services of CLLocationManager and of MapView. mapView:didUpdateUserLocation: is a delegate method of MKMapView. If you just need this method to update the user's location, you don't have to instantiate a CLLocationManager. Instead you simply say, as you did, [worldView setShowsUserLocation:YES];
But of course, your object that implements mapView:didUpdateUserLocation: has to be the delegate of you MKMapView object, here of worldView, not of a CLLocationManager object!
So my suggestion is to set your TrackViewController object as the delegate of your MKMapView object, i.e. of worldView, and delete the code related to the CLLocationManager.
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];