谷歌地图 iOS SDK,获取用户当前位置

14

我正在开发一个iOS应用程序(基于iOS7),需要在应用程序加载时显示用户的当前位置。我正在使用Google Maps iOS SDK。我遵循了这个Google Map,但是我无法弄清楚。如果您经过这条路,请帮助我。

7个回答

40

请忘记我的先前回答。如果您使用本地的MapKit.framework,它可以很好地工作。

实际上GoogleMaps for iOS会为您完成所有工作。您不必直接使用CoreLocation。

您需要做的唯一一件事是添加yourMapView.myLocationEnabled = YES;,框架将完成其他所有工作。(除了将地图居中于您的位置之外)。

我所做的只是简单地按照以下文档的步骤。我得到了一个以悉尼为中心的地图,但如果我缩小并移动到我的位置(如果您使用真实设备,否则使用模拟器工具来将地图定位在Apple的位置),我可以看到蓝色点表示我的位置。

现在,如果您想更新地图以跟随您的位置,您可以复制包含在框架目录中的Google示例MyLocationViewController.m。他们只向myLocation属性添加观察器以更新相机属性:

@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

有了我给你的文档和框架中包含的示例,你应该能够做到你想要的。


是的,我看到了。当示例开始时,它加载了悉尼,并且在收缩后,我可以看到我的位置。我想要首先使用蓝点加载我的当前位置。我只是无法理解mapView_ .settings.myLocationButton后面的信息。如果我可以获取当前位置的JSON,那将使我高兴不已! - Sofeda
这正是上面代码(MyLocationViewController.m)的功能。当我在我的iPhone上启动应用程序时,地图将以我的位置为中心。要创建一个带有您当前位置的JSON,您可能应该将代码放在由观察者触发的方法中。在那里,您可以使用您的坐标构建JSON,并对其进行任何操作。 - Maxime Capelle
我没有尝试搜索请求。 - Maxime Capelle
请注意:如果 VC 被分配但从未加载,则在 dealloc 上尝试删除观察者(不存在),因为您在 viewDidLoad 中启动了 KVO,它将会崩溃。 - DanSkeel
不要忘记在您的 Info.plist 中设置以下其中一个键: NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription - hash3r
显示剩余2条评论

10
似乎 Google Maps iOS SDK无法访问设备位置信息,因此您需要使用iOSCLLocationManager来获取位置信息。
首先,将CoreLocation.framework添加到您的项目中:
  • 进入Project Navigator
  • 选择您的项目
  • 单击Build Phases选项卡
  • Link Binary with Libraries中添加CoreLocation.framework
然后,您只需要按照Apple文档中的基本示例进行操作。
在您的ViewDidLoad中创建一个CLLocationManager
if (nil == locationManager)
    locationManager = [[CLLocationManager alloc] init];

locationManager.delegate = self;
//Configure Accuracy depending on your needs, default is kCLLocationAccuracyBest
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;

// Set a movement threshold for new events.
locationManager.distanceFilter = 500; // meters

[locationManager startUpdatingLocation];

通过 CLLocationManagerDelegate,每次位置更新时,您可以在您的 Google Maps 上更新用户位置:

- (void)locationManager:(CLLocationManager *)manager
      didUpdateLocations:(NSArray *)locations {
    // If it's a relatively recent event, turn off updates to save power.
   CLLocation* location = [locations lastObject];
   NSDate* eventDate = location.timestamp;
   NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
   if (abs(howRecent) < 15.0) {
      // Update your marker on your map using location.coordinate.latitude
      //and location.coordinate.longitude); 
   }
}

非常感谢。还有一件事需要知道,我可以在这里使用Google GMSMapView来展示位置吗?还是必须使用MKMapView? - Sofeda
是的,您需要使用Google的GMSMapView和GMSMarker。MKMapView仅适用于使用本机iOS MapKit的情况。 - Maxime Capelle
请Maxime帮忙使用GMSMapView。 - Sofeda
关于Google文档,在实例化GMSMapView时,您需要激活位置,使用yourMapView.myLocationEnabled = YES;,并在CLLocationManager Delegate方法中尝试更新属性yourMapView.myLocation(location)。这里的参数location是从委托中检索到的CLLocation。我认为您应该在地图上看到通常的蓝点。 - Maxime Capelle
你的MapView是GMSMapView对象吗?由于我对位置不熟悉,如果您能提供任何示例帮助我,那将是我的福音。 - Sofeda
我已经获取了我的当前位置。我该如何在GMSMapView中呈现它? - Sofeda

3

Xcode + Swift + Google Maps iOS

步骤:

1.) 在Info.plist文件中添加密钥字符串(以源代码形式打开):

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs your location to function properly</string>

2.) 将CLLocationManagerDelegate添加到您的视图控制器类中:

class MapViewController: UIViewController, CLLocationManagerDelegate {
   ...
}

3.) 将 CLLocationManager 添加到你的类中:

var mLocationManager = CLLocationManager()
var mDidFindMyLocation = false

4.) 请求权限并添加观察者:

override func viewDidLoad() {
        super.viewDidLoad()          

        mLocationManager.delegate = self
        mLocationManager.requestWhenInUseAuthorization()
        yourMapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.new, context: nil)
        ...
}

5.)等待授权并在Google地图中启用位置:

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

        if (status == CLAuthorizationStatus.authorizedWhenInUse) {
            yourMapView.isMyLocationEnabled = true
        }

    }

6.) 添加用于位置变更的观察器:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if (!mDidFindMyLocation) {

            let myLocation: CLLocation = change![NSKeyValueChangeKey.newKey] as! CLLocation

            // do whatever you want here with the location
            yourMapView.camera = GMSCameraPosition.camera(withTarget: myLocation.coordinate, zoom: 10.0)
            yourMapView.settings.myLocationButton = true

            mDidFindMyLocation = true

            print("found location!")

        }

    }

就是这样!


2

在任何iOS设备上,使用Core Location获取用户位置。具体来说,您需要使用CLLocation类(和CLLocationManager)。


这是唯一的方法吗?因为我正在使用Google Maps iOS SDK,所以我不能从这里获取吗?当我需要根据用户当前位置搜索时,我该怎么办? - Sofeda
@SMi 这是正确的方法。浏览 Google Maps SDK 文档时,似乎没有提取当前位置的方法。这并不让我感到惊讶,Google 的工程师往往非常聪明,不会没有充分理由地重新发明轮子。Core Location 并不难使用(请参考 Maxime 的答案)。 - JeremyP
非常感谢。但是当我在谷歌地图上查看我的当前位置时,它非常具体。我只想要详细的位置地址。既然您向我保证这是正确的方法,那么我会按照这个方法进行... - Sofeda

1

0

当前位置不会在模拟器上显示...连接一个真实设备并尝试一下吧。我在模拟器上跑了两天,都不知道它不会模拟位置。


-2

有许多方法...

我使用了这种方法,并且在所有情况下都有效。Google会以JSON格式返回所有内容,你需要自己处理这些数据。

以下是在项目中加载Google地图的步骤:

  1. 从此链接https://developers.google.com/places/ios-api/获取API密钥,使用你的Google账户登录并添加你的项目,创建一个iOS密钥,然后在你的项目中使用它。

  2. 启用所有需要的Google地图API

a-googlemaps sdk for ios b-googlemap direction api c-" " javasripts api d- picker api e- places api for ios f distance matrix api

在AppDelegate方法中...

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [GMSServices provideAPIKey:@"xxxxxxxx4rilCeZeUhPORXWNJVpUoxxxxxxxx"];

    return YES;
}
  1. 在您的项目中添加所有必需的库和框架 如果谷歌地图无法工作,则需要添加所需的框架 祝你好运,享受使用谷歌地图

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接