将数据集添加到地图

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

将样式应用于数据集地图项。

前提条件

在继续操作之前,您应备好地图 ID、地图样式和数据集 ID。

将数据集 ID 与地图样式相关联

若要设置数据集的地图项样式,请将样式函数应用于地图的数据集地图项图层。当您将数据集与地图样式相关联时,系统会创建数据集地图项图层。

如要将您的数据集与您使用的地图样式相关联,请按以下步骤操作:

  1. 在 Google Cloud 控制台中,前往数据集页面
  2. 点击相应数据集的名称。系统随即会显示数据集详细信息页面。
  3. 点击预览标签页。
  4. 关联的地图样式部分中,点击添加地图样式
    显示“添加地图样式”按钮的屏幕截图。
  5. 勾选要关联的地图样式对应的复选框,然后点击保存

将样式应用于数据集

如需设置数据集图层的地图项的样式,请使用样式闭包,它接受 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(例如,需要让部分地图项保持不可见状态时)。