how to get current location in google map sdk in iphone - iphone

I want to set camera on current location and zoom level upto 10.
So I have written code like this and for current location i get hint from this post.
How to use delegates in Google map API for IOS 6
here is my code
mapView_=[[GMSMapView alloc]initWithFrame:CGRectZero];
CLLocationCoordinate2D currentPosition = mapView_.myLocation.coordinate;
GMSCameraPosition* camera =
[GMSCameraPosition cameraWithTarget: currentPosition zoom: 10];
mapView_.camera = camera;
mapView_.delegate=self;
mapView_.mapType = kGMSTypeSatellite;
mapView_.myLocationEnabled = YES;
self.view = mapView_;
mapView_.settings.myLocationButton = YES;
But coordinate is 0.00 in device.
Please Any Can help to solve out this issue?

Try this:
#property (nonatomic, retain) IBOutlet GMSMapView *googleMapView;
#property (nonatomic, retain) CLLocationManager *locationManager;
- (void)showCurrentLocation {
_googleMapView.myLocationEnabled = YES;
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:newLocation.coordinate.latitude
longitude:newLocation.coordinate.longitude
zoom:17.0];
[_googleMapView animateToCameraPosition:camera];
//...
}

You can add an observer for the myLocation property as follows:
[self.mapView addObserver:self
forKeyPath:#"myLocation"
options:(NSKeyValueObservingOptionNew |
NSKeyValueObservingOptionOld)
context:NULL];
You should then implement the following method:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if ([keyPath isEqualToString:#"myLocation"]) {
NSLog(#"My position changed");
}
}

write this line in info plist
CLLocationManager requestAlwaysAuthorization (string) abcd
//code and also set annotation pin
.h
#import<MapKit/Mapkit.h>
CLLocationManager *locationManager;
#property(nonatomic, weak) IBOutlet MKMapView* mapView;
#property(nonatomic,retain)CLLocationManager* locationManager;
- (id)init {
self = [super init];
if(self != nil) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
}
return self;
}
in viewDidLoad
_mapView.showsUserLocation = YES;
_mapView.mapType = MKMapTypeStandard;
_mapView.delegate = self;
if(IS_OS_8_OR_LATER) {
[self.locationManager requestAlwaysAuthorization];
}
[self.locationManager startUpdatingLocation];
// NSDictionary *dictlatitude = [_dict objectForKey:#"latitude"];
float strlatitude = [[_dict objectForKey:#"latitude"] floatValue];
// NSDictionary *dictlongitude = [_dict objectForKey:#"longitude"];
float strlongitude = [[_dict objectForKey:#"longitude"] floatValue];
NSLog(#"Staring Point latitude : %f", strlatitude);
NSLog(#"Staring Point longitude: %f", strlongitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.005;
span.longitudeDelta = 0.005;
CLLocationCoordinate2D location;
location.latitude = strlatitude;
location.longitude = strlongitude;
region.span = span;
region.center = location;
[_mapView setRegion:region animated:YES];
MyAnnotation *ann = [[MyAnnotation alloc] init];
ann.title=#"name of the pin";
ann.coordinate = region.center;
[_mapView addAnnotation:ann];

Related

MapView only shows correct location after 2nd load

Im struggling with a mapview on my app. When loading the screen with the mapview on, the map just opens to the default location for mapviews. However, when I return to the previous scren and then launch the map for a 2nd time, the correct location is displayed.
Obviously, this isn't ideal.
Any suggestions please?
My code is:
CLLocation *mapLocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
[[self map] setCenterCoordinate:[mapLocation coordinate]];
[[self map] setRegion: MKCoordinateRegionMakeWithDistance([mapLocation coordinate], 1000, 1000)];
MapAnnotation *annotation = [[MapAnnotation alloc] init];
[annotation setCoordinate:[mapLocation coordinate]];
[[self map] addAnnotation:annotation];
Thank you!
I set the current location like this:
Location.h:
#interface WhereamiViewController : UIViewController <CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate> {
CLLocationManager *locationManager;
MKMapView *worldView;
IBOutlet UIActivityIndicatorView *activityIndicator;
IBOutlet UITextField *locationTextField;
}
- (void)findLocation;
- (void)foundLocation:(CLLocation *)loc;
- (IBAction)setMapTyp:(id)sender;
#property MKMapType mapType;
#property (nonatomic, retain) IBOutlet MKMapView *worldView;
#property (nonatomic, readonly) NSDate *currentDate;
#end
Location.m:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSLog(#"%#", newLocation);
NSTimeInterval t = [[newLocation timestamp] timeIntervalSinceNow];
if (t < -180) {
return;
}
[self foundLocation:newLocation];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
CLLocationCoordinate2D loc = [userLocation coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 250, 250);
[worldView setRegion:region animated:YES];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
NSLog(#"Could not find location: %#", error);
}
- (void)findLocation {
[locationManager startUpdatingLocation];
[activityIndicator startAnimating];
[locationTextField setHidden:YES];
}
- (void)foundLocation:(CLLocation *)loc {
CLLocationCoordinate2D coord = [loc coordinate];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"HH:mm, dd. MMM. yyyy "];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
MyOwnMapPoint *mp = [[MyOwnMapPoint alloc] initWithCoordinate:coord
title:[locationTextField text]
subtitle:dateString];
NSLog(#"Die Uhrzeit ist: %#", dateString);
[worldView addAnnotation:mp];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 250, 250);
[worldView setRegion:region animated:YES];
//Reset the UI
[locationTextField setText:#""];
[activityIndicator stopAnimating];
[locationTextField setHidden:NO];
[locationManager stopUpdatingLocation];
}
Hope its giving you an idea!

Current Location in the Simulator

Im doing an app in which i have to find the current location of the user.can i get the current location of the user in the iOS 5 simulator by using CLLocationmanager?
xcode - Edit Scheme - Run you.app - Option
check Allow Location Simulation, then select "Default Location"
Add GPX File to Project
the format like this
In Xcode, you can select the location to simulate using a small button above the console.
- (void)viewDidLoad{
[super viewDidLoad];
self.title = #"MapView";
self.navigationController.navigationBarHidden = NO;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
- (void) loadPin {
iCodeBlogAnnotation *appleStore1;
CLLocationCoordinate2D workingCoordinate;
workingCoordinate.latitude = [latitude doubleValue];
workingCoordinate.longitude = [longitude doubleValue];
appleStore1 = [[iCodeBlogAnnotation alloc] initWithCoordinate:workingCoordinate];
[appleStore1 setTitle:[NSString stringWithFormat:#"Default Point"]];
//[appleStore1 setSubtitle:[NSString stringWithFormat:#"Distance %.2f Miles",miles]];
[appleStore1 setAnnotationType:iCodeBlogAnnotationTypeEDU];
[mapView addAnnotation:appleStore1];
[(MKMapView*)self.mapView selectAnnotation:appleStore1 animated:NO];
MKCoordinateRegion region;
region.center.latitude = [latitude doubleValue];
region.center.longitude = [longitude doubleValue];
region.span.latitudeDelta = .5;
region.span.longitudeDelta = .5;
[mapView setRegion:region animated:YES];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
latitude = [[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.latitude];
longitude = [[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.longitude];
[locationManager stopUpdatingLocation];
if (latitude > 0) {
[self loadPin];
}
}

How to call MKAnnotation Method in another Method using Objective C

-(MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation {
}
MKAnnotationView method is used to display icon in map. How to call MKAnnotationView method in -didUpdateToLocation method using objective-c?
i'm not sure if this is what you want but :
here's the class that i've written for annotations :
.h file :
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface MyLocation : NSObject <MKAnnotation> {
NSString *_name;
NSString *_address;
CLLocationCoordinate2D _coordinate;
}
#property (copy) NSString *name;
#property (copy) NSString *address;
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
- (id)initWithName:(NSString*)name address:(NSString*)address coordinate:(CLLocationCoordinate2D)coordinate;
#end
and the .m file :
#import "MyLocation.h"
#implementation MyLocation
#synthesize name = _name;
#synthesize address = _address;
#synthesize coordinate = _coordinate;
- (id)initWithName:(NSString*)name address:(NSString*)address coordinate:(CLLocationCoordinate2D)coordinate {
if ((self = [super init])) {
_name = [name copy];
_address = [address copy];
_coordinate = coordinate;
}
return self;
}
- (NSString *)title {
if ([_name isKindOfClass:[NSNull class]])
return #"Unknown charge";
else
return _name;
}
- (NSString *)subtitle {
return _address;
}
#end
and in the view controller i am calling location manager like :
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = 10.0; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
and then in the location manager's delegate method i am setting my map like this:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
[locationManager stopUpdatingLocation];
//CLLocationCoordinate2D newCoord = { newLocation.coordinate.latitude, newLocation.coordinate.longitude };
CLLocationCoordinate2D centerPoint = { newLocation.coordinate.latitude, newLocation.coordinate.longitude };
MKCoordinateSpan coordinateSpan = MKCoordinateSpanMake(0.01, 0.01);
MKCoordinateRegion coordinateRegion = MKCoordinateRegionMake(centerPoint, coordinateSpan);
["your-map-name" setRegion:coordinateRegion];
["your-map-name" regionThatFits:coordinateRegion];
CLLocationCoordinate2D cordPoint = { latitude_value, longitude_value };
MyLocation *annotation = [[MyLocation alloc] initWithName:#"title of the pin" address:#"some sub string" coordinate:cordPoint] ;
["your-map-name" addAnnotation:annotation]; }
this is how i solved my annotation and map problem ..
i hope this helps..

How to get user's location in a later screen for the MapKit?

I am building a navigation-based app for the iPhone, where I calculate the user's geolocation in the RootViewController (this is the code for my RootViewController.h) class:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "SecondViewController.h"
#import <sqlite3.h>
#interface RootViewController : UITableViewController <CLLocationManagerDelegate>{
SecondViewController *secondViewController;
NSUInteger numUpdates;
CLLocationManager *lm;
CLLocation *firstLocation;
CLLocation *secondLocation;
}
#property (nonatomic, retain) SecondViewController *secondViewController;
#property (nonatomic, retain) NSMutableArray *restaurants;
#property (nonatomic, retain) NSArray *sortedRestaurants;
here is the code for my RootViewController.m class:
- (void) locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D location;
NSString *lat = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.latitude];
double lat1 = newLocation.coordinate.latitude;
location.latitude = newLocation.coordinate.latitude; //setting the latitude property of the location variable
NSString *lng = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.longitude];
double lon1 = newLocation.coordinate.longitude;
location.longitude = newLocation.coordinate.longitude; //setting the longitude property of the location variable
MapViewController *mController = [[MapViewController alloc] initWithNibName:#"MapViewController" bundle:[NSBundle mainBundle]];
self.mapViewController = mController;
[mController release];
self.mapViewController.userCoord = [[[CLLocation alloc] initWithLatitude:location.latitude longitude:location.longitude] autorelease];
//in the above line I get the error, "incompatible type for argument 1 of 'setUserCoord' "
[lm stopUpdatingLocation];
Because I am calculating the user's geolocation in the RootViewController class, I would like to re-use these value when I use the MapKit later on in the application in the MapViewController.m class:
- (void)viewDidLoad {
[super viewDidLoad];
MKCoordinateRegion region;
MKCoordinateSpan span;
region.center = userCoord;
/* userCoord is declared as an object of type CLLocationCoordinate2D
in MapViewController.h, and is declared as a property, and then
synthesized in the .m class. Even though I am trying to center
the map on the user's coordinates, the map is neither centering,
nor zooming to my settings. */
span.latitudeDelta = 0.2;
span.longitudeDelta = 0.2;
region.span = span;
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
mapView.showsUserLocation = YES;
[mapView setRegion:region animated:YES];
RestaurantAnnotation *rAnnotation = [[RestaurantAnnotation alloc] init];
rAnnotation.title = restaurantObj.name;
rAnnotation.subTitle = restaurantObj.address;
CLLocationCoordinate2D newCoord = {restaurantObj.latitude, restaurantObj.longitude};
rAnnotation.coordinate = newCoord;
[mapView addAnnotation:rAnnotation];
}
I would like the map to be centered on the user's location, and choose appropriate span values as well.
There are a lot of ways to do this, the way I've done it is to store the location in NSUserDefaults and access that value later when I'm presenting my map. The benefit of doing it this way is that the user's location persists between runs, so if the next time they open the app they're having trouble getting a GPS signal, you still have a location to display.
This code may not be 100%, i'm writing it from memory:
#define latKey #"latKey"
#define lonKey #"lonKey"
#define locationKey #"locationKey"
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSNumber *lat = [NSNumber numberWithDouble:newLocation.coordinate.latitude];
NSNumber *lon = [NSNumber numberWithDouble:newLocation.coordinate.longitude];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:lat, latKey, lon, lonKey, nil];
[[NSUserDefaults standardUserDefaults] addObjectForKey:locationKey];
}
- (void)viewDidLoad {
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] dictForKey:locationKey];
CLLocation *location = [[CLLocation alloc] initWithLatitude:[[dict objectForKey:lat] doubleValue] longitude:[[dict objectForKey:lon] doubleValue]];
}

Obtain user location from a MKMapView

Is it possible to use the MKMapView's own location manager to return the users current location to pass into a webservice?
I have mapView.showsUserLocation=YES; and this does return a valid blue dot at my location, but in the simulator, its Cupertino - which is fine, but when i look at
mapView.userLocation.coordinate.latitude, its equal to 180, whereas a CLLocationManager returns the correct one, 37.3317.
I want to avoid having multiple location managers for my three tabs, so using the mapViews own would be helpful.
Thanks.
You can get the user location from the MKMapView. You are just missing a property in your retrieval of it. It should be:
mapView.userLocation.location.coordinate.latitude;
userLocation only stores a CLLocation location attribute and a BOOL updating attribute. You must go to the location attribute to get coordinates.
-Drew
EDIT: The MKMapView's userLocation does not update until the map has finished loading, and checking too early will return zeros. To avoid this, I suggest using the MKMapViewDelegate method
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation.
So, to use a unique CLLocateManager, you can create a class to be the delegate for all you maps., so, instead of doing:
self.locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
Do something like:
self.locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = mySharedDelegate;
Where mySharedDelegate is your class with all the CLLocationManager delegate methods.
You can only get a valid coordinate for the userLocation, after the first calling of - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
When this method is called it is because the GPS has found the new location and so the blue dot will be moved to there and the userLocation will have the new coordinate.
Use the following method on your CLLocationManager delegate to log the current location when it is found:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"---------- locationManager didUpdateToLocation");
location=newLocation.coordinate;
NSLog(#"Location after calibration, user location (%f, %f)", _mapView.userLocation.coordinate.latitude, _mapView.userLocation.coordinate.longitude);
}
Have you got the idea?
Cheers,
VFN
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"welcome into the map view annotation");
// if it's the user location, just return nil.
if ([annotation isKindOfClass:[MyMapannotation class]])
{
MyMapannotation *annotation12=(MyMapannotation *)annotation;
// try to dequeue an existing pin view first
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKPinAnnotationView* pinView = [[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] ;
pinView.animatesDrop=YES;
pinView.canShowCallout=YES;
pinView.pinColor=MKPinAnnotationColorPurple;
pinView.tag=annotation12.tag;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
rightButton.tag=annotation12.tag;
[rightButton addTarget:self
action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
UIImageView *profileIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"artpin"]];
pinView.image = profileIconView.image;
return pinView;
}
else
return nil;
}
-(IBAction)showDetails:(id)sender
{
UIButton *btn=(UIButton *)sender;
}
-(void)Load_mapview
{
for (int i=0; i<[arr_nearby count]; i++)
{
NSNumber *latitude = [[[[arr_nearby objectAtIndex:i] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lat"];
NSNumber *longitude = [[[[arr_nearby objectAtIndex:i] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lng"];
NSString *title = [[arr_nearby objectAtIndex:i] valueForKey:#"name"];
//Create coordinates from the latitude and longitude values
CLLocationCoordinate2D coord;
coord.latitude = latitude.doubleValue;
coord.longitude = longitude.doubleValue;
MyMapannotation *annotation = [[MyMapannotation alloc] initWithTitle:title AndCoordinate:coord andtag:i];
[_map_nearby addAnnotation:annotation];
// [annotations addObject:annotation];
}
[self zoomToLocation];
}
-(void)zoomToLocation
{
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = [[[[[arr_nearby objectAtIndex:0] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lat"] floatValue];
zoomLocation.longitude= [[[[[arr_nearby objectAtIndex:0] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lng"] floatValue];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 7.5*5,7.5*5);
[_map_nearby setRegion:viewRegion animated:YES];
[_map_nearby regionThatFits:viewRegion];
}
//
// MyMapannotation.h
// IOS_Googgle
//
// Created by Vivek Chauhan on 27/06/16.
// Copyright (c) 2016 anand. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface MyMapannotation : NSObject <MKAnnotation>
#property (nonatomic,copy) NSString *title;
#property (nonatomic,assign) int tag;
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
-(id) initWithTitle:(NSString *) title AndCoordinate:(CLLocationCoordinate2D)coordinate andtag:(int)tagofbutton;
#end
//
// MyMapannotation.m
// IOS_Googgle
//
// Created by Vivek Chauhan on 27/06/16.
// Copyright (c) 2016 anand. All rights reserved.
//
#import "MyMapannotation.h"
#implementation MyMapannotation
#synthesize coordinate=_coordinate;
#synthesize title=_title;
#synthesize tag=_tag;
-(id) initWithTitle:(NSString *) title AndCoordinate:(CLLocationCoordinate2D)coordinate andtag:(int)tagofbutton
{
self = [super init];
_title = title;
_coordinate = coordinate;
_tag=tagofbutton;
return self;
}
#end