Zooming to users location iOS 8 MapKit Obj-C - objective-c

I have no issues displaying a users current location, but I am having trouble trying to zoom to it. I have found a few solutions from other posts here, but nothing seems to be working. Advice is appreciated as it is highly likely that I am missing something simple.
Here is what I have so far:
#import CoreLocation;
#interface ViewController () <CLLocationManagerDelegate>
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Get authorization
CLLocationManager * locationManager = [[CLLocationManager alloc] init];
// Check before requesting, otherwise it might crash older versions of ios
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
[locationManager requestWhenInUseAuthorization];
}
self.mapView.showsUserLocation = YES;
self.mapView = [[MKMapView alloc] init];
self.mapView.delegate = self;
self.mapView.scrollEnabled = YES;
self.mapView.zoomEnabled = YES;
self.mapView.userTrackingMode = YES;
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
//CLLocationCoordinate2D loc = [userLocation coordinate];
//MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 1000, 1000);
//[self.mapView setRegion:region animated:YES];
//Zoom map to users current location
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.00001;
span.longitudeDelta = 0.00001;
CLLocationCoordinate2D location = mapView.userLocation.coordinate;
region.span = span;
region.center = location;
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
}
#end

I did something like this
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
if (!self.initialLocation) {
self.initialLocation = userLocation.location;
MKCoordinateRegion mapRegion;
mapRegion.center = mapView.userLocation.coordinate;
mapRegion.span.latitudeDelta = 0.2;
mapRegion.span.longitudeDelta = 0.2;
[mapView setRegion:mapRegion animated: YES];
}
}
self.initialLocation is an instance of CLLocation. This method constantly updates the user's current location and so what I would do is check to see if it is nil, which it should be off the start and then run the code to zoom in. After the first time, self.initialLocation will never be nil.
if you would constantly like to zoom into the the user's current location...get rid of the if statement.
EDIT
Set this in your .h file for self.initialLocation
#property (strong, nonatomic) CLLocation *initialLocation;
EDIT 2
Remove this line
self.mapView = [[MKMapView alloc] init];
No need to re-initialize your IBOulet

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.

Objective C - Have only one pin at a time?

I have 2 different set of pins on top of a map view. One pin appears first and it's the user location, then when you search for a location in the search bar multiple pins appear depending on the location. I want to have one pin showing at a time. Once you search for the location the user's location pin should disappear, and once you select one of the multiple pins you searched the others should disappear.
Here's my code:
#import "UbicacionVC.h"
#import "SWRevealViewController.h"
#import <MapKit/Mapkit.h>
#import "Location.h"
#interface UbicacionVC ()
#end
#implementation UbicacionVC
#synthesize mapView;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self inicializarComponentes];
self.mapView.delegate = self;
self.searchBar.delegate = self;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)inicializarComponentes {
[self.btnContinuar.layer setCornerRadius:20.0f];
[self.btnCancelar.layer setCornerRadius:20.0f];
////
UITapGestureRecognizer *gestureMenu = [[UITapGestureRecognizer alloc] init];
[gestureMenu addTarget:self.revealViewController action:#selector(revealToggle:)];
[gestureMenu setCancelsTouchesInView:NO];
[self.btnLeftMenu addGestureRecognizer:gestureMenu];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
////
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self->locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
}
- (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);
CLLocationDegrees lat = newLocation.coordinate.latitude;
CLLocationDegrees lon = newLocation.coordinate.longitude;
CLLocation * location = [[CLLocation alloc]initWithLatitude:lat longitude:lon];
self.viewRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500);
[self.mapView setRegion:self.viewRegion];
}
-(void)localSearch:(NSString*)searchString{
[self.mapView setRegion:self.viewRegion];
MKLocalSearchRequest * request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = [searchString lowercaseString];
request.region = self.viewRegion;
MKLocalSearch* search = [[MKLocalSearch alloc] initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
if([response.mapItems count] == 0){
NSLog(#"No matches \n");
}
else{
for(MKMapItem * item in response.mapItems){
Location * pin = [[Location alloc] initWith:item.placemark.title andSubtitle:item.phoneNumber andCoordinate:item.placemark.coordinate andImageName:#"" andURL:item.url.absoluteString];
[self.mapView addAnnotation:pin];
}
}
}];
}
#pragma mark UISearchBarDelegate
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
[searchBar resignFirstResponder];
[self.mapView removeAnnotations:[self.mapView annotations]];
[self localSearch:searchBar.text];
}
#pragma mark MKMapViewDelegate
-(MKAnnotationView*)mapView:(MKMapView*)sender viewForAnnotation: (id<MKAnnotation>)annotation{
static NSString* identifier = #"reusablePin";
MKAnnotationView * aView = [sender dequeueReusableAnnotationViewWithIdentifier:identifier];
if(!aView){
aView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
aView.canShowCallout = YES;
}
aView.annotation = annotation;
return aView;
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
NSLog(#"%#",view.annotation.title);
NSLog(#"%#",view.annotation.subtitle);
}
I want to have one pin showing at a time.
How about break; in for loop?
for(MKMapItem * item in response.mapItems){
Location * pin = [[Location alloc] initWith:item.placemark.title andSubtitle:item.phoneNumber andCoordinate:item.placemark.coordinate andImageName:#"" andURL:item.url.absoluteString];
[self.mapView addAnnotation:pin];
// one pin showed
break;
}
Once you search for the location the user's location pin should disappear,
and once you select one of the multiple pins you searched the others should disappear.
You can use didSelectAnnotationView method.
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
// once you select one of the multiple pins, the others should disappear.
for (MKPointAnnotation *annotation in mapView.annotations) {
if (view.annotation != annotation) {
[mapView removeAnnotation:annotation];
NSLog(#"yes!!");
}
}
}

Current Location returning 0

My Xcode app that I am developing needs to get the latitude and longitude of the users iOS device. Although currently all I get is 0 for both values. It does not ask for permission to have the location, and I am on a real device not a simulator.
NSLocationAlwaysUsageDescription is in my info.plist
I have also imported CoreLocation and in my .h file
#interface LocationViewController : UIViewController <CLLocationManagerDelegate>
in my .m file
#interface LocationViewController () <CLLocationManagerDelegate>
Here is my code:
#implementation LocationViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self getCurrentLocation];
}
-(CLLocationCoordinate2D) getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;
}
- (void)getCurrentLocation{
CLLocationCoordinate2D coordinate = [self getLocation];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude = %#", latitude);
NSLog(#"Longitude = %#", longitude);
}
Refer this answer. Hope, this helps.
Make this changes :
-(CLLocationCoordinate2D) getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager requestWhenInUseAuthorization];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
NSLog(#"Status : %d", status);
}
Goto Settings > Privacy > Location > Your App > Always
And see how 'Status' value gets changes.
Put below before startUpdatingLocation
#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];
}
#endif
[self.locationManager startUpdatingLocation];
Also call [self getCurrentLocation]; in viewDidLoad & viewDidAppear both.
It will work.
Also make sure you have entry for requestWhenInUseAuthorization in info.plist file too.
check this for more info

Can't assign a google maps map to custom view

So I followed this guide on how to add a Google map to an iOS application and it all works fine. But what I want to do is assign the map, not to self.view but a custom view I dragged out on to the storyboard inside(?) the other view, because when adding the map to self.view I can't add other elements, like buttons, or well, I probably can but I don't know how.
Code:
// Start locationmanager
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
// Set up the startposition for the camera when the app first starts.
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:59.34702 longitude:18.04053 zoom:10];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = mapView_;
So i created a UIView inside the view currently containing the map and ctrl dragged it to create an outlet called mapView in that viewController. So i changed the line of code from
self.view = _mapView;
to
self.mapView = _mapView;
but this does not seem to work at all, just blank. Both self.view and self.mapsView are instances of UIView, so why does this not work?
Update:
This is what my viewDidLoad looks like atm:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.mapView addSubview:mapView_];
// Start locationmanager
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
// Standard cameraposition
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:59.34702 longitude:18.04053 zoom:10];
mapView_ = [GMSMapView mapWithFrame:self.mapView.frame camera:camera];
self.mapView = mapView_;
}
Do the following:
Change your custom view Class to GMSMapView in the identity inspector of IB
create outlet mapView to this custom view in you view controller (pay attention that outlet type is also GMSMapView)
So now when you start your app this instance will be created, and it will display default location on the map (near London). Now you only need to create a camera and add it to the map object. Add this code in your ViewDidLoad method:
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:45.24 longitude:19.84 zoom:6];
// set camera location to Novi Sad, Serbia :-)
[self.mapView setCamera:camera]; // set the camera to map
Thats it, you do not need instance variable mapView_ from Google sample code, nor any other code from Google sample. Enjoy!
Try this in your project:
//
// testViewController.m
// maps
//
// Created by Millén on 2013-02-25.
// Copyright (c) 2013 JamWeb. All rights reserved.
//
#import "testViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#interface testViewController ()
#property(nonatomic, strong) GMSMapView *gMapView;
#end
#implementation testViewController {
CLLocation *oldLocation;
}
-(void)loadView
{
CLLocationDegrees lat = 59.34702;
CLLocationDegrees lon = 18.04053;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:lat longitude:lon zoom:10];
self.gMapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.gMapView.myLocationEnabled = YES;
self.view = self.gMapView;
[self updateLocation];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Start locationmanager
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
}
- (IBAction)updateLocation {
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
/*
if(!oldLocation)
{
oldLocation = location;
}
if (![location isEqual:oldLocation]) {
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude: location.coordinate.latitude
longitude: location.coordinate.longitude
zoom:7];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.myLocationEnabled = YES;
self.view = mapView_;
oldLocation = location;
[locationManager stopUpdatingLocation];
}
*/
NSLog(#"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
In your code you have:
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
CGRectZero will make its size zero. You should use self.mapView.frame instead.
Also need to add add mapView_ as subview of mapView:
[self.mapView addSubview:mapView_];

MKMapView zoom User Location and Annotation

I want my MKMapView to zoom 'User Location' and the Annotation as close as possible.
The map already show both, but is zoomed out to the whole country.
How can I do that?
And I don’t know why the Annotation and Pin are not animated.
My Code:
//Coords User
CLLocationCoordinate2D user_location;
user_location.latitude = mapView.userLocation.location.coordinate.latitude;
user_location.longitude = mapView.userLocation.location.coordinate.longitude;
//Coords Annotation
CLLocationCoordinate2D club_location;
club_location.latitude = [self.clubInfo.latitude doubleValue];
club_location.longitude = [self.clubInfo.longitude doubleValue];
MKMapPoint userPoint = MKMapPointForCoordinate(user_location);
MKMapPoint annotationPoint = MKMapPointForCoordinate(club_location);
MKMapRect userRect = MKMapRectMake(userPoint.x, userPoint.y, 0, 0);
MKMapRect annotationRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
MKMapRect unionRect = MKMapRectUnion(userRect, annotationRect);
MKMapRect unionRectThatFits = [mapView mapRectThatFits:unionRect];
[mapView setVisibleMapRect:unionRectThatFits animated:YES];
// Add an annotation
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = club_location;
annotation.title = self.clubInfo.clubName;
annotation.subtitle = #"Pin!";
[mapView addAnnotation:annotation]; // This was missing
[mapView selectAnnotation:annotation animated:YES];
Logs:
userRect: {{134217728.0, 134217728.0}, {0.0, 0.0}}
annotationRect: {{99775488.0, 152579328.0}, {0.0, 0.0}}
unionRect: {{99775488.0, 134217728.0}, {34442240.0, 18361600.0}}
mapView.visibleMapRect: {{96025087.6, 116070015.1}, {41943040.7, 54657025.8}}
If I understand well, you want those two annotations to be visible with maximum possible zoom. I found this solution that does not reqire any calculations.
// You have coordinates
CLLocationCoordinate2D user = ...;
CLLocationCoordinate2D annotation = ...;
// Make map points
MKMapPoint userPoint = MKMapPointForCoordinate(user);
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation);
// Make map rects with 0 size
MKMapRect userRect = MKMapRectMake(userPoint.x, userPoint.y, 0, 0);
MKMapRect annotationRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
// Make union of those two rects
MKMapRect unionRect = MKMapRectUnion(userRect, annotationRect);
// You have the smallest possible rect containing both locations
MKMapRect unionRectThatFits = [mapView mapRectThatFits:unionRect];
[mapView setVisibleMapRect:unionRectThatFits animated:YES];
CoreLocation and MapKit structures are hell.
For anyone coming here later: The shortest way of doing this is (iOS7+) this:
Assuming you have a #property MKMapView *mapView, and an MKPointAnnotation *theAnnotation, call:
[self.mapView showAnnotations:#[theAnnotation, self.mapView.userLocation] animated:NO];
Now this could cause some problems if called too early (i.e. when self.mapView.userLocation is not yet set). If so, you can call in viewWillAppear:
[self.mapView.userLocation addObserver:self forKeyPath:#"location" options:0 context:NULL];
Then, implement:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:#"location"]) {
[self.mapView showAnnotations:#[theAnnotation, self.mapView.userLocation] animated:NO];
}
}
That way you're sure it's set. Don't forget to remove the observer at viewWillDisappear:
[self.mapView.userLocation removeObserver:self forKeyPath:#"location"];
Use these 4 classes - it works like a charm!
//MapViewController.h file
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface MapViewController : UIViewController <CLLocationManagerDelegate> {
IBOutlet UIButton *buttonBack;
IBOutlet MKMapView *mapView;
IBOutlet UILabel *labelTitle;
NSString *lon,*lat,*nickName;
BOOL isFirstLaunch;
}
#property(nonatomic,retain) NSString *lon,*lat,*nickName;
#property(nonatomic,retain) IBOutlet UIButton *buttonBack;
#property(nonatomic,retain) IBOutlet UILabel *labelTitle;
#property(nonatomic,retain) IBOutlet MKMapView *mapView;
-(IBAction)buttonBackAction:(UIButton *)_btn;
-(void)zoomToFitMapAnnotations;
#end
//
// MapViewController.m
//
#import "MapViewController.h"
#import "Annotation.h"
#implementation MapViewController
#synthesize buttonBack,mapView,labelTitle;
#synthesize lon,lat,nickName;
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
-(IBAction)buttonBackAction:(UIButton *)_btn{
[self.navigationController popViewControllerAnimated:1];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
CLLocationManager* locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
NSLog(#"MapViewController");
labelTitle.text = #"anscacorona.blogspot.in"
CLLocationCoordinate2D location;
location.latitude = [self.lat floatValue];
location.longitude = [self.lon floatValue];
Annotation *annotation = [[Annotation alloc] init];
annotation.theCoordinate = location;
annotation.theTitle = [NSString stringWithFormat:#"%#",labelTitle.text];
[mapView addAnnotation:annotation];
[annotation release];
mapView.showsUserLocation = 1;
[self zoomToFitMapAnnotations];
[super viewDidLoad];
}
// Shows the location of both users. called when the device location changes to move the map accordinly. necessary ONLY once when the window is opened. afterwards the user can move the map as he choises.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (isFirstLaunch) {
CLLocationCoordinate2D topLeftCoord;
CLLocationCoordinate2D bottomRightCoord;
topLeftCoord.longitude = fmin([self.lon floatValue], newLocation.coordinate.longitude);
topLeftCoord.latitude = fmax([self.lat floatValue], newLocation.coordinate.latitude);
bottomRightCoord.longitude = fmax([self.lon floatValue], newLocation.coordinate.longitude);
bottomRightCoord.latitude = fmin([self.lat floatValue], newLocation.coordinate.latitude);
MKCoordinateRegion region;
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.5; // Add a little extra space on the sides
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.5; // Add a little extra space on the sides
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
isFirstLaunch = NO;
}
}
-(void)zoomToFitMapAnnotations
{
if([mapView.annotations count] == 0)
return;
CLLocationCoordinate2D topLeftCoord;
CLLocationCoordinate2D bottomRightCoord;
topLeftCoord.longitude = fmin(mapView.userLocation.location.coordinate.longitude, [self.lon floatValue]);
topLeftCoord.latitude = fmax(mapView.userLocation.location.coordinate.latitude, [self.lat floatValue]);
bottomRightCoord.longitude = fmax(mapView.userLocation.location.coordinate.longitude, [self.lon floatValue]);
bottomRightCoord.latitude = fmin(mapView.userLocation.location.coordinate.latitude, [self.lat floatValue]);
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
CLLocationCoordinate2D userCoord = {[self.lat floatValue],[self.lon floatValue]};
region.center = userCoord;
region.span.latitudeDelta = 0.05f;//fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
region.span.longitudeDelta = 0.05f;//fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides
[mapView setRegion:region animated:YES];
[mapView regionThatFits:region];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
#pragma mark - View Lifecycle
-(void)viewWillAppear:(BOOL)animated{
isFirstLaunch=YES;
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
//anotation classes- Annotation.h
#import <MapKit/MapKit.h>
#interface Annotation : NSObject <MKAnnotation>{
CLLocationCoordinate2D theCoordinate;
NSString *theTitle;
NSString *restId;
NSString *theSubtitle;
}
#property(nonatomic,retain) NSString *restId;
#property(nonatomic,retain) NSString *theTitle;
#property(nonatomic,retain) NSString *theSubtitle;
#property CLLocationCoordinate2D theCoordinate;
#end
//Annotation.m
#import "Annotation.h"
#implementation Annotation
#synthesize theCoordinate,theTitle,theSubtitle,restId;
- (CLLocationCoordinate2D)coordinate;
{
return theCoordinate;
}
// required if you set the MKPinAnnotationView's "canShowCallout" property to YES
- (NSString *)title
{
return theTitle;
}
// optional
- (NSString *)subtitle
{
return theSubtitle;
}
- (void)dealloc
{
[super dealloc];
}
#end