do Google Map Markers have to be added in ViewDidLoad? - ios

This is my code for ViewController.m: So far, I've been loading a list of Map markers from a database in viewDidLoad. I want to add a marker and have it appear on the map, but the marker never shows up until I close the view and open it again.
#interface ViewController : UIViewController <GMSMapViewDelegate, CLLocationManagerDelegate>
#property (strong, nonatomic) IBOutlet GMSMapView *mapView;
#end
- (void)viewDidLoad {
[super viewDidLoad];
// Getting My Location
//Instantiate a location object.
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
//Set some parameters for the location object.
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy: kCLLocationAccuracyBest];
[locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
NSLog(#"created locationManager");
// Google Map View
_mapView.settings.compassButton = YES;
_mapView.padding = UIEdgeInsetsMake(self.topLayoutGuide.length + 10, 0, self.bottomLayoutGuide.length, 0);
/* Setting Up Markers */
self.mapView.delegate = self;
[self addMarkers];
}
an IB Action is called (and definitely gets called) to add a new Marker, but the Marker does not show up on the map. I've tried this in ViewWillAppear and others, but the marker is not added. I'm starting to think markers can only be added in ViewDidLoad...is this true?
-(IBAction)unwindtoRoot:(UIStoryboardSegue *)segue {
NSLog(#"unwindToRoot");
//[self addMarkers];
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(40.729358, -73.998301);
GMSMarker *marker = [GMSMarker markerWithPosition:position];
marker.title = #"Kopi Kopi";
marker.map = _mapView;
}

Related

Zoom with animation in current location when map loads in IOS

I have used map in my view controller but when the maps loads it shows me view of the whole country. I want to show my current location view when maps loads, for that I have used didUpdateUserLocation method and set delegate for it.
My code is this:
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}
Now when my map loads it animate and zoom but in wrong location. It is taking me to any location in sea when map loads , but my current location is different.
I have also tested it in real device but it does not show my location.
The maps looks like that when loads:
ViewController class code:
#property BOOL updateUserLocation;
#property(strong,nonatomic) CLLocation *userLocation;
#property (nonatomic, retain) MKPolyline *routeLine;
#property (nonatomic, retain) MKPolylineView *routeLineView;
#property (nonatomic,retain) NSString *latitude;
#property (nonatomic,retain) NSString *longitude;
- (void)viewDidLoad {
[super viewDidLoad];
[[self navigationController] setNavigationBarHidden:YES animated:YES];
_AlertView.hidden=YES;
_distanceView.hidden=YES;
self.mapView.zoomEnabled=YES;
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
[self.mapView setShowsUserLocation:YES];
[self.mapView setDelegate:self];
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}
Add these lines in the viewDidLoad:
self.mapView.showsUserLocation = YES;
if you want to center the map to the user location add this:
[self.mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];
EDIT:
ViewController example:
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController () <CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property (nonatomic, strong) CLLocationManager *locationManager;
#property (nonatomic, strong) CLLocation *location;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[self mapView] setShowsUserLocation:YES];
self.locationManager = [[CLLocationManager alloc] init];
// we have to setup the location manager with permission in later iOS versions
if ([[self locationManager] respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[[self locationManager] requestWhenInUseAuthorization];
}
[[self locationManager] setDelegate:self];
[[self locationManager] setDesiredAccuracy:kCLLocationAccuracyBest];
[[self locationManager] startUpdatingLocation];
}
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
// Stop updating location, when you want to restart update use [[self locationManager] startUpdatingLocation];
[manager stopUpdatingLocation];
self.location = locations.lastObject;
// zoom the map into the users current location
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance
(self.location.coordinate, 2, 2);
[[self mapView] setRegion:viewRegion animated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I've only added the IBOutlet on the storyboard and the NSLocationWhenInUseUsageDescription key in the plist.
If you change the location on the simulator you can see the maps change location.
If you want I can upload the complete example project.
NEW EDIT:
There is an error in you code!
When you use [self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES], you use _userLocation that is your CLLocation variable! You must use userLocation that is the value that you receive from the method.
I recommend you to change the CCLocation variable name and use the userLocation name only for the variable used in the didUpdateUserLocation method.
You can call this method and zoom on map
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = ; // your latitude value
zoomLocation.longitude= // your longitude value
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.18; // change as per your zoom level
span.longitudeDelta=0.18;
region.span=span;
region.center= zoomLocation;
[mapview setRegion:region animated:TRUE];
[mapview regionThatFits:region];
Use didUpdateToLocation instead of didUpdateUserLocation.
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
[self.locationManager stopUpdatingLocation];
MKCoordinateRegion region;
region.span.latitudeDelta = 0.005;
region.span.longitudeDelta = 0.005;
region.center.latitude = newLocation.coordinate.latitude;
region.center.longitude = newLocation.coordinate.longitude;
[self.mapView setRegion:region animated:YES];
}
See also my library.
https://github.com/koogawa/KGWLocationPicker/blob/master/KGWLocationPicker/KGWLocationPickerViewController.m

google maps zoom to current location in ios

google maps could not zoom to current Location
after searching for many solution over stack such as Zoom in to current location on map in object c but i found a solution could help me but it was written in swift
Current Location in Google Maps with swift
Code
.h File
#import <UIKit/UIKit.h>
#import GoogleMaps;
#interface BranchesViewController : UIViewController <GMSMapViewDelegate,CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet GMSMapView *mapView;
#property (nonatomic, retain) CLLocationManager *locationManager;
#end
.m File
//
// BranchesViewController.m
// Geeks Diner
//
// Created by Zakaria Darwish on 5/15/16.
// Copyright © 2016 CodeBee. All rights reserved.
//
#import "BranchesViewController.h"
#import "infoWindow.h"
#import "SplashViewController.h"
#import "sharedVariables.h"
#import"AFNetworking.h"
#import "UIWebView+AFNetworking.h"
#import "SDWebImageCompat.h"
#import "SDWebImageDownloaderOperation.h"
#import "SDWebImageDownloader.h"
#import "MyGeeksTableViewController.h"
#import "GeeksLocations.h"
#import "BranchDetailsViewController.h"
#import GoogleMaps;
#interface BranchesViewController () <GMSMapViewDelegate>
#end
#implementation BranchesViewController
{
GMSMarker *marker_1;
BOOL firstLocationUpdate_;
CLLocationCoordinate2D *startPoint;
CLLocation *myLocation;
NSMutableArray *list;
}
-(void)getCurrentLocationAndZoomToIt {
}
//- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
// GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:newLocation.coordinate.latitude
// longitude:newLocation.coordinate.longitude
// zoom:17.0];
// [self.mapView animateToCameraPosition:camera];
// CLLocation *location = newLocation;
//
//
//
//
//
////
//// let userLocation = locations.last
//// let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)
////
//// let camera = GMSCameraPosition.cameraWithLatitude(userLocation!.coordinate.latitude,
//// longitude: userLocation!.coordinate.longitude, zoom: 8)
//// let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
//// mapView.myLocationEnabled = true
//// self.view = mapView
////
//// let marker = GMSMarker()
//// marker.position = center
//// marker.title = "Current Location"
//// marker.snippet = "XXX"
//// marker.map = mapView
////
//// locationManager.stopUpdatingLocation()
// }
-(void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker
{
NSLog(#"tapped");
// we need to move into new view //
BranchDetailsViewController *avc = [[UIStoryboard storyboardWithName:#"Main" bundle:nil] instantiateViewControllerWithIdentifier:#"branchdetailviewcontroller"];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:avc];
// nav.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:nav animated:YES completion:nil];
}
-(UIImage *)getImage :(UIImage *)icon stop:(NSString *)stopNumber color:(UIColor *)color
{
// create label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, icon.size.width,icon.size.height)];
[label setText:stopNumber];
[label setTextColor:color];
[label setFont:[UIFont boldSystemFontOfSize:11]];
label.textAlignment = NSTextAlignmentCenter;
//start drawing
UIGraphicsBeginImageContext(icon.size);
//draw image
[icon drawInRect:CGRectMake(0, 0, icon.size.width, icon.size.height)];
//draw label
[label drawTextInRect:CGRectMake((icon.size.width - label.frame.size.width)/2, -5, label.frame.size.width, label.frame.size.height)];
//get the final image
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.mapView.delegate = self;
self.locationManager = [[CLLocationManager alloc] init] ;
self.locationManager.delegate = self;
[self.locationManager requestWhenInUseAuthorization];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation ;
[self.locationManager setDistanceFilter:10.0f] ;
[self.locationManager startUpdatingLocation];
// UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]];
// // Width equivalent to system default Done button's (which appears on pushed view in my case).
// rightBarButtonItem.enabled = NO;
// self.navigationItem.leftBarButtonItem = rightBarButtonItem;
[self getGeeksLocations];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
[self.locationManager stopUpdatingLocation];
CLLocationCoordinate2D zoomLocation;
// zoomLocation.latitude = self.mapView.myLocation.location.coordinate.latitude;
// zoomLocation.longitude= YourMapView.userLocation.location.coordinate.longitude;
// 2
// MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*1609.344, 0.5*1609.344);
// 3
// [self.mapView setRegion:viewRegion animated:YES];
// [self.locationManager stopUpdatingLocation];
// zoomLocation.latitude = self.mapView.userLocation.location.coordinate.latitude;
// zoomLocation.longitude= self.mapView.userLocation.location.coordinate.longitude;
// // 2
// MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*1609.344, 0.5*1609.344);
// // 3
// [self.mapView setRegion:viewRegion animated:YES];
}
so any one could help me with that ??
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
mapView.animate(toLocation: CLLocationCoordinate2D(latitude: locValue.latitude, longitude: locValue.longitude))
mapView.setMinZoom(4.6, maxZoom: 20)
}
You can pan the map or change its perspective with very little latency. The bearing, tilt, location and zoom level of the map can be controlled programmatically via the GMSCameraPosition object.
You can use -animateToZoom: on your GMSMapView, or you can create a GMSCameraPosition and set the coordinate and zoom level and then use -animateToCameraPosition: or create a GMSCameraUpdate and then use -animateWithCameraUpdate:
GMSCameraPosition *cameraPosition = [GMSCameraPosition cameraWithLatitude:latitude
longitude:longitude
zoom:11.0];
[self.mapView animateToCameraPosition:cameraPosition];
or
GMSCameraUpdate *update = [GMSCameraUpdate zoomTo:11.0];
[self.mapView animateWithCameraUpdate:update];
or
[self.mapView animateToZoom:11.0];

how to show a map with a single annotation and the users location and have the map display both whether the user is 100ft or 100miles

I'd like to have a map with just two points, the users location and a single annotation (it's for a pov). I have included what I
have below. Ideally, I would like it to handle if the user is 100 feet away or 100 miles in displaying both the User and the annotation in
the map view. I think it would be best if the location were at the center and the user were on the edge with some reasonable 20% buffer on the edge of the map view. I only need to support iOS 7 and greater.
Is there something like sizeToFit for annotations that takes into account users position as an annotation?
my MapViewController.h
#interface MapViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
my MapViewController.m:
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#import "MapViewController.h"
#import "MYUtility.h"
#interface MapViewController (){
NSMutableArray *_yourAnnotationArray;
MKPointAnnotation *_locationPoint;
BOOL _firstTime;
}
#end
#implementation MapViewController
- (void)viewDidLoad {
[super viewDidLoad];
_firstTime=YES;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
if(IS_OS_8_OR_LATER) {
//[self.locationManager requestWhenInUseAuthorization];
//[self.locationManager requestAlwaysAuthorization];
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager startUpdatingLocation];
}
[self.locationManager startUpdatingLocation];
[self.mapView setShowsUserLocation:YES];
[self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
CGFloat latitude=MYLocationLatitude();
CGFloat longitude=MYLocationLongitude();
_locationPoint = [[MKPointAnnotation alloc] init];
_locationPoint.coordinate = CLLocationCoordinate2DMake(latitude, longitude);
_locationPoint.title = #"Where am I?";
_locationPoint.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:_locationPoint];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//if(_firstTime){
NSLog(#"here is my thinking %#", [locations lastObject]);
[self setMapStart];
}
-(void)setMapStart
{
//if(_firstTime){
NSLog(#"at top of _firstTime being true");
MKPointAnnotation *myPoint = [[MKPointAnnotation alloc] init];
myPoint.coordinate = CLLocationCoordinate2DMake(34.035645, -118.233434);
MKMapPoint annotationPoint = MKMapPointForCoordinate(self.mapView.userLocation.coordinate);
//[_yourAnnotationArray addObject:annotationPoint];
_yourAnnotationArray=[[NSMutableArray alloc] initWithObjects:_locationPoint,annotationPoint, nil];
//NSLog(#"here is my count: %i",(unsigned long)[_yourAnnotationArray count]);
[self.mapView showAnnotations:self.mapView.annotations animated:YES]; // <- determine when this has run
_firstTime=NO;
//}
}

GPS Tracking in Xcode stopped working in Xcode 6 after working in Xcode 5

I am going through a tutorial on youtube that teaches you how to track and trace a user's location on a map view. The tutorial comes with a copy of the code so I downloaded the code files and opened them up in Xcode. The first time that I opened the code in Xcode I had the newest Xcode 5. It ran just fine finding and tracing the location. About a day later Xcode 6 came out so I updated my Xcode to Xcode 6. When opening the code files in Xcode 6, the application would not preform correctly. I am getting an error that says...
2014-09-28 17:24:34.468 GPSTrack[1644:130866] Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
In the header file GPSTrackerViewController.h
//
// GPSTrackViewController.h
// GPSTrack
//
// Created by Nick Barrowclough on 4/21/14.
// Copyright (c) 2014 iSoftware Developers. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h> //import the mapkit framework
#interface GPSTrackViewController : UIViewController <CLLocationManagerDelegate, MKMapViewDelegate, MKOverlay> {
CLLocationManager *lm; //core lcoation manager instance
NSMutableArray *trackPointArray; //Array to store location points
//instaces from mapkit to draw trail on map
MKMapRect routeRect;
MKPolylineView* routeLineView;
MKPolyline* routeLine;
}
- (IBAction)startTracking:(id)sender;
- (IBAction)stopTracking:(id)sender;
- (IBAction)clearTrack:(id)sender;
#property (weak, nonatomic) IBOutlet MKMapView *mapview;
#end
GPSTrackViewController.m
//
// GPSTrackViewController.m
// GPSTrack
//
// Created by Nick Barrowclough on 4/21/14.
// Copyright (c) 2014 iSoftware Developers. All rights reserved.
//
#import "GPSTrackViewController.h"
#interface GPSTrackViewController ()
#end
#implementation GPSTrackViewController
#synthesize mapview;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
mapview.mapType = MKMapTypeHybrid;
}
- (void)viewWillAppear:(BOOL)animated {
trackPointArray = [[NSMutableArray alloc] init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startTracking:(id)sender {
//start location manager
lm = [[CLLocationManager alloc] init];
lm.delegate = self;
lm.desiredAccuracy = kCLLocationAccuracyBest;
lm.distanceFilter = kCLDistanceFilterNone;
[lm startUpdatingLocation];
mapview.delegate = self;
mapview.showsUserLocation = YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
//get the latest location
CLLocation *currentLocation = [locations lastObject];
//store latest location in stored track array;
[trackPointArray addObject:currentLocation];
//get latest location coordinates
CLLocationDegrees Latitude = currentLocation.coordinate.latitude;
CLLocationDegrees Longitude = currentLocation.coordinate.longitude;
CLLocationCoordinate2D locationCoordinates = CLLocationCoordinate2DMake(Latitude, Longitude);
//zoom map to show users location
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(locationCoordinates, 1000, 1000);
MKCoordinateRegion adjustedRegion = [mapview regionThatFits:viewRegion]; [mapview setRegion:adjustedRegion animated:YES];
NSInteger numberOfSteps = trackPointArray.count;
CLLocationCoordinate2D coordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++) {
CLLocation *location = [trackPointArray objectAtIndex:index];
CLLocationCoordinate2D coordinate2 = location.coordinate;
coordinates[index] = coordinate2;
}
MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
[mapview addOverlay:polyLine];
//NSLog(#"%#", trackPointArray);
}
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
polylineView.strokeColor = [UIColor redColor];
polylineView.lineWidth = 4.0;
return polylineView;
}
- (IBAction)stopTracking:(id)sender {
//reset location manager and turn off GPS
lm = [[CLLocationManager alloc] init];
[lm stopUpdatingLocation];
lm = nil;
//stop shwing user location
mapview.showsUserLocation = NO;
//reset array fo tracks
trackPointArray = nil;
trackPointArray = [[NSMutableArray alloc] init];
}
- (IBAction)clearTrack:(id)sender {
//remove overlay on mapview
[mapview removeOverlays: mapview.overlays];
}
#end
Can someone please help me understand why the application is not running any more and give me some suggestions of what I need to do to get it up and running again.
under base sdk 8 (which is what xcode 6 uses, I removed the xcode tag as it isn't IDE specific) you have to ask for authorisation first and have to have a plist key (a string saying why you need to use GPS)
the plist key depends on your needs is EITHER
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
this SO question looks good:
IOS 8 CLLocationManager Issue (Authorization Not Working)
for detailed instructs, I can recommend (skimmed it):
http://nevan.net/2014/09/core-location-manager-changes-in-ios-8/

How does locationManager get coordinates?

I can't understand how CLLocationManager get my current location coordinates ? if I don't call [locationManager startUpdatingLocation] and don't set parameters in locationManager.location.coordinate.
ViewController.h
#interface ViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
}
#property (weak, nonatomic) IBOutlet MKMapView* mapView;
#end
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.mapView.delegate = self;
[self.mapView setShowsUserLocation:YES];
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
}
-(void) mapView:(MKMapView *) mv didAddAnnotationViews:(NSArray *)views {
MKCoordinateRegion region;
region = MKCoordinateRegionMakeWithDistance(locationManager.location.coordinate, 1000, 1000);
[mv setRegion:region animated:YES];
}
Most likely it's a cached value after MapView requested current location update because of the following line:
[self.mapView setShowsUserLocation:YES];

Resources