I've been struggling to change the camera's value in the Google Maps API. So that it displays the users position as soon as you open the app, using CoreLocation and passing those values into the camera.
There's some other tutorials online, but nothing that works for me.
If you could help it would be massively appreciated.
#implementation HMSBViewController{
CLLocationManager *_locationManager;
}
- (NSString *)deviceLocation
{
NSString *theLocation = [NSString stringWithFormat:#"latitude: %f longitude: %f", _locationManager.location.coordinate.latitude, _locationManager.location.coordinate.longitude];
return theLocation;
}
- (void)viewDidLoad
{
//mapView.settings.myLocationButton = YES;
mapView.myLocationEnabled = YES;
_locationManager = [[CLLocationManager alloc] init];
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; // Setting the accuracy to the best possible
if([_locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
[_locationManager requestAlwaysAuthorization];
}
[_locationManager startUpdatingLocation];
}
- (void)loadView{
CLLocation *myLocation = mapView.myLocation;
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(myLocation.coordinate.latitude, myLocation.coordinate.longitude);
marker.title = #"Current Location";
marker.map = mapView;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:_locationManager.location.coordinate.latitude
longitude:_locationManager.location.coordinate.longitude
zoom:6];
mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = mapView;
NSLog(#"%f, %f", _locationManager.location.coordinate.latitude, _locationManager.location.coordinate.longitude);
}
When the app runs the coordinates are always set to zero.
Thanks
This happens because Google Maps API only get your current location after it's placed on the controller view. To solve this limitation you should create a notification that tells your controller when the current location is available.
On your viewWillApper add this observer:
[mapView addObserver:self forKeyPath:#"myLocation" options:0 context:nil];
Then add -(void)observeValueForKeyPath:ofObject:change:context: that is called everytime the keyPath value changes. On this method you can now get the current location and animate the map to it so it shows centered in there. At the end of the method you should deregister the observer since if it's not deregistered this method will be called every time the position changes.
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if([keyPath isEqualToString:#"myLocation"]) {
CLLocation *location = [object myLocation];
CLLocationCoordinate2D target = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
[mapView animateToLocation:target];
#try {
[map removeObserver:self forKeyPath:#"myLocation"];
} #catch(id exception){
//do nothing, obviously it wasn't attached because an exception was thrown
}
}
}
The map can take a while to get the current location, but it's usually fast.
Related
i am getting current attitude and longitude of device and print it with nslog but now how will update these latttitude and longitude on map accordingly. here is my code please look at this.
- (void)viewDidLoad {
[super viewDidLoad];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
longitude:151.2086
zoom:12];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.settings.myLocationButton = YES;
self.view = mapView_;
mapView_.settings.compassButton = YES;
[self startStandardUpdates];
}
- (void)startStandardUpdates
{
// Create the location manager if this object does not
// already have one.
NSLog(#"startupdatelocation");
if (nil == _locationManager)
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
// Set a movement threshold for new events.
_locationManager.distanceFilter = 10; // meters
[self.locationManager startUpdatingLocation];
}
- (void)startSignificantChangeUpdates
{
// Create the location manager if this object does not
// already have one.
if (nil == _locationManager)
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
[self.locationManager startMonitoringSignificantLocationChanges];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// If it's a relatively recent event, turn off updates to save power.
CLLocation* location = [locations lastObject];
NSLog(#"location %#", location);
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0) {
// If the event is recent, do something with it.
NSLog(#"latitude %+.6f, longitude %+.6f\n",location.coordinate.latitude,
location.coordinate.longitude);
}
}
i am printing current latitude and longitude now how will i show this location on map also please help me in this situation.
Current device location should be requested from the iOS - https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html
than you could show the marker with device location on the map
I want to move the marker on basis of lat,long which i'm getting continously I'm doing this like below...
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations (NSArray<CLLocation *> *)locations
{
CLLocationCoordinate2D coor2D = CLLocationCoordinate2DMake(longitude, latitude);
self.marker.position = coor2D;
}
The method is updating lat long but the markers is not moving why...
In info.plist I have added..
Try this, assuming you have set your delegate:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations (NSArray<CLLocation *> *)locations
{
CLLocationCoordinate2D coor2D = CLLocationCoordinate2DMake(longitude, latitude);
self.marker.position = coor2D;
[self.mapView animateToLocation:coord2D.coordinate]
}
If all you're trying to do is update your current location. You should probably just use KVO for that.
#implementation MyLocationViewController {
GMSMapView *mapView_;
BOOL firstLocationUpdate_;
}
- (void)viewDidLoad {
[super viewDidLoad];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
longitude:151.2086
zoom:12];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.settings.compassButton = YES;
mapView_.settings.myLocationButton = YES;
// Listen to the myLocation property of GMSMapView.
[mapView_ addObserver:self
forKeyPath:#"myLocation"
options:NSKeyValueObservingOptionNew
context:NULL];
self.view = mapView_;
// Ask for My Location data after the map has already been added to the UI.
dispatch_async(dispatch_get_main_queue(), ^{
mapView_.myLocationEnabled = YES;
});
}
- (void)dealloc {
[mapView_ removeObserver:self
forKeyPath:#"myLocation"
context:NULL];
}
#pragma mark - KVO updates
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (!firstLocationUpdate_) {
// If the first location update has not yet been recieved, then jump to that
// location.
firstLocationUpdate_ = YES;
CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
mapView_.camera = [GMSCameraPosition cameraWithTarget:location.coordinate
zoom:14];
}
}
#end
Hi i am beginner in Ios and in my project i am using Google SDK for getting route when user walking or driving along the road
But i am not able to get current location and showing in my x code console 0.0 and 0.0(latitude and longitude values) please help me some one for getting current location
My code is below:-
#import "ViewController.h"
#interface ViewController ()
{
GMSMapView *_mapView;
NSMutableArray *_coordinates;
LRouteController *_routeController;
GMSPolyline *_polyline;
GMSMarker *_markerStart;
GMSMarker *_markerFinish;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_mapView.settings.myLocationButton = YES;
_mapView.myLocationEnabled = YES;
_mapView.delegate = self;
}
- (void)loadView{
CLLocation *myLocation = _mapView.myLocation;
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(myLocation.coordinate.latitude, myLocation.coordinate.longitude);
marker.title = #"Current Location";
marker.map = _mapView;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:myLocation.coordinate.latitude
longitude:myLocation.coordinate.longitude
zoom:6];
_mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = _mapView;
NSLog(#"%f, %f", myLocation.coordinate.latitude, myLocation.coordinate.longitude);
}
#pragma mark - GMSMapViewDelegate
- (void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate
{
_polyline.map = nil;
_markerStart.map = nil;
_markerFinish.map = nil;
[_coordinates addObject:[[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude]];
if ([_coordinates count] > 1)
{
[_routeController getPolylineWithLocations:_coordinates travelMode:TravelModeDriving andCompletitionBlock:^(GMSPolyline *polyline, NSError *error) {
if (error)
{
NSLog(#"%#", error);
}
else if (!polyline)
{
NSLog(#"No route");
[_coordinates removeAllObjects];
}
else
{
_markerStart.position = [[_coordinates objectAtIndex:0] coordinate];
_markerStart.map = _mapView;
_markerFinish.position = [[_coordinates lastObject] coordinate];
_markerFinish.map = _mapView;
_polyline = polyline;
_polyline.strokeWidth = 3;
_polyline.strokeColor = [UIColor blueColor];
_polyline.map = _mapView;
}
}];
}
}
#end
getting the location is an asynchronous process. So you need to 'wait' for the location to be updated -- in this case by observing "myLocation"
observe location
this code only works if _mapView is onscreen
// Listen to the myLocation property of GMSMapView.
[_mapView addObserver:self
forKeyPath:#"myLocation"
options:NSKeyValueObservingOptionNew
context:NULL];
// Ask for My Location data after the map has already been added to the UI.
dispatch_async(dispatch_get_main_queue(), ^{
_mapView.myLocationEnabled = YES;
});
get the location updates:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (!_firstLocationUpdate) {
// If the first location update has not yet been recieved, then jump to that
// location.
_firstLocationUpdate = YES;
CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
_mapView.camera = [GMSCameraPosition cameraWithTarget:location.coordinate
zoom:14];
}
}
I've cannot change the camera's value in the Google Maps API. So that it displays the users position as soon as you open the app, using CoreLocation and passing those values into the camera. I've had a look at some tutorials online, but I haven't managed to solve it yet.
I've tried to make a method that observes when the GPS coordinates have been found and then pass them to the camera. But it still shows 0,0.
#implementation HMSBViewController{
CLLocationManager *_locationManager;
}
#synthesize mapView;
- (NSString *)deviceLocation
{
NSString *theLocation = [NSString stringWithFormat:#"latitude: %f longitude: %f", _locationManager.location.coordinate.latitude, _locationManager.location.coordinate.longitude];
return theLocation;
}
- (void)viewDidLoad
{
mapView.delegate = self;
//[mapView addObserver:self forKeyPath:#"myLocation" options:0 context:nil];
//mapView.settings.myLocationButton = YES;
mapView.myLocationEnabled = YES;
_locationManager = [[CLLocationManager alloc] init];
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; // Setting the accuracy to the best possible
if([_locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
[_locationManager requestAlwaysAuthorization];
}
[_locationManager startUpdatingLocation];
}
- (void)viewWillAppear{
[mapView addObserver:self forKeyPath:#"myLocation" options:0 context:nil];
}
- (void)loadView{
CLLocation *myLocation = mapView.myLocation;
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(myLocation.coordinate.latitude, myLocation.coordinate.longitude);
marker.title = #"Current Location";
marker.map = mapView;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:_locationManager.location.coordinate.latitude
longitude:_locationManager.location.coordinate.longitude
zoom:1];
mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = mapView;
NSLog(#"%f, %f", _locationManager.location.coordinate.latitude, _locationManager.location.coordinate.longitude);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if([keyPath isEqualToString:#"myLocation"]) {
CLLocation *location = [object myLocation];
CLLocationCoordinate2D target = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
[mapView animateToLocation:target];
#try {
[mapView removeObserver:self forKeyPath:#"myLocation"];
} #catch(id exception){
;
}
}
}
Any suggestions would be much appreciated!
You need to set the locationManager delegate and then use the delegate method
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
to retrieve the location. Once you have the location, then call your map function to populate Google
At the start of the application, the application request for user's current location. AlertBox pop up regarding about giving the app permission to access location services. My question is how do I get the location right after the user allows location services?
My Code
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[self.locationManager startUpdatingLocation];
latitude = [NSString stringWithFormat:#"%f",self.locationManager.location.coordinate.latitude];
longtitude = [NSString stringWithFormat:#"%f",self.locationManager.location.coordinate.longitude];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[latitude floatValue]
longitude:[longtitude floatValue]
zoom:16];
mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView.delegate = self;
mapView.myLocationEnabled = YES;
self.view = mapView;
// Creates a marker in the center of the map.
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake([latitude intValue], [longtitude intValue]);
marker.title = #"Current Location";
marker.map = mapView;
}
Is there any way to get user's current location once it allows location services?
My codes only works when user allows the location services then restart the app.
I tried implementing the code below as well. But the NSLog is not appearing.
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *loc = locations.lastObject;
double speed = loc.speed;
NSLog(#"speed-----%f ", speed);
}
Any advice? Did I left out anything?
Just put:
self.locationManager.delegate = self;
After this line:
self.locationManager = [[CLLocationManager alloc] init];
Note:
Make sure you have added CLLocationManagerDelegate in your header file.
My answer comes a year too late and I'm using Swift 2 but for anyone else requiring an answer:
You need to update the mapview in the didUpdateLocations delegate. Please see the code below.
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
mapUIView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
locationManager.stopUpdatingLocation()
}
}