Google Maps iOS SDK,获取用户当前位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20967496/
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
Google Maps iOS SDK, Getting Current Location of user
提问by Sofeda
For my iOS
app (building in iOS7
),i need to show user's current location when the app load.I am using Google Maps iOS SDK
. I am following this
Google MapBut i can't figure it out. Please help if you go through the path.
对于我的iOS
应用程序(iOS7
内置),我需要在应用程序加载时显示用户的当前位置Google Maps iOS SDK
。我正在使用. 我正在关注这个
谷歌地图,但我无法弄清楚。如果你走过这条路,请帮忙。
采纳答案by Maxime Capelle
It seems Google Maps iOS SDK
cannot access to the device position.
So you have to retrieve the position by using CLLocationManager
of iOS
.
似乎Google Maps iOS SDK
无法访问设备位置。所以你必须使用CLLocationManager
of来检索位置iOS
。
First, add the CoreLocation.framework
to your project :
首先,添加CoreLocation.framework
到您的项目:
- Go in
Project Navigator
- Select your project
- Click on the tab
Build Phases
- Add the
CoreLocation.framework
in theLink Binary with Libraries
- 进去
Project Navigator
- 选择您的项目
- 单击选项卡
Build Phases
- 添加
CoreLocation.framework
在Link Binary with Libraries
Then all you need to do is to follow the basic exemple of Apple documentation.
然后您需要做的就是遵循Apple 文档的基本示例。
Create a
CLLocationManager
probably in yourViewDidLoad
: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];
创建一个
CLLocationManager
可能在您的ViewDidLoad
: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];
With the CLLocationManagerDelegate
every time the position is updated, you can update the user position on your Google Maps
:
随着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);
}
}
回答by Maxime Capelle
Forget my previous answer. It works well if you use the native MapKit.framework.
忘记我之前的回答。如果您使用本机 MapKit.framework,它运行良好。
In fact GoogleMaps for iOS do all the work for you. You don't have to use CoreLocation directly.
事实上,iOS 版 GoogleMaps 会为您完成所有工作。您不必直接使用 CoreLocation。
The only thing you have to do is to add yourMapView.myLocationEnabled = YES;
and the framework will do everything. (Except center the map on you position).
你唯一需要做的就是添加yourMapView.myLocationEnabled = YES;
,框架会做所有的事情。(除了将地图放在您的位置上)。
What I have done : I simply followed the steps of the following documentation. And I got a map centered on Sydney but if I zoomed out and moved to my place (if you use a real device, otherwise use simulator tools to center on Apple's location), I could see the blue point on my position.
我所做的:我只是按照以下文档的步骤操作。我有一张以悉尼为中心的地图,但如果我缩小并移动到我的位置(如果您使用真实设备,否则使用模拟器工具以 Apple 的位置为中心),我可以看到我位置上的蓝点。
Now if you want to update the map to follow your position, you can copy Google example MyLocationViewController.m
that is included in the framework directory. They just add a observer on the myLocation
property to update the camera properties:
现在,如果您想更新地图以跟随您的位置,您可以复制MyLocationViewController.m
框架目录中包含的Google 示例。他们只是在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
With the doc I gave you and the samples included in the framework you should be able to do what you want.
有了我给你的文档和框架中包含的示例,你应该能够做你想做的事。
回答by lenooh
Xcode + Swift + Google Maps iOS
Xcode + Swift + 谷歌地图 iOS
Step by step recipe:
分步食谱:
1.) Add key string to Info.plist (open as source code):
1.) 在 Info.plist 中添加 key 字符串(作为源代码打开):
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs your location to function properly</string>
2.) Add CLLocationManagerDelegate
to your view controller class:
2.) 添加CLLocationManagerDelegate
到您的视图控制器类:
class MapViewController: UIViewController, CLLocationManagerDelegate {
...
}
3.) Add CLLocationManager
into your class:
3.) 添加CLLocationManager
到您的班级中:
var mLocationManager = CLLocationManager()
var mDidFindMyLocation = false
4.) Ask for permission and add observer:
4.) 请求许可并添加观察者:
override func viewDidLoad() {
super.viewDidLoad()
mLocationManager.delegate = self
mLocationManager.requestWhenInUseAuthorization()
yourMapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.new, context: nil)
...
}
5.) Wait for authorization and enable location in Google Maps:
5.) 等待授权并在谷歌地图中启用位置:
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if (status == CLAuthorizationStatus.authorizedWhenInUse) {
yourMapView.isMyLocationEnabled = true
}
}
6.) Add observable for change of location:
6.) 添加 observable 以更改位置:
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!")
}
}
That's it!
就是这样!
回答by JeremyP
On any iOS device, get the user's location with Core Location. Specifically, you want the CLLocationclass (and CLLocationManager).
在任何 iOS 设备上,使用Core Location获取用户的位置。具体来说,您需要CLLocation类(和 CLLocationManager)。
回答by Dmitry Nelepov
Is delegate method didTapMyLocationButton is not way?
是委托方法 didTapMyLocationButton 不行吗?
- (BOOL)didTapMyLocationButtonForMapView:(GMSMapView *)mapView {
return YES;
}
And you can get location by
你可以通过
(lldb) po mapView.myLocation
<+37.33243033,-122.03088128> +/- 386.93m (speed -1.00 mps / course -1.00) @ 5/19/14, 6:22:28 PM Moscow Standard Time
回答by Marwa Lamey
The current location won't show on the simulator... connect a real device and give it a try I spent 2 days running in the simulator and don't know that it doesn't simulate locations
当前位置不会显示在模拟器上...连接一个真实的设备并试一试我在模拟器中运行了2天,不知道它不会模拟位置
回答by Sachin Kanojia
there are many methods... I used this method and it works in all cases. Google gives you everything with the reponse in json format and its on you how you deal with that data.
有很多方法......我使用了这种方法,它适用于所有情况。谷歌为你提供了 json 格式的响应,以及你如何处理这些数据。
Some steps are there to load google map in your project.
有一些步骤可以在您的项目中加载谷歌地图。
find the api key from this link https://developers.google.com/places/ios-api/sign in with your google account and add your project and create a ios key. then use this in your project
enable all the api needed for google map
从此链接https://developers.google.com/places/ios-api/ 中找到 api 密钥 ,使用您的 google 帐户登录并添加您的项目并创建一个 ios 密钥。然后在你的项目中使用它
启用谷歌地图所需的所有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
a-googlemaps sdk for ios b-googlemap 方向 api c-"" javasripts api d-picker api e-places api for ios f 距离矩阵 api
in appdelegate method...
在 appdelegate 方法中...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GMSServices provideAPIKey:@"xxxxxxxx4rilCeZeUhPORXWNJVpUoxxxxxxxx"];
return YES;
}
- add all needed library and frameworks in your project if google map is not working it means you have to add required framework all the best play with google map
- 如果谷歌地图无法正常工作,请在您的项目中添加所有需要的库和框架,这意味着您必须添加所需的框架,以便最好地使用谷歌地图