添加带有标记的地图
本教程介绍了如何向 iOS 应用添加 Google 地图。地图中包含一个用于指示特定位置的标记(也称为图钉)。
获取代码
从 GitHub 克隆或下载 Google Maps iOS 示例代码库。
设置开发项目
若要安装 Maps SDK for iOS,请按以下步骤操作:
- 下载并安装 Xcode 13.0 版或更高版本。
- 如果您还没有 CocoaPods,请在 macOS 上从终端运行以下命令进行安装:
sudo gem install cocoapods
- 克隆或下载 Google Maps iOS 示例代码库。
- 进入
tutorials/map-with-marker
目录。 - 运行
pod install
命令。此操作会安装Podfile
中指定的 API 及其可能具有的任何依赖项。 - 打开(双击)项目的 map-with-marker.xcworkspace 文件,以在 Xcode 中将其打开。您必须使用
.xcworkspace
文件打开项目。
获取 API 密钥并启用必要的 API
如需完成本教程,您需要一个已获得 Maps SDK for iOS 使用授权的 Google API 密钥。点击下面的按钮以获取密钥并激活 API。
开始使用如需了解详情,请参阅获取 API 密钥。
为应用添加API密钥
Swift
按照以下方法向 AppDelegate.swift
添加 API 密钥:
- 请注意,以下 import 语句已添加到文件中:
import GoogleMaps
- 在
application(_:didFinishLaunchingWithOptions:)
方法中修改以下代码行,将 YOUR_API_KEY 替换为您的 API 密钥:GMSServices.provideAPIKey("YOUR_API_KEY")
Objective-C
按照以下方法向 AppDelegate.m
添加 API 密钥:
- 请注意,以下 import 语句已添加到文件中:
@import GoogleMaps;
- 在
application(_:didFinishLaunchingWithOptions:)
方法中修改以下代码行,将 YOUR_API_KEY 替换为您的 API 密钥:[GMSServices provideAPIKey:@"YOUR_API_KEY"];
构建和运行您的应用
- 将 iOS 设备连接到您的计算机,或者从 Xcode 的方案弹出式菜单中选择模拟器。
- 如果您使用的是设备,请确保位置信息服务已启用。 如果您使用的是模拟器,请从功能菜单中选择一个位置。
- 在 Xcode 中,点击 Product/Run 菜单选项(或 play 按钮图标)。
Xcode 构建应用,然后在设备或模拟器上运行该应用。
您将看到一张带有以澳大利亚东海岸悉尼为中心的地图,与本页上的图像类似。
问题排查:
- 如果您没有看到地图,请检查您是否已获取 API 密钥,以及是否已将其添加到应用,如上文所述。查看 Xcode 的调试控制台,查找有关 API 密钥的错误消息。
- 如果您已按 iOS 软件包标识符限制了 API 密钥,请修改密钥以为应用添加软件包标识符:
com.google.examples.map-with-marker
。 - 确保 Wi-Fi 或 GPS 连接良好。
- 使用 Xcode 调试工具查看日志并调试应用。
了解代码
- 创建地图,并将其设置为
loadView()
中的视图。Swift
// Create a GMSCameraPosition that tells the map to display the // coordinate -33.86,151.20 at zoom level 6. let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0) let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) view = mapView
Objective-C
// Create a GMSCameraPosition that tells the map to display the // coordinate -33.86,151.20 at zoom level 6. GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86 longitude:151.20 zoom:6.0]; GMSMapView *mapView = [[GMSMapView alloc] initWithFrame: CGRectZero camera:camera]; self.view = mapView;
- 向
loadView()
中的地图添加标记。Swift
// Creates a marker in the center of the map. let marker = GMSMarker() marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20) marker.title = "Sydney" marker.snippet = "Australia" marker.map = mapView
Objective-C
// Creates a marker in the center of the map. GMSMarker *marker = [[GMSMarker alloc] init]; marker.position = CLLocationCoordinate2DMake(-33.86, 151.20); marker.title = @"Sydney"; marker.snippet = @"Australia"; marker.map = mapView;
默认情况下,当用户点按某个标记时,Maps SDK for iOS 会显示信息窗口的内容。如果您愿意使用默认行为,则无需为标记添加点击监听器。
恭喜!您已构建了一个 iOS 应用,该应用显示使用标记指示特定位置的 Google 地图。您还学习了如何使用 Maps SDK for iOS。