Начать
Прежде чем вы сможете опробовать пример кода, вам необходимо настроить среду разработки. Дополнительную информацию см. в разделе «Примеры кода Maps SDK для iOS» .
Посмотреть код
import GoogleMaps
import UIKit
// Sample code for GeoCoder service.
class GeocoderViewController: UIViewController {
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 12)
return GMSMapView(frame: .zero, camera: camera)
}()
private lazy var geocoder = GMSGeocoder()
override func loadView() {
view = mapView
mapView.delegate = self
}
}
extension GeocoderViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
// On a long press, reverse geocode this location.
geocoder.reverseGeocodeCoordinate(coordinate) { response, error in
guard let address = response?.firstResult() else {
let errorMessage = error.map { String(describing: $0) } ?? "<no error>"
print(
"Could not reverse geocode point (\(coordinate.latitude), \(coordinate.longitude)): \(errorMessage)"
)
return
}
print("Geocoder result: \(address)")
let marker = GMSMarker(position: address.coordinate)
marker.appearAnimation = .pop
marker.map = mapView
guard let lines = address.lines, let title = lines.first else { return }
marker.title = title
if lines.count > 1 {
marker.snippet = lines[1]
}
}
}
}
#import "GoogleMapsDemos/Samples/GeocoderViewController.h"
#import <GoogleMaps/GoogleMaps.h>
@implementation GeocoderViewController {
GMSMapView *_mapView;
GMSGeocoder *_geocoder;
}
- (void)viewDidLoad {
[super viewDidLoad];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
longitude:151.2086
zoom:12];
_mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
_mapView.delegate = self;
_geocoder = [[GMSGeocoder alloc] init];
self.view = _mapView;
}
- (void)mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate {
// On a long press, reverse geocode this location.
__weak __typeof__(self) weakSelf = self;
GMSReverseGeocodeCallback handler = ^(GMSReverseGeocodeResponse *response, NSError *error) {
[weakSelf handleResponse:response coordinate:coordinate error:error];
};
[_geocoder reverseGeocodeCoordinate:coordinate completionHandler:handler];
}
- (void)handleResponse:(nullable GMSReverseGeocodeResponse *)response
coordinate:(CLLocationCoordinate2D)coordinate
error:(nullable NSError *)error {
GMSAddress *address = response.firstResult;
if (address) {
NSLog(@"Geocoder result: %@", address);
GMSMarker *marker = [GMSMarker markerWithPosition:address.coordinate];
NSArray<NSString *> *lines = [address lines];
marker.title = [lines firstObject];
if (lines.count > 1) {
marker.snippet = [lines objectAtIndex:1];
}
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.map = _mapView;
} else {
NSLog(@"Could not reverse geocode point (%f,%f): %@", coordinate.latitude, coordinate.longitude,
error);
}
}
@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 install
open GoogleMapsSwiftDemos.xcworkspace
cd maps-sdk-for-ios-samples-main/GoogleMaps
pod install
open GoogleMapsDemos.xcworkspace
- В Xcode нажмите кнопку компиляции, чтобы создать приложение с текущей схемой. При сборке возникает ошибка, предлагающая ввести ключ API в файл
SDKConstants.swift
для Swift или файлSDKDemoAPIKey.h
для Objective-C. - Если у вас еще нет ключа API, следуйте инструкциям , чтобы настроить проект в Google Cloud Console и получить ключ API. При настройке ключа в Cloud Console вы можете ограничить ключ идентификатором пакета примера приложения, чтобы гарантировать, что только ваше приложение может использовать ключ. Идентификатор пакета по умолчанию для примера приложения SDK —
com.example.GoogleMapsDemos
. - Отредактируйте файл
SDKConstants.swift
для Swift или файлSDKDemoAPIKey.h
для Objective-C и вставьте свой ключ API в определение константыapiKey
илиkAPIKey
. Например:static let apiKey = "
YOUR_API_KEY "static NSString *const kAPIKey = @"
YOUR_API_KEY "; - В файле
SDKConstants.swift
(Swift) или файлеSDKDemoAPIKey.h
(Objective-C) удалите следующую строку, поскольку она используется для регистрации определяемой пользователем проблемы:#error (Register for API Key and insert here. Then delete this line.)
#error Register for API Key and insert here.
- Создайте и запустите проект. Появится окно симулятора iOS со списком демонстрационных версий Maps SDK .
- Выберите один из отображаемых вариантов, чтобы поэкспериментировать с функцией Maps SDK для iOS.
- Если будет предложено разрешить GoogleMapsDemos доступ к вашему местоположению, выберите «Разрешить» .