製作 choropleth 地圖

選取平台: Android iOS JavaScript

「choropleth 地圖」是一種主題地圖,其中的行政區會根據資料值加上顏色或陰影。您可以使用樣式工廠函式,根據資料設定地圖樣式,其中每個行政區都與一個範圍內的數值相關聯。以下地圖範例為美國各州的分級著色圖。

在本例中,資料是由州/省的地點 ID 組成。樣式工廠函式會根據狀態的地點 ID 雜湊值,為每個狀態加上條件式上色。

螢幕截圖:顯示美國各州的分級著色圖。

  1. 如果尚未建立新的地圖 ID 和地圖樣式,請按照「開始使用」一文中的步驟進行。請務必啟用 行政區層級 1 地圖項目圖層。

  2. 在地圖初始化時,取得行政區第一級地圖項目圖層的參照。在美國境內,這些行政層級對應到各州。

    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) }