Оптимизируйте свои подборки Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Кнопка «Мое местоположение» отображается в правом нижнем углу карты. Когда пользователь нажимает кнопку, карта перемещается к текущему местоположению пользователя.
Начать
Прежде чем вы сможете опробовать пример кода, вам необходимо настроить среду разработки. Дополнительную информацию см. в разделе «Примеры кода Maps SDK для iOS» .
Посмотреть код
Быстрый
importGoogleMapsimportUIKitclassMyLocationViewController:UIViewController{privateletcameraLatitude:CLLocationDegrees=-33.868privateletcameraLongitude:CLLocationDegrees=151.2086privateletcameraZoom:Float=12lazyvarmapView:GMSMapView={letcamera=GMSCameraPosition(latitude:cameraLatitude,longitude:cameraLongitude,zoom:cameraZoom)returnGMSMapView(frame:.zero,camera:camera)}()varobservation:NSKeyValueObservation?varlocation:CLLocation?{didSet{guardoldValue==nil,letfirstLocation=locationelse{return}mapView.camera=GMSCameraPosition(target:firstLocation.coordinate,zoom:14)}}overridefuncviewDidLoad(){super.viewDidLoad()mapView.delegate=selfmapView.settings.compassButton=truemapView.settings.myLocationButton=truemapView.isMyLocationEnabled=trueview=mapView// Listen to the myLocation property of GMSMapView.observation=mapView.observe(\.myLocation,options:[.new]){[weakself]mapView,_inself?.location=mapView.myLocation}}deinit{observation?.invalidate()}}extensionMyLocationViewController:GMSMapViewDelegate{funcmapView(_mapView:GMSMapView,didTapMyLocationlocation:CLLocationCoordinate2D){letalert=UIAlertController(title:"Location Tapped",message:"Current location: <\(location.latitude), \(location.longitude)>",preferredStyle:.alert)alert.addAction(UIAlertAction(title:"OK",style:.default))present(alert,animated:true)}}
#import "GoogleMapsDemos/Samples/MyLocationViewController.h"#import <GoogleMaps/GoogleMaps.h>@implementationMyLocationViewController{GMSMapView*_mapView;BOOL_firstLocationUpdate;}-(void)viewDidLoad{[superviewDidLoad];GMSCameraPosition*camera=[GMSCameraPositioncameraWithLatitude:-33.868longitude:151.2086zoom:12];_mapView=[GMSMapViewmapWithFrame:CGRectZerocamera:camera];_mapView.delegate=self;_mapView.settings.compassButton=YES;_mapView.settings.myLocationButton=YES;// Listen to the myLocation property of GMSMapView.[_mapViewaddObserver:selfforKeyPath:@"myLocation"options:NSKeyValueObservingOptionNewcontext:NULL];self.view=_mapView;// Ask for My Location data after the map has already been added to the UI.GMSMapView*mapView=_mapView;dispatch_async(dispatch_get_main_queue(),^{mapView.myLocationEnabled=YES;});}-(void)mapView:(GMSMapView*)mapViewdidTapMyLocation:(CLLocationCoordinate2D)location{NSString*message=[NSStringstringWithFormat:@"My Location Dot Tapped at: [lat: %f, lng: %f]",location.latitude,location.longitude];UIAlertController*alertController=[UIAlertControlleralertControllerWithTitle:@"Location Tapped"message:messagepreferredStyle:UIAlertControllerStyleAlert];UIAlertAction*okAction=[UIAlertActionactionWithTitle:@"OK"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*action){}];[alertControlleraddAction:okAction];[selfpresentViewController:alertControlleranimated:YEScompletion:nil];}-(void)dealloc{[_mapViewremoveObserver:selfforKeyPath:@"myLocation"context:NULL];}#pragma mark - KVO updates-(void)observeValueForKeyPath:(NSString*)keyPathofObject:(id)objectchange:(NSDictionary*)changecontext:(void*)context{if(!_firstLocationUpdate){// If the first location update has not yet been received, then jump to that location._firstLocationUpdate=YES;CLLocation*location=[changeobjectForKey:NSKeyValueChangeNewKey];_mapView.camera=[GMSCameraPositioncameraWithTarget:location.coordinatezoom:14];}}@end
Пример приложения Maps SDK для iOS доступен в виде архива для загрузки на GitHub . Выполните следующие действия, чтобы установить и опробовать пример приложения Maps SDK для iOS.
Запустите git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git , чтобы клонировать репозиторий образцов в локальный каталог.
Откройте окно терминала, перейдите в каталог, в который вы клонировали файлы примеров, и перейдите к каталогу GoogleMaps:
Быстрый
cd maps-sdk-for-ios-samples-main/GoogleMaps-Swift pod installopen GoogleMapsSwiftDemos.xcworkspace
Цель-C
cd maps-sdk-for-ios-samples-main/GoogleMaps pod installopen GoogleMapsDemos.xcworkspace
В Xcode нажмите кнопку компиляции, чтобы создать приложение с текущей схемой. При сборке возникает ошибка, предлагающая ввести ключ API в файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C.
Отредактируйте файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C и вставьте свой ключ API в определение константы apiKey или kAPIKey . Например:
Быстрый
static let apiKey = "YOUR_API_KEY"
Цель-C
staticNSString*constkAPIKey=@"YOUR_API_KEY";
В файле SDKConstants.swift (Swift) или файле SDKDemoAPIKey.h (Objective-C) удалите следующую строку, поскольку она используется для регистрации определяемой пользователем проблемы:
Быстрый
#error (Register for API Key and insert here. Then delete this line.)
Цель-C
#error Register for API Key and insert here.
Создайте и запустите проект. Появится окно симулятора iOS со списком демонстрационных версий Maps SDK .
Выберите один из отображаемых вариантов, чтобы поэкспериментировать с функцией Maps SDK для iOS.
Если будет предложено разрешить GoogleMapsDemos доступ к вашему местоположению, выберите «Разрешить» .
,
Кнопка «Мое местоположение» отображается в правом нижнем углу карты. Когда пользователь нажимает кнопку, карта перемещается к текущему местоположению пользователя.
Начать
Прежде чем вы сможете опробовать пример кода, вам необходимо настроить среду разработки. Дополнительную информацию см. в примерах кода Maps SDK для iOS .
Посмотреть код
Быстрый
importGoogleMapsimportUIKitclassMyLocationViewController:UIViewController{privateletcameraLatitude:CLLocationDegrees=-33.868privateletcameraLongitude:CLLocationDegrees=151.2086privateletcameraZoom:Float=12lazyvarmapView:GMSMapView={letcamera=GMSCameraPosition(latitude:cameraLatitude,longitude:cameraLongitude,zoom:cameraZoom)returnGMSMapView(frame:.zero,camera:camera)}()varobservation:NSKeyValueObservation?varlocation:CLLocation?{didSet{guardoldValue==nil,letfirstLocation=locationelse{return}mapView.camera=GMSCameraPosition(target:firstLocation.coordinate,zoom:14)}}overridefuncviewDidLoad(){super.viewDidLoad()mapView.delegate=selfmapView.settings.compassButton=truemapView.settings.myLocationButton=truemapView.isMyLocationEnabled=trueview=mapView// Listen to the myLocation property of GMSMapView.observation=mapView.observe(\.myLocation,options:[.new]){[weakself]mapView,_inself?.location=mapView.myLocation}}deinit{observation?.invalidate()}}extensionMyLocationViewController:GMSMapViewDelegate{funcmapView(_mapView:GMSMapView,didTapMyLocationlocation:CLLocationCoordinate2D){letalert=UIAlertController(title:"Location Tapped",message:"Current location: <\(location.latitude), \(location.longitude)>",preferredStyle:.alert)alert.addAction(UIAlertAction(title:"OK",style:.default))present(alert,animated:true)}}
#import "GoogleMapsDemos/Samples/MyLocationViewController.h"#import <GoogleMaps/GoogleMaps.h>@implementationMyLocationViewController{GMSMapView*_mapView;BOOL_firstLocationUpdate;}-(void)viewDidLoad{[superviewDidLoad];GMSCameraPosition*camera=[GMSCameraPositioncameraWithLatitude:-33.868longitude:151.2086zoom:12];_mapView=[GMSMapViewmapWithFrame:CGRectZerocamera:camera];_mapView.delegate=self;_mapView.settings.compassButton=YES;_mapView.settings.myLocationButton=YES;// Listen to the myLocation property of GMSMapView.[_mapViewaddObserver:selfforKeyPath:@"myLocation"options:NSKeyValueObservingOptionNewcontext:NULL];self.view=_mapView;// Ask for My Location data after the map has already been added to the UI.GMSMapView*mapView=_mapView;dispatch_async(dispatch_get_main_queue(),^{mapView.myLocationEnabled=YES;});}-(void)mapView:(GMSMapView*)mapViewdidTapMyLocation:(CLLocationCoordinate2D)location{NSString*message=[NSStringstringWithFormat:@"My Location Dot Tapped at: [lat: %f, lng: %f]",location.latitude,location.longitude];UIAlertController*alertController=[UIAlertControlleralertControllerWithTitle:@"Location Tapped"message:messagepreferredStyle:UIAlertControllerStyleAlert];UIAlertAction*okAction=[UIAlertActionactionWithTitle:@"OK"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*action){}];[alertControlleraddAction:okAction];[selfpresentViewController:alertControlleranimated:YEScompletion:nil];}-(void)dealloc{[_mapViewremoveObserver:selfforKeyPath:@"myLocation"context:NULL];}#pragma mark - KVO updates-(void)observeValueForKeyPath:(NSString*)keyPathofObject:(id)objectchange:(NSDictionary*)changecontext:(void*)context{if(!_firstLocationUpdate){// If the first location update has not yet been received, then jump to that location._firstLocationUpdate=YES;CLLocation*location=[changeobjectForKey:NSKeyValueChangeNewKey];_mapView.camera=[GMSCameraPositioncameraWithTarget:location.coordinatezoom:14];}}@end
Пример приложения Maps SDK для iOS доступен в виде архива для загрузки на GitHub . Выполните следующие действия, чтобы установить и опробовать пример приложения Maps SDK для iOS.
Запустите git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git , чтобы клонировать репозиторий образцов в локальный каталог.
Откройте окно терминала, перейдите в каталог, в который вы клонировали файлы примеров, и перейдите к каталогу GoogleMaps:
Быстрый
cd maps-sdk-for-ios-samples-main/GoogleMaps-Swift pod installopen GoogleMapsSwiftDemos.xcworkspace
Цель-C
cd maps-sdk-for-ios-samples-main/GoogleMaps pod installopen GoogleMapsDemos.xcworkspace
В Xcode нажмите кнопку компиляции, чтобы создать приложение с текущей схемой. При сборке возникает ошибка, предлагающая ввести ключ API в файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C.
Отредактируйте файл SDKConstants.swift для Swift или файл SDKDemoAPIKey.h для Objective-C и вставьте свой ключ API в определение константы apiKey или kAPIKey . Например:
Быстрый
static let apiKey = "YOUR_API_KEY"
Цель-C
staticNSString*constkAPIKey=@"YOUR_API_KEY";
В файле SDKConstants.swift (Swift) или файле SDKDemoAPIKey.h (Objective-C) удалите следующую строку, поскольку она используется для регистрации определяемой пользователем проблемы:
Быстрый
#error (Register for API Key and insert here. Then delete this line.)
Цель-C
#error Register for API Key and insert here.
Создайте и запустите проект. Появится окно симулятора iOS со списком демонстрационных версий Maps SDK .
Выберите один из отображаемых вариантов, чтобы поэкспериментировать с функцией Maps SDK для iOS.
Если будет предложено разрешить GoogleMapsDemos доступ к вашему местоположению, выберите «Разрешить» .
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2025-07-23 UTC."],[[["\u003cp\u003eThe "My Location" button, located in the bottom right corner of the map, centers the map on the user's current location when tapped.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code samples (Swift and Objective-C) demonstrate how to implement the "My Location" functionality within a map view.\u003c/p\u003e\n"],["\u003cp\u003eTo run the sample code, you'll need to configure your development environment, including obtaining and integrating a Google Maps API key.\u003c/p\u003e\n"],["\u003cp\u003eThe full sample app can be downloaded and explored to experiment with various features of the Maps SDK for iOS.\u003c/p\u003e\n"]]],["The content describes implementing a \"My Location\" feature in a map view using the Google Maps SDK for iOS. When enabled, a button appears, allowing the user to center the map on their current location upon tapping. The code examples show how to set up the map, enable the \"My Location\" button and feature, and observe changes to the user's location. Additionally, it details setting up a project and API key. It also describes setting up a tap handler on the current user's location in the map.\n"],null,["The **My Location** button is displayed in the bottom right corner of the map view. When the user taps the button, the map pans to the user's current location.\n\nGet started\n\nBefore you can try the sample code, you must configure your development environment.\nFor more information, see [Maps SDK for iOS code samples](/maps/documentation/ios-sdk/examples).\n\nView the code \n\nSwift \n\n```swift\nimport GoogleMaps\nimport UIKit\n\nclass MyLocationViewController: UIViewController {\n\n private let cameraLatitude: CLLocationDegrees = -33.868\n\n private let cameraLongitude: CLLocationDegrees = 151.2086\n\n private let cameraZoom: Float = 12\n\n lazy var mapView: GMSMapView = {\n let camera = GMSCameraPosition(\n latitude: cameraLatitude, longitude: cameraLongitude, zoom: cameraZoom)\n return GMSMapView(frame: .zero, camera: camera)\n }()\n\n var observation: NSKeyValueObservation?\n var location: CLLocation? {\n didSet {\n guard oldValue == nil, let firstLocation = location else { return }\n mapView.camera = GMSCameraPosition(target: firstLocation.coordinate, zoom: 14)\n }\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n mapView.delegate = self\n mapView.settings.compassButton = true\n mapView.settings.myLocationButton = true\n mapView.isMyLocationEnabled = true\n view = mapView\n\n // Listen to the myLocation property of GMSMapView.\n observation = mapView.observe(\\.myLocation, options: [.new]) {\n [weak self] mapView, _ in\n self?.location = mapView.myLocation\n }\n }\n\n deinit {\n observation?.invalidate()\n }\n}\n\nextension MyLocationViewController: GMSMapViewDelegate {\n func mapView(_ mapView: GMSMapView, didTapMyLocation location: CLLocationCoordinate2D) {\n let alert = UIAlertController(\n title: \"Location Tapped\",\n message: \"Current location: \u003c\\(location.latitude), \\(location.longitude)\u003e\",\n preferredStyle: .alert)\n alert.addAction(UIAlertAction(title: \"OK\", style: .default))\n present(alert, animated: true)\n }\n}https://github.com/googlemaps-samples/maps-sdk-for-ios-samples/blob/5092537f1ae5f51e9a7fd0ab6523d52f06a5b8a9/GoogleMaps-Swift/GoogleMapsSwiftDemos/Swift/Samples/MyLocationViewController.swift#L14-L69\n \n```\n\nObjective-C \n\n```objective-c\n#import \"GoogleMapsDemos/Samples/MyLocationViewController.h\"\n\n#import \u003cGoogleMaps/GoogleMaps.h\u003e\n\n@implementation MyLocationViewController {\n GMSMapView *_mapView;\n BOOL _firstLocationUpdate;\n}\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868\n longitude:151.2086\n zoom:12];\n\n _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];\n _mapView.delegate = self;\n _mapView.settings.compassButton = YES;\n _mapView.settings.myLocationButton = YES;\n\n // Listen to the myLocation property of GMSMapView.\n [_mapView addObserver:self\n forKeyPath:@\"myLocation\"\n options:NSKeyValueObservingOptionNew\n context:NULL];\n\n self.view = _mapView;\n\n // Ask for My Location data after the map has already been added to the UI.\n GMSMapView *mapView = _mapView;\n dispatch_async(dispatch_get_main_queue(), ^{\n mapView.myLocationEnabled = YES;\n });\n}\n\n- (void)mapView:(GMSMapView *)mapView didTapMyLocation:(CLLocationCoordinate2D)location {\n NSString *message = [NSString stringWithFormat:@\"My Location Dot Tapped at: [lat: %f, lng: %f]\",\n location.latitude, location.longitude];\n UIAlertController *alertController =\n [UIAlertController alertControllerWithTitle:@\"Location Tapped\"\n message:message\n preferredStyle:UIAlertControllerStyleAlert];\n UIAlertAction *okAction = [UIAlertAction actionWithTitle:@\"OK\"\n style:UIAlertActionStyleDefault\n handler:^(UIAlertAction *action){\n }];\n [alertController addAction:okAction];\n [self presentViewController:alertController animated:YES completion:nil];\n}\n\n- (void)dealloc {\n [_mapView removeObserver:self forKeyPath:@\"myLocation\" context:NULL];\n}\n\n#pragma mark - KVO updates\n\n- (void)observeValueForKeyPath:(NSString *)keyPath\n ofObject:(id)object\n change:(NSDictionary *)change\n context:(void *)context {\n if (!_firstLocationUpdate) {\n // If the first location update has not yet been received, then jump to that location.\n _firstLocationUpdate = YES;\n CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];\n _mapView.camera = [GMSCameraPosition cameraWithTarget:location.coordinate zoom:14];\n }\n}\n\n@end \nhttps://github.com/googlemaps-samples/maps-sdk-for-ios-samples/blob/5092537f1ae5f51e9a7fd0ab6523d52f06a5b8a9/GoogleMaps/GoogleMapsDemos/Samples/MyLocationViewController.m#L16-L84\n\n \n```\n\nRun the full sample app locally\n\nThe Maps SDK for iOS sample app is available as a\n[download archive](https://github.com/googlemaps-samples/maps-sdk-for-ios-samples/archive/main.zip)\nfrom [GitHub](https://github.com/googlemaps-samples/maps-sdk-for-ios-samples/tree/main/GoogleMaps).\nFollow these steps to install and try the Maps SDK for iOS sample app.\n\n1. Run `git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git` to clone the samples repository into a local directory.\n2. Open a terminal window, navigate to the directory where you cloned the sample files, and\n drill down into the GoogleMaps directory:\n\n Swift \n\n cd maps-sdk-for-ios-samples-main/GoogleMaps-Swift\n pod install\n open GoogleMapsSwiftDemos.xcworkspace\n\n Objective-C \n\n cd maps-sdk-for-ios-samples-main/GoogleMaps\n pod install\n open GoogleMapsDemos.xcworkspace\n\n3. In Xcode, press the compile button to [build the app](https://developer.apple.com/documentation/xcode/building-and-running-an-app) with the current scheme. The build produces an error, prompting you to enter your API key in the `SDKConstants.swift` file for Swift or`SDKDemoAPIKey.h` file for Objective-C.\n4. [Get an API key](/maps/documentation/ios-sdk/get-api-key) from your project with the [Maps SDK for iOS enabled](/maps/documentation/ios-sdk/cloud-setup#enabling-apis).\n5. Edit the `SDKConstants.swift` file for Swift or`SDKDemoAPIKey.h` file for Objective-C and paste your API key into the definition of either the `apiKey` or `kAPIKey` constant. For example: \n\n Swift \n\n ```scdoc\n static let apiKey = \"YOUR_API_KEY\"\n ```\n\n Objective-C \n\n ```objective-c\n static NSString *const kAPIKey = @\"YOUR_API_KEY\";\n ```\n6. In the `SDKConstants.swift` file (Swift) or`SDKDemoAPIKey.h` file (Objective-C), remove the following line, because it's used to register the user-defined issue: \n\n Swift \n\n ```text\n #error (Register for API Key and insert here. Then delete this line.)\n ```\n\n Objective-C \n\n ```text\n #error Register for API Key and insert here.\n ```\n7. Build and run the project. The iOS simulator window appears, showing a list of **Maps SDK Demos**.\n8. Choose one of the options displayed, to experiment with a feature of the Maps SDK for iOS.\n9. If prompted to allow GoogleMapsDemos to access your location, choose **Allow**."]]