製作 choropleth 地圖

選取平台: Android iOS JavaScript

「choropleth 地圖」是一種主題地圖,其中的行政區會根據資料值加上顏色或陰影。你可以使用風格工廠 函式,根據每個行政區的位置,設定地圖樣式 只和一個數值範圍產生關聯下方地圖範例顯示 美國各州的 choropleth 地圖。

在本例中,資料是由州/省的地點 ID 組成。樣式 工廠函式會根據 州的地點 ID。

螢幕截圖顯示美國各州的 choropleth 地圖。

  1. 如果您還沒有這樣做,請按照 開始使用 建立新的地圖 ID 和地圖樣式。請務必啟用 行政區層級 1 地圖項目圖層。

  2. 在執行以下動作時,取得 行政區層級 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() }

  3. 建立樣式工廠函式,並套用至 行政區層級 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) }