2014-01-30 4 views
3

Редактировать: Это не обязательно относится к симулятору, в котором используется объект Debug-> Location. Он показывает 0.000000 ли я на симуляторе или на реальном телефоне.Карты Google Maps SDK на iOS (не Simulator!), MyLocation - 0.000000

Я использую карты Google, чтобы попытаться создать приложение, которое может делать что-то на основе моего текущего местоположения.

Когда я открываю приложение, точка синей точки на карте находится в моем фактическом (правильном) месте, но маркер, который я разместил в «myLocation», составляет 0,000000,0.000000 (это также значение, которое печатается на консоль)

Как я могу сделать так, чтобы местоположение моего маркера находилось в текущем местоположении, когда я открываю приложение и/или что-то делаю, чтобы получить живые координаты, где находится синяя точка? (Таким образом, я мог бы получить доступ к широте и долготе в реальном времени, когда захочу)

Заранее спасибо!

Вот мой код:

#import "MyViewController.h" 
#import <GoogleMaps/GoogleMaps.h> 


@interface MyViewController() 
@property (nonatomic, readwrite) NSString *coord; 
@end 

@implementation MyViewController 

GMSMapView *mapView_; 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self.view layoutIfNeeded]; 

    // Do any additional setup after loading the view, typically from a nib. 
    // Create a GMSCameraPosition that tells the map to display the 
    // coordinate -33.86,151.20 at zoom level 6. 
    CLLocation *myLocation = mapView_.myLocation; 
    GMSCameraPosition *camera = [GMSCameraPosition  cameraWithLatitude:myLocation.coordinate.latitude 
                  longitude:myLocation.coordinate.longitude 
                  zoom:6]; 
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera]; 
mapView_.myLocationEnabled = YES; 


self.view = mapView_; 




// Creates a marker in the center of the map. 
GMSMarker *marker = [[GMSMarker alloc] init]; 
// marker.position = CLLocationCoordinate2DMake(-33.86, 151.20); 
    marker.position = CLLocationCoordinate2DMake(myLocation.coordinate.latitude,  myLocation.coordinate.longitude); 
marker.title = @"Current:"; 
float lat = mapView_.myLocation.coordinate.latitude; 
float lon = mapView_.myLocation.coordinate.longitude; 
_coord = [NSString stringWithFormat:@"%f %f",lat,lon]; 
printf("%f %f",lat,lon); 
marker.snippet = (_coord); 
marker.map = mapView_; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 





@end 
+0

Возможный дубликат [Можно ли получить текущее местоположение в реальном времени с помощью симулятора iOS?] (Http://stackoverflow.com/questions/21102917/is-it-possible-to-get-the-live -current-location-with-an-ios-simulator) –

+0

Я не говорю об Simulator, я говорю о том, чтобы получить текущее местоположение из API Карт Google на реальном iPhone. – Inbl

ответ

1
#import "ViewController.h" 
#import <GoogleMaps/GoogleMaps.h> 

@interface ViewController() <GMSMapViewDelegate> 
{ 
GMSMapView *mapView_; 
} 
@end 

@implementation ViewController 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (void)viewWillAppear:(BOOL)animated 
{ 
    [mapView_ addObserver:self forKeyPath:@"myLocation" options:0 context:nil]; 
} 

- (void)dealloc 
{ 
    [mapView_ removeObserver:self forKeyPath:@"myLocation"]; 
} 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{ 
    if([keyPath isEqualToString:@"myLocation"]) 
    { 
     CLLocation *location = [object myLocation]; 

     NSLog(@"Location, %@,", location); 

     CLLocationCoordinate2D target = 
     CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude); 

     [mapView_ animateToLocation:target]; 
     [mapView_ animateToZoom:17]; 
    } 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    GMSCameraPosition *cam = [GMSCameraPosition cameraWithLatitude:mapView_.myLocation.coordinate.latitude longitude:mapView_.myLocation.coordinate.longitude zoom:15]; 
    mapView_ = [GMSMapView mapWithFrame:CGRectMake(20, 20, self.view.frame.size.width, self.view.frame.size.height - 64) camera:cam]; 

    self.view = mapView_; 

    mapView_.delegate = self; 

    mapView_.userInteractionEnabled = YES; 
    mapView_.myLocationEnabled = YES; 

    mapView_.mapType = kGMSTypeNormal; 
    mapView_.indoorEnabled = YES; 
    mapView_.accessibilityElementsHidden = NO; 

    mapView_.settings.scrollGestures = YES; 
    mapView_.settings.zoomGestures = YES; 
    mapView_.settings.tiltGestures = YES; 
    mapView_.settings.rotateGestures = YES; 

    mapView_.settings.compassButton = YES; 
    mapView_.settings.myLocationButton = YES; 
    mapView_.settings.indoorPicker = YES; 

} 
0

Для этого вам понадобится помощь CLLocationManger класса

В файле .h

CLLocationManager *currentLocationManager; 
CLLocation *myLocation ; 

В .m файл

#import <CoreLocation/CoreLocation.h> 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self.view layoutIfNeeded]; 

currentLocationManager = [[CLLocationManager alloc] init]; 
    currentLocationManager.desiredAccuracy = kCLLocationAccuracyBest; 
    currentLocationManager.distanceFilter = DISTANCE_FILTER_VALUE_STATIONARY; 
    [self.currentLocationManager setDelegate:self]; 
    [currentLocationManager startUpdatingLocation]; 

}

#pragma mark 
#pragma mark for Location manager Delegate Methods 

- (void)locationManager:(CLLocationManager *)manager 
    didUpdateLocations:(NSArray *)locations { 

myLocation = [locations lastObject]; 

// Now create maker on current location 
GMSMarker *marker = [[GMSMarker alloc] init]; 
marker.position = myLocation.coordinate; 
marker.title = @"Current:"; 
float lat = mapView_.myLocation.coordinate.latitude; 
float lon = mapView_.myLocation.coordinate.longitude; 
_coord = [NSString stringWithFormat:@"%f %f",lat,lon]; 
printf("%f %f",lat,lon); 
marker.snippet = (_coord); 
marker.map = mapView_; 

}

Это создает маркер на текущем местоположении. Вы получите обновления местоположения на основе «фильтра расстояния» и «четкости», заданного менеджером местоположений.

Смежные вопросы