MKUserTrackingBarButtonItem crashes on zoom in - ios7

I am using MKUserTrackingBarButtonItem to track user. I am not able to set the zoom when using user tracking bar button. So i tried to zoom in on the screen .
And application crashes after few steps.
I have a coordinate near by and i am trying to use this to keep track of user relative to the coordinates.
Why is app crashing.
Is there a better way to do this? Any help is greatly appreciated.
Here is my code:-
-(void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
self.mapView.delegate = self;
_coordinate1.latitude = 29.9431438;
_coordinate1.longitude = -95.5170326;
self.mapView.showsUserLocation = YES; }
-(void) viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
MKCoordinateRegion region = [self regionFromLocations:self.currentLoc];
[self displayPoints];
MKCoordinateRegion adjustRegion = [self.mapView regionThatFits:region];
self.mapView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
[self.mapView setRegion:adjustRegion animated:YES]; }
- (void)viewDidLoad {
[super viewDidLoad];
MKUserTrackingBarButtonItem *locateMeButton = [[MKUserTrackingBarButtonItem alloc] initWithMapView:self.mapView];
NSArray *toolbarItems = [NSArray arrayWithObjects: locateMeButton,
nil];
self.toolBar.items = toolbarItems; }
- (void)viewWillDisappear:(BOOL)animated {
NSLog(#"viewwillDisapear");
[self.mapView setUserTrackingMode:MKUserTrackingModeNone];
[super viewWillDisappear:animated];}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
// getting current location
self.currentLoc = userLocation.location.coordinate;
NSLog(#"loc- %f %f", self.currentLoc.longitude, self.currentLoc.latitude); }

Solved the problem by removing map view when view Disappear
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
self.mapView.delegate = nil;
[self.mapView removeFromSuperview];
}

Related

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!!");
}
}
}

How to find the current location address?

I done the task on Mapkit to find the currentLocation by using below code. Now I want to display the current location address at the annotation pain.How to cal the geo coding method for displaying the current location address.latitude and longitude values?
#import "MapKitViewController.h"
#import "ViewController.h"
#define METERS_MILE 1609.344
#define METERS_FEET 3.28084
#interface MapKitViewController ()<CLLocationManagerDelegate,MKMapViewDelegate >
#end
#implementation MapKitViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// _mapView.delegate = self;
locationManager =[[CLLocationManager alloc] init];
[[self mapView ] setShowsUserLocation:YES];
[locationManager setDelegate:self];
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
NSLog(#" startUpdatingLocation");
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations{
CLLocation *location=locations.lastObject;
[[self latitudeValue] setText:[NSString stringWithFormat:#"%.6f",location.coordinate.latitude]];
[[self longnitudeValue] setText:[NSString stringWithFormat:#"%.6f",location.coordinate.longitude]];
// [[self altitudeValue] setText:[NSString stringWithFormat:#"%.2f feet",location.altitude*METERS_FEET]];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 2*METERS_MILE, 2*METERS_MILE);
[[self mapView] setRegion:viewRegion animated:YES];
MKPointAnnotation *point=[[MKPointAnnotation alloc]init];
point.coordinate=location.coordinate;
[self.mapView addAnnotation:point];
point.title=#"this is my place";
NSLog(#"I got the point");
NSLog(#"didUpdateLocations");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
For display current location on map use this..
MKPointAnnotation *annonation = [[MKPointAnnotation alloc]init];
CLLocationCoordinate2D mycordinate;
mycordinate.latitude = [self.strlog floatValue];
mycordinate.longitude =[self.strlat floatValue];
annonation.coordinate = mycordinate;
[self.mapview addAnnotation:annonation];

Zooming to users location iOS 8 MapKit Obj-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

infowindow not displaying with marker in didTapAtCoordinate method

i am trying to show infowindow and marker both simultaneously.
code
-(void)set_markerOnMap:(double)lat longitude:(double)lon{
GMSMarker *marker = [[GMSMarker alloc] init];
marker.title = #"Location selected";
marker.position = CLLocationCoordinate2DMake(lat, lon);
marker.snippet = #"Testing";
marker.icon=[UIImage imageNamed:#"red-pin.png"];
marker.map = self.MyMapView;
[self.MyMapView setSelectedMarker:marker];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self set_markerOnMap:21.214894 longitude:72.88087];
self.MyMapView.delegate=self;
}
above code is working fine and its showing both infowindow and marker together.
but my problem is when i called set_markerOnMap method from didTapAtCoordinate instead of viewDidLoad it does not work and only marker is shown.
code:
- (void)viewDidLoad
{
[super viewDidLoad];
self.MyMapView.delegate=self;
}
- (void) mapView: (GMSMapView *) mapView
didTapAtCoordinate: (CLLocationCoordinate2D) coordinate{
[self set_markerOnMap:21.214894 longitude:72.88087];
}
anyone can help me where i am wrong?
See if this works...
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self set_markerOnMap:21.214894 longitude:72.88087];
}];
So the short term answer, as hinted by i2Fluffy, is the following:
#implementation ViewController {
GMSMarker *tapMarker;
}
- (void)viewDidLoad {
[super viewDidLoad];
GMSMapView *mapView = (GMSMapView*)self.view;
mapView.delegate = self;
CLLocationCoordinate2D sydney = CLLocationCoordinate2DMake(-33.868, 151.2086);
mapView.camera = [GMSCameraPosition cameraWithTarget:sydney zoom:8];
tapMarker = [GMSMarker markerWithPosition:sydney];
tapMarker.title = #"Tap Marker";
tapMarker.map = (GMSMapView*)self.view;
}
-(void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate {
NSLog(#"Tap at (%g,%g)", coordinate.latitude, coordinate.longitude);
tapMarker.position = coordinate;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[((GMSMapView*)self.view) setSelectedMarker:tapMarker];
}];
}
#end
The longer term answer is that this is a bug (gmaps-api-issues/7222) and I'll work with engineering to get this fixed.
Thanks for the report! =)

MoPub banner Ad not appearing

I'm trying to get a MoPub banner ad to appear. I've created a UIViewController, and put the MoPub code into the View did load as thus..
- (id)init
{
self = [super init];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// ... your other -viewDidLoad code ...
self.adView = [[MPAdView alloc] initWithAdUnitId:#"ID HERE"
size:MOPUB_BANNER_SIZE];
self.adView.delegate = self;
CGRect frame = self.adView.frame;
CGSize size = [self.adView adContentViewSize];
frame.origin.y = [[UIScreen mainScreen] applicationFrame].size.height - size.height;
self.adView.frame = frame;
[self.view addSubview:self.adView];
[self.adView loadAd];
//[super viewDidLoad];
}
#pragma mark - <MPAdViewDelegate>
- (UIViewController *)viewControllerForPresentingModalView {
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
And in my AppDelegate I'm setting everything up like this (it's a Sparrow game)
//setup Sparrow
CGRect screenBounds = [UIScreen mainScreen].bounds;
_window = [[UIWindow alloc] initWithFrame:screenBounds];
_gcViewController = [[UIViewController alloc]init];
_viewController = [[SPViewController alloc] init];
[_viewController startWithRoot:[Game class] supportHighResolutions:YES doubleOnPad:YES];
_viewController.multitouchEnabled = YES;
[_window setRootViewController:_viewController];
adViewController = [[AdViewController alloc]init];
[_window addSubview:adViewController.view];
[_window addSubview:_gcViewController.view];
[_window makeKeyAndVisible];
And in the console I seem to be getting the correct msgs as this...
Looking for custom event class named MPHTMLBannerCustomEvent. MOPUB:
Loading MoPub HTML banner MOPUB: MoPub HTML banner did load
But I can't see anything on the screen in the simulator, any ideas?