分级统计图是一种主题地图,其中行政区的颜色或阴影是根据数据值确定的。您可以使用样式工厂 函数,根据数据设置地图样式,其中每个行政区均为 相关联。以下示例地图显示了 美国各州的分级统计图。
在此示例中,数据包含州的地点 ID。样式工厂函数会根据相应状态的地点 ID 的经过哈希处理的值,有条件地为每个状态着色。
按照 开始 以创建新的地图 ID 和地图样式。请务必启用 行政区级别 1 的地图项图层。
创建地图时,获取对行政区第 1 级地图项图层的引用, 地图初始化。在美国,这类行政级别 与各个州相对应
Java
private FeatureLayer areaLevel1Layer;
@Override public void onMapReady(GoogleMap map) { areaLevel1Layer = map.getFeatureLayer(new FeatureLayerOptions.Builder() .featureType(FeatureType.ADMINISTRATIVE_AREA_LEVEL_1) .build());
// Apply style factory function to ADMINISTRATIVE_AREA_LEVEL_1 layer. styleAreaLevel1Layer(); }Kotlin
private var areaLevel1Layer: FeatureLayer? = null
override fun onMapReady(googleMap: GoogleMap) { // Get the ADMINISTRATIVE_AREA_LEVEL_1 feature layer. areaLevel1Layer = googleMap.getFeatureLayer(FeatureLayerOptions.Builder() .featureType(FeatureType.ADMINISTRATIVE_AREA_LEVEL_1) .build())
// Apply style factory function to ADMINISTRATIVE_AREA_LEVEL_1 layer. styleAreaLevel1Layer() }创建一个样式工厂函数,并将其应用于行政区第 1 级地图项图层。以下示例将 函数设置为表示美国各州的多边形。
Java
private void styleAreaLevel1Layer() { FeatureLayer.StyleFactory styleFactory = (Feature feature) -> { if (feature instanceof PlaceFeature) { PlaceFeature placeFeature = (PlaceFeature) feature;
// Return a hueColor in the range [-299,299]. If the value is // negative, add 300 to make the value positive. int hueColor = placeFeature.getPlaceId().hashCode() % 300; if (hueColor < 0) { hueColor += 300; }
return new FeatureStyle.Builder() // Set the fill color for the state based on the hashed hue color. .fillColor(Color.HSVToColor(150, new float[] {hueColor, 1, 1})) .build(); } return null; };
// Apply the style factory function to the feature layer. areaLevel1Layer.setFeatureStyle(styleFactory); }Kotlin
private fun styleAreaLevel1Layer() { val styleFactory = FeatureLayer.StyleFactory { feature: Feature -> if (feature is PlaceFeature) { val placeFeature: PlaceFeature = feature as PlaceFeature
// Return a hueColor in the range [-299,299]. If the value is // negative, add 300 to make the value positive. var hueColor: Int = placeFeature.getPlaceId().hashCode() % 300 if (hueColor < 0) { hueColor += 300 } return@StyleFactory FeatureStyle.Builder() // Set the fill color for the state based on the hashed hue color. .fillColor(Color.HSVToColor(150, floatArrayOf(hueColor.toFloat(), 1f, 1f))) .build() } return@StyleFactory null }
// Apply the style factory function to the feature layer. areaLevel1Layer?.setFeatureStyle(styleFactory) }