Google Maps API:获取当前位置的坐标 iOS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17057805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:54:46  来源:igfitidea点击:

Google Maps API: Getting coordinates of current location iOS

iosobjective-cgoogle-mapslocationgoogle-maps-sdk-ios

提问by Alexyuiop

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:

我目前正在我的项目中使用 Google Maps API。我正在尝试将默认相机/变焦设置为用户位置。我这样做:

@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?

它返回 0, 0,并且不给出当前位置坐标。如何正确获取用户的坐标?

回答by DrDev

.h

。H

#import <CoreLocation/CoreLocation.h>
@property(nonatomic,retain) CLLocationManager *locationManager;

.m

.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.

在这里回答。

回答by Saxon Druce

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.myLocationis always empty (either nil or has coordinates 0,0) when the map view has just been created.

当应用程序首次启动时,它可能还不知道您的位置,因为 GPS 设备通常需要一段时间才能锁定您的位置(如果它刚刚启动),尤其是如果这是应用程序第一次启动时运行,因此用户尚未回答提示以授予应用程序访问其位置的权限。mapView.myLocation当地图视图刚刚创建时,它似乎总是空的(nil 或坐标 0,0)。

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 iphoneas 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.

一种方法可能是按照 Puneet 的建议使用如何在 iphone 中的 google map sdk 中获取当前位置的代码,但请注意,示例代码缺少设置位置管理器的详细信息(例如设置位置管理器的委托),这可能就是它对你不起作用的原因。

Another option could be to use KVO on mapView.myLocation, as described here: about positioning myself,some problems

另一种选择可能是使用 KVO on mapView.myLocation,如下所述:关于定位自己,一些问题

By the way in your sample code you are accessing mapView.myLocationbefore you create the mapView, and so the location would always be nil anyway.

顺便说一下,mapView.myLocation在您创建mapView,之前访问的示例代码中,因此无论如何该位置始终为零。

回答by TypingPanda

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.

我刚刚下载了适用于 iOS 的新 GoogleMap SDK 演示。这是我从源代码中看到的“当前位置”是如何通过 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.

希望它可以帮助你。

回答by agrippa

Just in case anyone wants DrDev's excellent answer in Swift 3:

以防万一有人想要 DrDev 在 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()
}