本页面介绍了如何将数据集添加到地图以及如何应用样式设置。

前提条件
在继续操作之前,您应备好地图 ID、地图样式和数据集 ID。
将数据集 ID 与地图样式相关联
如需设置数据集地图项的样式,请将样式函数应用于地图的 数据集地图项图层。当您 将数据集与地图样式相关联时,系统会创建数据集地图项图层。
如要将您的数据集与您使用的地图样式相关联,请按以下步骤操作:
- 在 Google Cloud 控制台中,进入数据集页面。
- 点击相应数据集的名称。系统随即会显示数据集详细信息 页面。
- 点击预览 标签页。
- 在关联的地图样式 部分中,点击
添加地图样式。
- 勾选要关联的地图样式对应的复选框,然后点击 保存。
将样式应用于数据集
如需设置数据集图层的地图项的样式,请使用样式设置闭包,该闭包接受
GMSDatasetFeature并返回GMSFeatureStyle以定义样式
属性。然后,将样式属性设置为包含样式设置逻辑的样式设置闭包。
样式设置闭包必须是确定性的,并且在应用时返回一致的结果。如果任何地图项的任何样式规范发生更改,则必须重新应用样式。
设置描边、填充和点半径
在样式工厂函数中设置地图项的样式时,您可以设置以下内容:
边框的描边颜色和不透明度 ,由
UIColor类定义。默认值为透明 (UIColor.clearColor)。边框的描边宽度 (以屏幕像素为单位)。默认值为 2。
填充颜色和不透明度 ,由
UIColor类定义。默认值为透明 (UIColor.clearColor)。点地图项的点半径 ,介于 0 到 128 像素之间。
使用简单的样式规则
设置地图项样式时,最简单的方式是定义常量样式属性,例如颜色、不透明度和线宽。您可以直接将地图项样式选项应用于数据集地图项图层,也可以将这些选项与自定义样式设置搭配使用。
Swift
let mapView = GMSMapView(frame: .zero, mapID: GMSMapID(identifier: "YOUR_MAP_ID"), camera: GMSCameraPosition(latitude: 40.7, longitude: -74.0, zoom: 12)) let layer = mapView.datasetFeatureLayer(of: "YOUR_DATASET_ID") // Define a style with green fill and stroke. // Apply the style to all features in the dataset. layer.style = { feature in let style = MutableFeatureStyle() style.fillColor = .green.withAlphaComponent(0.1) style.strokeColor = .green style.strokeWidth = 2.0 return style }
Objective-C
GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero mapID:[GMSMapID mapIDWithIdentifier:@"MAP_ID"] camera:[GMSCameraPosition cameraWithLatitude: 40.7 longitude: -74.0 zoom:12]]; GMSDatasetFeatureLayer *layer = [mapView datasetFeatureLayerOfDatasetID:@"YOUR_DATASET_ID"]; // Define a style with green fill and stroke. // Apply the style to all features in the dataset. layer.style = ^(GMSDatasetFeature *feature) { GMSMutableFeatureStyle *style = [GMSMutableFeatureStyle style]; style.fillColor = [[UIColor greenColor] colorWithAlphaComponent:0.1]; style.strokeColor = [UIColor greenColor]; style.strokeWidth = 2.0; return style; };
使用声明式样式规则
您可以根据地图项的属性以声明方式设置样式规则,并将其应用于整个数据集。您还可以从地图项样式函数返回 nil(例如,需要让部分地图项保持不可见状态时)。
例如,使用
GMSDatasetFeature.datasetAttributes
返回地图项的数据集属性的值。然后,您可以根据地图项的属性自定义其样式。
以下示例确定数据集的每个地图项的“highlightColor”属性的值,以控制样式设置:
Swift
layer.style = { feature in var attributeColor: String = feature.datasetAttributes["highlightColor"] // Conditionalize styling based on the value of the "highlightColor" attribute. ... }
Objective-C
// Apply the style to a single dataset feature. layer.style = ^(GMSDatasetFeature *feature) { NSString *attributeColor = feature.datasetAttributes[@"highlightColor"]; // Conditionalize styling based on the value of the "highlightColor" attribute. ... };
移除图层的样式
如需移除图层的样式,请将 style 设置为 null:
Swift
layer.style = nil
Objective-C
layer.style = nil;
您还可以从地图项样式函数返回 nil(例如,需要让部分地图项保持不可见状态时)。