MapView not zooming to user location - iphone

My mapview is not zooming to my user location. Please can you point out the error:
- (void)viewDidLoad {
[super viewDidLoad];
mapView = [[MKMapView alloc] init];
mapView.showsUserLocation = YES;
mapView.mapType = MKMapTypeHybrid;
mapView.delegate = self;
[self performSelector:#selector(startupZoom) withObject:nil afterDelay:1.25];
}
- (void)startupZoom {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.2;
span.longitudeDelta=0.2;
CLLocationCoordinate2D location=mapView.userLocation.coordinate;
location.latitude=mapView.userLocation.coordinate.latitude;
location.longitude=mapView.userLocation.coordinate.longitude;
region.span=span;
region.center=location;
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
NSLog(#"%f, %f", mapView.userLocation.coordinate.latitude, mapView.userLocation.coordinate.longitude);
}

The mapView is being created but its frame is not set and it's not being added as a subview of the view controller's view.
Change the alloc+init line to (change the dimensions as needed):
mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];
Then before the performSelector line, add this:
[self.view addSubview:mapView];
Note however that it's better to use the MKMapView's didUpdateUserLocation delegate method to zoom to the user's location instead of assuming the user location will be available after some arbitrary, fixed interval like 1.25 seconds.
For example, remove the performSelector line and implement didUpdateUserLocation:
- (void)mapView:(MKMapView *)mapView
didUpdateUserLocation:(MKUserLocation *)userLocation
{
[self startupZoom];
}
Only possible problem using the didUpdateUserLocation method is that it will be called every time the user's location changes so if you only want to zoom once on startup, you'll need to add a BOOL flag ivar and check/set it accordingly.

Related

place pin on mapview by coordinates sent from appdelegate

This takes me days..I could not make it work.
I write a method that places a pin on map as below:
- (void) SetMaps:(NSString *)Lats :(NSString *)lons;
{
if([upLo isEqualToString:#"Y"])
{
NSLog(#"setting maps:%#,%#",Lats,lons);
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
  [mapView setScrollEnabled:YES];
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = [Lats doubleValue] ;
region.center.longitude = [lons doubleValue];
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = region.center;
[self.mapView addAnnotation:point];
}
}
This method runs well if I call it in secondViewController.m in a tab bar controll application.
But, I want to call it from appdelegate.m.
So in appdelegate.m, I put
secondViewController *Gper=[[secondViewController alloc]init];
[Gper SetMaps:LAT:LON];
[Gper release];
from this NSLog(#"setting maps:%#,%#",Lats,lons); I can see the lat and lons values are correct into this method.
However, the map doesnt change to this location.
Whatelse should I do to make it showing new location?
Thanks for any help.
I feel you should learn (Objective-)C memory management and Cocoa conventions better before doing anything further. + alloc returns a new instance of your view controller class, and not the one that is currently displayed.
And begin your class names with a capital letter. And your method names with a lowercase one.

MKMapView Trouble

I am having trouble when trying to use a MKMapView. This is my first time trying to use one of these and I haven't been able to figure out how to work it. Here are the two different pieces of sample code that I used to try to get it to work and neither work:
mapView = [[MKMapView alloc] initWithFrame:CGRectMake( 0, 0, 320, 150 )];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance( CLLocationCoordinate2DMake( latitude, longitude ), metersPerMile*0.5, metersPerMile*0.5 );
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:region];
[mapView setRegion:adjustedRegion];
or
mapView = [[MKMapView alloc] initWithFrame:CGRectMake( 0, 0, 320, 150 )];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance( CLLocationCoordinate2DMake( latitude, longitude ), metersPerMile*0.5, metersPerMile*0.5 );
[mapView setRegion:region];
or
mapView = [[MKMapView alloc] initWithFrame:CGRectMake( 0, 0, 320, 150 )];
[self.mapView setRegion:MKCoordinateRegionMake(CLLocationCoordinate2DMake( latitude, longitude ), MKCoordinateSpanMake( 0.01, 0.01 ))];
all of these snippets of code do absolutely nothing for the MKMapView. Whenever the view ends up loading, it doesn't do anything and I'm just left looking at all of North America, which isn't very helpful.
If anyone can help me out with this, I would greatly appreciate it.
You haven't added map to your view.. like [self.view addSubView:mapView];
I show the user where he is by implementing – mapView:viewForAnnotation: from MKMapViewDelegate. Take a look at this:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
// If it's the user location, return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
{
MKCoordinateSpan coordinateSpan = MKCoordinateSpanMake(0.009, 0.009);
[mapView setRegion:MKCoordinateRegionMake(annotation.coordinate, coordinateSpan) animated:YES];
}
return nil;
}
If you are tying to load the MapView this will help
- (void)mapViewWillStartLoadingMap:(MKMapView *)mapView
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSLog(#"map loading...");
}

How to center map view while tracking user

I am just wondering how to center the map view as the user is vein tracked with CLLocationmanager and map kit
This is currently how I am tracking the user and updating the location etc.
- (void)viewDidLoad
{
// Initialize the TileOverlay with tiles in the application's bundle's resource directory.
// Any valid tiled image directory structure in there will do.
NSString *tileDirectory = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Tiles"];
TileOverlay *overlay = [[TileOverlay alloc] initWithTileDirectory:tileDirectory];
[map addOverlay:overlay];
// zoom in by a factor of two from the rect that contains the bounds
// because MapKit always backs up to get to an integral zoom level so
// we need to go in one so that we don't end up backed out beyond the
// range of the TileOverlay.
MKMapRect visibleRect = [map mapRectThatFits:overlay.boundingMapRect];
visibleRect.size.width /= 2;
visibleRect.size.height /= 2;
visibleRect.origin.x += visibleRect.size.width / 2;
visibleRect.origin.y += visibleRect.size.height / 2;
map.visibleMapRect = visibleRect;
// map.showsUserLocation = YES;
//location tracking
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//Show the users location.. hopefully it works with tracking.
map.showsUserLocation = YES;
[overlay release]; // map is now keeping track of overlay
}
//OverLays Topographical map
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
TileOverlayView *view = [[TileOverlayView alloc] initWithOverlay:overlay];
view.tileAlpha = 0.6;
return [view autorelease];
}
//Tracks Users location and Prints out the Lat and Lon
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
CLLocationCoordinate2D here = newLocation.coordinate;
NSLog(#"%f %f ", here.latitude, here.longitude);
}
The below method focus a particular location in the map,
//Don't forget to add this method to your header also
-(void)focusLocationInMap:(CLLocationCoordinate2D)location
{
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.01;
span.longitudeDelta=0.01;
region.span=span;
region.center=location;
[self.yourMapView setRegion:region animated:TRUE];
[self.yourMapView regionThatFits:region];
}
You could use it anywhere by passing coordinates to it,
CLLocationCoordinate2D here = newLocation.coordinate;
[self focusLocationInMap:here];
here.coordinate is not correct, should be just 'here'

User location annotation misplaced when not default

I am showing the user location in an MKMapView. I don't want the default blue circle but instead the red pin.
Therefore I implemented mapView:viewForAnnotation: and made it always return a red pin as the user's location is the only pin I will show on the map view.
When using the default blue circle the location is quite precise but when changing to the red pin it's off quite a lot. It's as if the red pin is dropped precisely and is then moved up so it does not longer show my current position.
This is my code:
- (MKAnnotationView *)mapView:(MKMapView *)_mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
NSLog(#"MapView: Annotation.");
MKPinAnnotationView *pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
[pin setPinColor:MKPinAnnotationColorRed];
[pin setAnimatesDrop:YES];
[pin setCanShowCallout:NO];
return pin;
}
I use mapView:didAddAnnotationViews: to center the map view to my current location.
- (void)mapView:(MKMapView *)_mapView didAddAnnotationViews:(NSArray *)views
{
for(MKAnnotationView *annotationView in views)
{
if(annotationView.annotation == _mapView.userLocation)
{
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.20;
span.longitudeDelta = 0.20;
CLLocationCoordinate2D location = [[_mapView userLocation] coordinate];
region.span = span;
region.center = location;
[_mapView setRegion:region animated:YES];
[_mapView regionThatFits:region];
}
}
}
Does anyone know why my annotation is no longer placed correct when using the red pin instead of the default annotation view?
Setting [pin setAnimatesDrop:NO] instead of YES solved this.

Retrieve UserLocation Coordinate with MapKit

I"m using MapKit in my application and disaply the user location with
[mapview setShowUserLocation:YES];
I want to set the region.center.latitude and region.center.longitude with the coordinate of the userLocation, how to do it?
Here is my answer, I try something like that and its working:
//inside my ViewDidLOad
locManager = [[CLLocationManager alloc] init];
[locManager setDelegate:self];
[locManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locManager startUpdatingLocation];
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D loc = [newLocation coordinate];
[maptView setCenterCoordiante:loc];
}
Much easier:
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 1500, 1500);
[mapView setRegion:region animated:YES];
}
For some reason, this didn't work for me. It's taking me to the coordinates (0.0000, 0.0000). Below is my code if you have a chance to check it out. Thanks for the help!
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
mapView.showsUserLocation=TRUE;
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
CLLocationCoordinate2D myCoord = {mapView.userLocation.location.coordinate.latitude,mapView.userLocation.location.coordinate.longitude};
[mapView setCenterCoordinate:myCoord animated:YES];
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
I think this answers your question :
Returning Mapkit Userlocation Coordinates
(uses the mapView.userLocation.location.coordinate.latitude and mapView.userLocation.location.coordinate.longitude properties )
and then inject those coordinates into the
-(void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated
of your MKMapView instance.
Using delegate:
Add Mapkit delegate: MKMapViewDelegate
Achieve method:MapView didUpdateUserLocation
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate,
500, 500);
[mapView setRegion:region animated:YES];
}
Without delegate:
[self.mapView setuserTrackingMode:MKUserTrackingModeFollow];