I am using google maps api in my app. I've got two buttons in my app. the first button adds a marker (pin) in my map.
Now I want the second button to move the added pin to the center of the page horizontally and make it move to 25% off the top of the page. I want the camera (The area that the user is viewing) to move it too.
this is my code:
#implementation ViewController
{
double latitudes;
double longitudes;
CLLocationManager *locationManager;
GMSMapView *mapView_;
}
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[self GetMyLocation];
UIButton *pinButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
pinButton.frame = CGRectMake(self.view.frame.size.width-80,self.view.frame.size.height-80, 60, 60);
[pinButton setTitle:#"Self" forState:UIControlStateNormal];
[pinButton setBackgroundColor:[UIColor whiteColor]];
[pinButton addTarget:self action:#selector(ShowMyLocation:) forControlEvents:UIControlEventTouchUpInside];
UIButton *add = [UIButton buttonWithType:UIButtonTypeRoundedRect];
add.frame = CGRectMake(20,self.view.frame.size.height-80, 60, 60);
[add setTitle:#"add" forState:UIControlStateNormal];
[add setBackgroundColor:[UIColor whiteColor]];
[add addTarget:self action:#selector(Move:) forControlEvents:UIControlEventTouchUpInside];
// Create a GMSCameraPosition that tells the map to display the
// nokte mohem ine ke baadan ye logitude & latitude default ezafe kon chon shaiad tuie ye sharaiete tokhmi ke hamid esrar dare va ye kasi mariz bood dastresie GPS ro ghat kard
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitudes longitude:longitudes zoom:14];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.myLocationEnabled = YES;
[mapView_ setMapType:kGMSTypeNormal];
self.view = mapView_;
[mapView_ addSubview:pinButton];
[mapView_ addSubview:add];
}
- (IBAction)Move:(id)sender{
//move marker place
}
- (IBAction)ShowMyLocation:(id)sender{
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(coor.latitude,coor.longitude);
marker.title = #"I'm Here";
marker.snippet = #"Rahnova Co.";
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.map = mapView_;
}
- (void) GetMyLocation{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitudes = currentLocation.coordinate.longitude;
latitudes = currentLocation.coordinate.latitude;
}
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitudes longitude:longitudes zoom:14];
[mapView_ animateToCameraPosition:camera];
}
Try this code:-
On the header of your .M implementation file, you have to implement the GMSMapViewDelegate.
#interface YourViewController ()<GMSMapViewDelegate>
Inside viewDidLoad, you have to set the mapView delegate to self.
mapView_.delegate=self;
For the delegate method:-
-(BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker{
[mapView animateToLocation:marker.position];
return YES;
}
It shall help you to go to the marker position when you tap on it.
You can move markers with animation. Here is code
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CATransaction.begin()
CATransaction.setValue(2.0, forKey: kCATransactionAnimationDuration)
CATransaction.setCompletionBlock {
self.driverMarker.groundAnchor = CGPoint(x: 0.5, y: 0.5)
}
self.mapView.animate(to: GMSCameraPosition.camera(withLatitude: locations[0].coordinate.latitude, longitude: locations[0].coordinate.longitude, zoom: 17))
self.driverMarker.position = locations[0].coordinate
CATransaction.commit()
self.driverMarker.map = self.mapView
}
Related
I am new in iOS and I am facing problem regarding to show India maps on Google Maps
My code is like this first
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:18.516726
longitude:73.856255
zoom:3];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
//Scrollview
mapView = [GMSMapView mapWithFrame:CGRectMake(10, 140, 750, 350) camera:camera];
}
else
{
//Scrollview
mapView = [GMSMapView mapWithFrame:CGRectMake(10, 140, 550, 350) camera:camera];
}
But When I used UIView and create it using IBOutlet like this
IBOutlet GMSMapView *mapView;
Than the above code not work.How can I show the India map first by using above coordinate.Thanks in Advance!
Get current Location coordinate and Pass on these camera position
CLLocationCoordinate2D coordinate;
float latitude;
float longitude;
coordinate = [self getLocation];
latitude = coordinate.latitude;
longitude = coordinate.longitude;
//pragma mark ----: GET Coordinate2D :----
-(CLLocationCoordinate2D) getLocation
{
CLLocation *location = [_locationManager location];
coordinate = [location coordinate];
return coordinate;
}
CGRect frame = CGRectMake(0, 0, kSCREEN_WIDTH,kSCREEN_HEIGHT);
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitude longitude:longitude zoom:12];
mapView_ = [GMSMapView mapWithFrame:frame camera:camera];
mapView_.myLocationEnabled = YES;
mapView_.delegate = self;
[mapView_ setCamera:camera];
Below is a Sample Code:
#import <GoogleMaps/GoogleMaps.h>
#interface ViewController ()<GMSMapViewDelegate>
{
GMSMapView *mapView;
GMSMarker *marker;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self showMarker];
}
- (void)showMarker
{
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:18.516726 longitude:73.856255 zoom:3];
mapView_ = [GMSMapView mapWithFrame:self.view.bounds camera:camera];
[self.view addSubview:mapView];
}
#end
Try This code:
#interface ViewController ()<GMSMapViewDelegate>
{
GMSMapView *mapView_;
}
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:18.516726
longitude:73.856255
zoom:3];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
//Scrollview
mapView_ = [GMSMapView mapWithFrame:CGRectMake(10, 140, 750, 350) camera:camera];
}
else
{
//Scrollview
mapView_ = [GMSMapView mapWithFrame:CGRectMake(10, 140, 550, 350) camera:camera];
}
NSError *error;
// Set the map style by passing a valid JSON string.
GMSMapStyle *style = [GMSMapStyle styleWithJSONString:kMapStyle error:&error];
if (!style) {
NSLog(#"The style definition could not be loaded: %#", error);
}
mapView_.mapStyle = style;
mapView_.mapType = kGMSTypeNormal;
[self.scrllView addSubview:mapView_];
[_btnMap setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
mapView_.delegate = self;
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(
18.516726,
73.856255);
GMSMarker *marker = [GMSMarker markerWithPosition:position];
marker.map = mapView_;
marker.icon=[UIImage imageNamed:#"locationBlue"];
marker.title = #"From";
I'm using Google Maps SDK for iOS (version 2.1.1) with Xcode 8. I added a UIView and set its class to GMSMapView and linked up with an IBOutlet called mapView.
double bearing;
int zoomLevel;
- (void)viewDidLoad {
[super viewDidLoad];
bearing = 30;
zoomLevel = 20;
_locationManager = [[CLLocationManager alloc] init];
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
_locationManager.delegate = self;
[_locationManager startUpdatingLocation];
if([CLLocationManager headingAvailable]) {
_locationManager.headingFilter = 5;
[_locationManager startUpdatingHeading];
}
mapView.myLocationEnabled = YES;
mapView.settings.tiltGestures = NO;
mapView.settings.scrollGestures = NO;
// obtain my position
CLLocation *myLocation = mapView.myLocation;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:myLocation.coordinate.latitude
longitude:myLocation.coordinate.longitude
zoom:zoomLevel
bearing:bearing
viewingAngle:45];
mapView.camera = camera;
}
The View Controller uses 2 delegates : CLLocationManagerDelegate and GMSMapViewDelegate.
Updating map location is not a problem, but when I rotate the map, since the bearing value has not changed at all, once the location is updated, the bearing is reset and cancelled the rotation. How can I update the bearing after I rotate the map?
Here is the didUpdateLocations: delegate function:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLLocation *myLocation = [locations lastObject];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:myLocation.coordinate.latitude
longitude:myLocation.coordinate.longitude
zoom:zoomLevel
bearing:bearing
viewingAngle:45];
[mapView animateToCameraPosition:camera];
}
My idea is to rotate the map exactly like the mobile game PokemonGO.
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];
#import "MyLocationViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#interface MyLocationViewController ()
#end
#implementation MyLocationViewController {
GMSMapView *mapView_;
CLLocationManager *locationManager;
}
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
NSLog(#"Current identifier: %#", [[NSBundle mainBundle] bundleIdentifier]);
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86
longitude:151.20
zoom:6];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.myLocationEnabled = YES;
self.view = mapView_;
//Add text field
UITextField *textField = [[UITextField alloc] init];
textField.frame = CGRectMake(mapView_.bounds.size.width - 290, mapView_.bounds.size.height - 48, 180, 40);
textField.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = #"enToi UHMUH Bar Heya";
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.delegate = self;
[mapView_ addSubview:textField];
[mapView_ resignFirstResponder];
[mapView_ bringSubviewToFront:textField];
[textField becomeFirstResponder];
//Add Send Chat Button to UI
UIButton *sendButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
sendButton.frame = CGRectMake(mapView_.bounds.size.width - 100, mapView_.bounds.size.height - 48, 90, 40);
sendButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
[sendButton setTitle:#"Send" forState:UIControlStateNormal];
[mapView_ addSubview:sendButton];
// Creates a marker in the center of the map.
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(-33.86, 151.20);
marker.title = #"Sydney";
marker.map = mapView_;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Failed to get your location!"
delegate:nil
cancelButtonTitle:#"OKAY"
otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currentLocation = [locations lastObject];
NSLog(#"didUpdateLocations: %#", currentLocation);
if (currentLocation != nil) {
GMSCameraPosition *newSpot = [GMSCameraPosition cameraWithLatitude:currentLocation.coordinate.latitude
longitude:currentLocation.coordinate.longitude
zoom:6];
[mapView_ setCamera:newSpot];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Here's my header file:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface MyLocationViewController : UIViewController <CLLocationManagerDelegate, UITextFieldDelegate>
#property (nonatomic, retain) UITextField *textField;
#end
I am not using Interface Builder. When the app loads I can see my textfield and button. The button does its default toggle behavior when touched. The text field is not editable - can't bring up the keyboard by clicking it, cant type into, etc.
I did run someone's method to determine if a frame is out of its parent view's bounds and it came back as saying it was out of bounds - but I'm not quite sure how to resolve this.
The googleMapView has a BlockingGestureRecognizer that blocks all user input. don't add the textfield to the map OR remove the blocker:
// Remove the GMSBlockingGestureRecognizer of the GMSMapView.
+ (void)removeGMSBlockingGestureRecognizerFromMapView:(GMSMapView *)mapView
{
if([mapView.settings respondsToSelector:#selector(consumesGesturesInView)]) {
mapView.settings.consumesGesturesInView = NO;
}
else {
for (id gestureRecognizer in mapView.gestureRecognizers)
{
if (![gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
{
[mapView removeGestureRecognizer:gestureRecognizer];
}
}
}
}
Add this if you need touch event enable in uitextfield
for (id gestureRecognizer in mapView_.gestureRecognizers)
{
NSLog(#"mapview recognizer %#",gestureRecognizer);
if (![gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
{
[mapView_ removeGestureRecognizer:gestureRecognizer];
}
}
Add Your UITextfield or UISearchbar in to subview of Mapview_
UISearchBar *search;
search = [[UISearchBar alloc] init];
[search setTintColor:[UIColor colorWithRed:233.0/255.0
green:233.0/255.0
blue:233.0/255.0
alpha:1.0]];
search.frame = CGRectMake(50,20,self.view.frame.size.width-70,32);
search.delegate = self;
search.placeholder = #"MapView";
[mapView_ addSubview:search];
Add Following method to your .m file
// Remove the GMSBlockingGestureRecognizer of the GMSMapView.
+ (void)removeGMSBlockingGestureRecognizerFromMapView:(GMSMapView *)mapView
{
for (id gestureRecognizer in mapView.gestureRecognizers)
{
NSLog(#"mapview recognizer %#",gestureRecognizer);
if (![gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
{
[mapView removeGestureRecognizer:gestureRecognizer];
}
}
}
Call This Method from your view will appear
- (void)viewWillAppear:(BOOL)animated {
[ViewController removeGMSBlockingGestureRecognizerFromMapView:mapView_];
}
Now it will work , i got tested with this code only.
Try
[self.view addSubview: textField];
Instead of
[mapView_ addSubview:textField];
This may help you.
I am currently working with Google Maps API in my project. I am trying to set the default camera/zoom to the users location. I do this:
#implementation ViewController{
GMSMapView *mapView_;
}
#synthesize currentLatitude,currentLongitude;
- (void)viewDidLoad
{
[super viewDidLoad];
mapView_.settings.myLocationButton = YES;
mapView_.myLocationEnabled = YES;
}
- (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);
}
However, it does not work, since when I do
NSLog(#"%f, %f", myLocation.coordinate.latitude, myLocation.coordinate.longitude);
it returns 0, 0, and it does not give the current location coordinates. How can I properly get the user's coordinates?
.h
#import <CoreLocation/CoreLocation.h>
#property(nonatomic,retain) CLLocationManager *locationManager;
.m
- (NSString *)deviceLocation
{
NSString *theLocation = [NSString stringWithFormat:#"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
return theLocation;
}
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
answered here.
When an app first starts it may not yet know your location, as it usually takes a while for the GPS device to lock on to your location (if it has just been started), and especially if this is the first time the application has been run, and so the user hasn't yet answered the prompt to give the app access to their location. Also it seems like mapView.myLocation is always empty (either nil or has coordinates 0,0) when the map view has just been created.
So you will need to wait until the user's location is known, and then update the camera position.
One way might be using the code at how to get current location in google map sdk in iphone as suggested by Puneet, but note that the sample code there is missing the details of setting up the location manager (like setting the location manager's delegate), which might be why it didn't work for you.
Another option could be to use KVO on mapView.myLocation, as described here: about positioning myself,some problems
By the way in your sample code you are accessing mapView.myLocation before you create the mapView, and so the location would always be nil anyway.
I just Downloaded the new GoogleMap SDK Demo for iOS. Here is what I have seen from the source code that how the "Current Location" is achieved via KVO.
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
#import "SDKDemos/Samples/MyLocationViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#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
Hope it can help you.
Just in case anyone wants DrDev's excellent answer in Swift 3:
var locationManager: CLLocationManager?
func deviceLocation() -> String {
let theLocation: String = "latitude: \(locationManager.location.coordinate.latitude) longitude: \(locationManager.location.coordinate.longitude)"
return theLocation
}
func viewDidLoad() {
locationManager = CLLocationManager()
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
// 100 m
locationManager.startUpdatingLocation()
}