设置数据地图项的样式

如果要将样式应用于数据地图项,请在数据集地图项图层将 style 属性设置为可以包含样式逻辑的 google.maps.FeatureStyleFunction;或者设置为 google.maps.FeatureStyleOptions,从而为图层的所有地图项设置统一样式。您可以为数据地图项应用填充样式(颜色、不透明度)、描边样式(颜色、不透明度、描边粗细)和直径样式(点)。本页面除了介绍如何以程序化方式访问数据集并设置其地图项的样式,还通过示例演示了如何基于点、多边形和多段线几何图形设置数据地图项的样式。

在对数据集进行数据驱动型样式设置时,系统会基于创建数据集时所用的地理空间数据文件中提供的经纬度坐标来渲染数据地图项。

数据地图项的属性

数据集内的所有数据均可通过地图项样式函数进行访问。如要获取数据地图项的属性,请先获取相应的数据集地图项(其中包含该数据集内的所有数据),然后再获取所需的特定数据属性,如下所示:

TypeScript

// Get the dataset feature, so we can work with all of its attributes.
const datasetFeature = params.feature;
// Get all of the needed dataset attributes.
const furColors = datasetFeature.datasetAttributes['CombinationofPrimaryandHighlightColor'];

JavaScript

// Get the dataset feature, so we can work with all of its attributes.
const datasetFeature = params.feature;
// Get all of the needed dataset attributes.
const furColors =
  datasetFeature.datasetAttributes["CombinationofPrimaryandHighlightColor"];

地图项样式选项

您可以在地图项样式选项中定义数据地图项图层的样式设置,例如为多边形设置填充和描边样式,或者为点设置颜色和直径样式。本例展示了可直接通过地图项的 style 属性加以应用的地图项样式选项:

TypeScript

// Apply style to all features.
datasetLayer.style = { strokeColor: 'green', strokeWeight: 4, };

JavaScript

// Apply style to all features.
datasetLayer.style = { strokeColor: "green", strokeWeight: 4 };

地图项样式函数

您可以使用地图项样式函数来定义数据集地图项的样式设置逻辑。如需设置地图项的样式,请将 style 属性设置为 google.maps.FeatureStyleFunction。您可通过样式函数对逻辑进行定义,以设置地图项图层上的各个地图项的样式。设置 featureLayer.style 后,样式函数会针对受影响的地图项图层中的每个地图项运行。系统会在您设置样式属性时应用该函数。如需更新样式,您必须重新设置 style 属性。本例展示了一个简单的地图项样式函数:

TypeScript

const styleDefault = {
  strokeColor: 'green',
  strokeWeight: 2.0,
  strokeOpacity: 1.0,
  fillColor: 'green',
  fillOpacity: 0.3,
};

const styleClicked = {
  ...styleDefault,
  strokeColor: 'blue',
  fillColor: 'blue',
  fillOpacity: 0.5,
};

const styleMouseMove = {
   ...styleDefault,
  strokeWeight: 4.0
};

function applyStyle(/* FeatureStyleFunctionOptions */ params) {
  const datasetFeature = params.feature;
  // Note, 'globalid' is an attribute in this dataset.
  //@ts-ignore
  if (lastClickedFeatureIds.includes(datasetFeature.datasetAttributes['globalid'])) {
    return styleClicked;
  }
  //@ts-ignore
  if (lastInteractedFeatureIds.includes(datasetFeature.datasetAttributes['globalid'])) {
    return styleMouseMove;
  }
  return styleDefault;
}

JavaScript

const styleDefault = {
  strokeColor: "green",
  strokeWeight: 2.0,
  strokeOpacity: 1.0,
  fillColor: "green",
  fillOpacity: 0.3,
};
const styleClicked = {
  ...styleDefault,
  strokeColor: "blue",
  fillColor: "blue",
  fillOpacity: 0.5,
};
const styleMouseMove = {
  ...styleDefault,
  strokeWeight: 4.0,
};

function applyStyle(/* FeatureStyleFunctionOptions */ params) {
  const datasetFeature = params.feature;

  // Note, 'globalid' is an attribute in this dataset.
  //@ts-ignore
  if (
    lastClickedFeatureIds.includes(datasetFeature.datasetAttributes["globalid"])
  ) {
    return styleClicked;
  }

  //@ts-ignore
  if (
    lastInteractedFeatureIds.includes(
      datasetFeature.datasetAttributes["globalid"],
    )
  ) {
    return styleMouseMove;
  }
  return styleDefault;
}

针对地图项应用样式函数时,样式函数应始终返回一致的结果。例如,如果要随机为一组地图项着色,不应针对随机部分应用地图项样式函数,否则会导致意外结果。由于此函数会针对图层中的每个地图项运行,因此优化至关重要。如果不再使用某个图层,请将样式设置为 null,以免渲染时间受到影响。

点数据的样式设置示例

本例演示了如何为基于点几何图形的数据地图项设置样式。

关于数据集

本例中使用的数据集是纽约市中央公园 2018 年松鼠调查的结果。下表摘录自 CSV 格式的调查数据文件,从中我们可以看到:xy 列用于表示地理位置;表中包含 LatLng 列,但在本例中并未使用该列,因为地理位置必须由两列表示。松鼠普查数据集包含多种不同的数据点,这些数据点与观察到的松鼠毛色和行为相关(请务必水平滚动屏幕,以查看全部内容)。

X Y UniqueSquirrelID Hectare Shift Date Hectare SquirrelNumber Age PrimaryFurColor HighlightFurColor CombinationofPrimaryandHighlightColor Colornotes Location AboveGroundSighter Measurement SpecificLocation Running Chasing Climbing Eating Foraging Other Activities Kuks Quaas Moans Tailflags Tailtwitches Approaches Indifferent Runsfrom OtherInteractions LatLng
-73.9561344937861 40.7940823884086 37F-PM-1014-03 37F PM 10142018 3 + false false false false false false false false false false false false false POINT (-73.9561344937861 40.7940823884086)
-73.9688574691102 40.7837825208444 21B-AM-1019-04 21B AM 10192018 4 + false false false false false false false false false false false false false POINT (-73.9688574691102 40.7837825208444)
-73.9742811484852 40.775533619083 11B-PM-1014-08 11B PM 10142018 8 Gray Gray+ Above Ground 10 false true false false false false false false false false false false false POINT (-73.97428114848522 40.775533619083)
-73.9596413903948 40.7903128889029 32E-PM-1017-14 32E PM 10172018 14 Adult Gray Gray+ Nothing selected as Primary. Gray selected as Highlights. Made executive adjustments. false false false true true false false false false false false false true POINT (-73.9596413903948 40.7903128889029)
-73.9702676472613 40.7762126854894 13E-AM-1017-05 13E AM 10172018 5 Adult Gray Cinnamon Gray+Cinnamon Above Ground on tree stump false false false false true false false false false false false false false POINT (-73.9702676472613 40.7762126854894)
-73.9683613516225 40.7725908847499 11H-AM-1010-03 11H AM 10102018 3 Adult Cinnamon White Cinnamon+White false false false false true false false false false true false true false POINT (-73.9683613516225 40.7725908847499)
-73.9541201789795 40.7931811701082 36H-AM-1010-02 36H AM 10102018 2 Adult Gray Gray+ just outside hectare Ground Plane FALSE false false false false true false false false false false false false false POINT (-73.9541201789795 40.7931811701082)

设置点数据地图项的样式

本例中的代码采用简单的方法,根据 CombinationofPrimaryandHighlightColor 属性(该属性合并了每只松鼠的主要毛色和次要毛色)为每个点的填充颜色和描边颜色设置样式。

TypeScript

function setStyle(/* FeatureStyleFunctionOptions */ params) {
    // Get the dataset feature, so we can work with all of its attributes.
    const datasetFeature = params.feature;
    // Get all of the needed dataset attributes.
    const furColors = datasetFeature.datasetAttributes['CombinationofPrimaryandHighlightColor'];

    // Apply styles. Fill is primary fur color, stroke is secondary fur color.
    switch (furColors) {
        case 'Black+':
            return /* FeatureStyleOptions */ { fillColor: 'black', pointRadius: 8 };
            break;
        case 'Cinnamon+':
            return /* FeatureStyleOptions */ { fillColor: '#8b0000', pointRadius: 8 };
            break;
        case 'Cinnamon+Gray':
            return /* FeatureStyleOptions */ { fillColor: '#8b0000', strokeColor: 'gray', pointRadius: 6 };
            break;
        case 'Cinnamon+White':
            return /* FeatureStyleOptions */ { fillColor: '#8b0000', strokeColor: 'white', pointRadius: 6 };
            break;
        case 'Gray+':
            return /* FeatureStyleOptions */ { fillColor: 'gray', pointRadius: 8 };
            break;
        case 'Gray+Cinnamon':
            return /* FeatureStyleOptions */ { fillColor: 'gray', strokeColor: '#8b0000', pointRadius: 6 };
            break;
        case 'Gray+Cinnamon, White':
            return /* FeatureStyleOptions */ { fillColor: 'silver', strokeColor: '#8b0000', pointRadius: 6 };
            break;
        case 'Gray+White':
            return /* FeatureStyleOptions */ { fillColor: 'gray', strokeColor: 'white', pointRadius: 6 };
            break;
        default: // Color not defined.
            return /* FeatureStyleOptions */ { fillColor: 'yellow', pointRadius: 8 };
            break; 
    }
}

JavaScript

function setStyle(/* FeatureStyleFunctionOptions */ params) {
  // Get the dataset feature, so we can work with all of its attributes.
  const datasetFeature = params.feature;
  // Get all of the needed dataset attributes.
  const furColors =
    datasetFeature.datasetAttributes["CombinationofPrimaryandHighlightColor"];

  // Apply styles. Fill is primary fur color, stroke is secondary fur color.
  switch (furColors) {
    case "Black+":
      return /* FeatureStyleOptions */ { fillColor: "black", pointRadius: 8 };
      break;
    case "Cinnamon+":
      return /* FeatureStyleOptions */ { fillColor: "#8b0000", pointRadius: 8 };
      break;
    case "Cinnamon+Gray":
      return /* FeatureStyleOptions */ {
        fillColor: "#8b0000",
        strokeColor: "gray",
        pointRadius: 6,
      };
      break;
    case "Cinnamon+White":
      return /* FeatureStyleOptions */ {
        fillColor: "#8b0000",
        strokeColor: "white",
        pointRadius: 6,
      };
      break;
    case "Gray+":
      return /* FeatureStyleOptions */ { fillColor: "gray", pointRadius: 8 };
      break;
    case "Gray+Cinnamon":
      return /* FeatureStyleOptions */ {
        fillColor: "gray",
        strokeColor: "#8b0000",
        pointRadius: 6,
      };
      break;
    case "Gray+Cinnamon, White":
      return /* FeatureStyleOptions */ {
        fillColor: "silver",
        strokeColor: "#8b0000",
        pointRadius: 6,
      };
      break;
    case "Gray+White":
      return /* FeatureStyleOptions */ {
        fillColor: "gray",
        strokeColor: "white",
        pointRadius: 6,
      };
      break;
    default: // Color not defined.
      return /* FeatureStyleOptions */ { fillColor: "yellow", pointRadius: 8 };
      break;
  }
}

完整示例代码

查看完整的示例源代码

TypeScript

let map;
function setStyle(/* FeatureStyleFunctionOptions */ params) {
    // Get the dataset feature, so we can work with all of its attributes.
    const datasetFeature = params.feature;
    // Get all of the needed dataset attributes.
    const furColors = datasetFeature.datasetAttributes['CombinationofPrimaryandHighlightColor'];

    // Apply styles. Fill is primary fur color, stroke is secondary fur color.
    switch (furColors) {
        case 'Black+':
            return /* FeatureStyleOptions */ { fillColor: 'black', pointRadius: 8 };
            break;
        case 'Cinnamon+':
            return /* FeatureStyleOptions */ { fillColor: '#8b0000', pointRadius: 8 };
            break;
        case 'Cinnamon+Gray':
            return /* FeatureStyleOptions */ { fillColor: '#8b0000', strokeColor: 'gray', pointRadius: 6 };
            break;
        case 'Cinnamon+White':
            return /* FeatureStyleOptions */ { fillColor: '#8b0000', strokeColor: 'white', pointRadius: 6 };
            break;
        case 'Gray+':
            return /* FeatureStyleOptions */ { fillColor: 'gray', pointRadius: 8 };
            break;
        case 'Gray+Cinnamon':
            return /* FeatureStyleOptions */ { fillColor: 'gray', strokeColor: '#8b0000', pointRadius: 6 };
            break;
        case 'Gray+Cinnamon, White':
            return /* FeatureStyleOptions */ { fillColor: 'silver', strokeColor: '#8b0000', pointRadius: 6 };
            break;
        case 'Gray+White':
            return /* FeatureStyleOptions */ { fillColor: 'gray', strokeColor: 'white', pointRadius: 6 };
            break;
        default: // Color not defined.
            return /* FeatureStyleOptions */ { fillColor: 'yellow', pointRadius: 8 };
            break; 
    }
}

async function initMap() {
    // Request needed libraries.
    const { Map } = await google.maps.importLibrary('maps') as google.maps.MapsLibrary;

    const position = {lat: 40.780101, lng: -73.967780};
    const map = new Map(document.getElementById('map') as HTMLElement, {
        zoom: 17,
        center: position,
        mapId: 'b98e588c46685dd7',
        mapTypeControl: false,
        streetViewControl: false,
        fullscreenControl: false,
    });

    // Add the data legend.
    makeLegend(map);

    // Dataset ID for squirrel dataset.
    const datasetId = '02fa1552-37dd-4a95-844f-f99e1c22541f';
    //@ts-ignore
    const datasetLayer = map.getDatasetFeatureLayer(datasetId);
    //@ts-ignore
    datasetLayer.style = setStyle;

    // Create an attribution DIV and add the attribution to the map.
    const attributionDiv = document.createElement('div');
    const attributionControl = createAttribution(map);
    attributionDiv.appendChild(attributionControl);
    map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(attributionDiv);
}

// Create a custom control to hold attribution text.
function createAttribution(map) {
    const attributionLabel = document.createElement('div');
    // Define CSS styles.
    attributionLabel.style.backgroundColor = '#fff';
    attributionLabel.style.opacity = '0.7';
    attributionLabel.style.fontFamily = 'Roboto,Arial,sans-serif';
    attributionLabel.style.fontSize = '10px';
    attributionLabel.style.padding = '2px';
    attributionLabel.style.margin = '2px';
    attributionLabel.textContent = 'Data source: NYC Open Data';
    return attributionLabel;
}

function makeLegend(map) {
    let colors = {
        'black': ['black'],
        'cinnamon': ['#8b0000'],
        'cinnamon + gray': ['#8b0000','gray'],
        'cinnamon + white': ['#8b0000', 'white'],
        'gray': ['gray'],
        'gray + cinnamon': ['gray', '#8b0000'],
        'gray + cinnamon + white': ['silver', '#8b0000'],
        'gray + white': ['gray', 'white'],
        'no color data': ['yellow'],
    };
    let legend = document.createElement('div');
    legend.id = 'legend';
    let title = document.createElement('div');
    title.innerText = 'Fur Colors';
    title.classList.add('title');
    legend.appendChild(title);
    let k;
    for (k in colors) {
        let wrapper = document.createElement('div');
        wrapper.id = 'container';
        let box = document.createElement('div');
        box.style.backgroundColor = colors[k][0];
        if (colors[k][1]) {
            box.style.borderColor = colors[k][1];
        } else {
            box.style.borderColor = colors[k][0];
        }
        box.classList.add('box');
        let txt = document.createElement('div');
        txt.classList.add('legend');
        txt.innerText = k;
        wrapper.appendChild(box);
        wrapper.appendChild(txt);
        legend.appendChild(wrapper);
    }
    map.controls[google.maps.ControlPosition.LEFT_TOP].push(legend);
}

initMap();

JavaScript

let map;

function setStyle(/* FeatureStyleFunctionOptions */ params) {
  // Get the dataset feature, so we can work with all of its attributes.
  const datasetFeature = params.feature;
  // Get all of the needed dataset attributes.
  const furColors =
    datasetFeature.datasetAttributes["CombinationofPrimaryandHighlightColor"];

  // Apply styles. Fill is primary fur color, stroke is secondary fur color.
  switch (furColors) {
    case "Black+":
      return /* FeatureStyleOptions */ { fillColor: "black", pointRadius: 8 };
      break;
    case "Cinnamon+":
      return /* FeatureStyleOptions */ { fillColor: "#8b0000", pointRadius: 8 };
      break;
    case "Cinnamon+Gray":
      return /* FeatureStyleOptions */ {
        fillColor: "#8b0000",
        strokeColor: "gray",
        pointRadius: 6,
      };
      break;
    case "Cinnamon+White":
      return /* FeatureStyleOptions */ {
        fillColor: "#8b0000",
        strokeColor: "white",
        pointRadius: 6,
      };
      break;
    case "Gray+":
      return /* FeatureStyleOptions */ { fillColor: "gray", pointRadius: 8 };
      break;
    case "Gray+Cinnamon":
      return /* FeatureStyleOptions */ {
        fillColor: "gray",
        strokeColor: "#8b0000",
        pointRadius: 6,
      };
      break;
    case "Gray+Cinnamon, White":
      return /* FeatureStyleOptions */ {
        fillColor: "silver",
        strokeColor: "#8b0000",
        pointRadius: 6,
      };
      break;
    case "Gray+White":
      return /* FeatureStyleOptions */ {
        fillColor: "gray",
        strokeColor: "white",
        pointRadius: 6,
      };
      break;
    default: // Color not defined.
      return /* FeatureStyleOptions */ { fillColor: "yellow", pointRadius: 8 };
      break;
  }
}

async function initMap() {
  // Request needed libraries.
  const { Map } = await google.maps.importLibrary("maps");
  const position = { lat: 40.780101, lng: -73.96778 };
  const map = new Map(document.getElementById("map"), {
    zoom: 17,
    center: position,
    mapId: "b98e588c46685dd7",
    mapTypeControl: false,
    streetViewControl: false,
    fullscreenControl: false,
  });

  // Add the data legend.
  makeLegend(map);

  // Dataset ID for squirrel dataset.
  const datasetId = "02fa1552-37dd-4a95-844f-f99e1c22541f";
  //@ts-ignore
  const datasetLayer = map.getDatasetFeatureLayer(datasetId);

  //@ts-ignore
  datasetLayer.style = setStyle;

  // Create an attribution DIV and add the attribution to the map.
  const attributionDiv = document.createElement("div");
  const attributionControl = createAttribution(map);

  attributionDiv.appendChild(attributionControl);
  map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(attributionDiv);
}

// Create a custom control to hold attribution text.
function createAttribution(map) {
  const attributionLabel = document.createElement("div");

  // Define CSS styles.
  attributionLabel.style.backgroundColor = "#fff";
  attributionLabel.style.opacity = "0.7";
  attributionLabel.style.fontFamily = "Roboto,Arial,sans-serif";
  attributionLabel.style.fontSize = "10px";
  attributionLabel.style.padding = "2px";
  attributionLabel.style.margin = "2px";
  attributionLabel.textContent = "Data source: NYC Open Data";
  return attributionLabel;
}

function makeLegend(map) {
  let colors = {
    "black": ["black"],
    "cinnamon": ["#8b0000"],
    "cinnamon + gray": ["#8b0000", "gray"],
    "cinnamon + white": ["#8b0000", "white"],
    "gray": ["gray"],
    "gray + cinnamon": ["gray", "#8b0000"],
    "gray + cinnamon + white": ["silver", "#8b0000"],
    "gray + white": ["gray", "white"],
    "no color data": ["yellow"],
  };
  let legend = document.createElement("div");

  legend.id = "legend";

  let title = document.createElement("div");

  title.innerText = "Fur Colors";
  title.classList.add("title");
  legend.appendChild(title);

  let k;

  for (k in colors) {
    let wrapper = document.createElement("div");

    wrapper.id = "container";

    let box = document.createElement("div");

    box.style.backgroundColor = colors[k][0];
    if (colors[k][1]) {
      box.style.borderColor = colors[k][1];
    } else {
      box.style.borderColor = colors[k][0];
    }

    box.classList.add("box");

    let txt = document.createElement("div");

    txt.classList.add("legend");
    txt.innerText = k;
    wrapper.appendChild(box);
    wrapper.appendChild(txt);
    legend.appendChild(wrapper);
  }

  map.controls[google.maps.ControlPosition.LEFT_TOP].push(legend);
}

initMap();

多边形数据的样式设置示例

本例演示了如何为基于多边形几何图形的数据地图项设置样式。

关于数据集

本例中使用的数据集描绘的是纽约市的公园。以下内容摘录自 GeoJSON 数据集文件,显示了一个具有代表性的地图项条目。

{
  "type": "Feature",
  "properties": {
    "jurisdiction": "DPR",
    "mapped": "False",
    "zipcode": "11356",
    "acres": "0.05",
    "location": "College Pl., College Pt. Blvd., bet. 11 Ave. and 12 Ave.",
    "nys_assembly": "27",
    "councildistrict": "19",
    "url": "http://www.nycgovparks.org/parks/Q042/",
    "typecategory": "Triangle/Plaza",
    "us_congress": "14",
    "eapply": "Poppenhusen Park",
    "parentid": "Q-07",
    "gispropnum": "Q042",
    "retired": "false",
    "communityboard": "407",
    "objectid": "6248",
    "globalid": "F4810079-CBB9-4BE7-BBFA-B3C0C35D5DE5",
    "name311": "Poppenhusen Park",
    "department": "Q-07",
    "pip_ratable": "true",
    "subcategory": "Sitting Area/Triangle/Mall",
    "precinct": "109",
    "permit": "true",
    "acquisitiondate": null,
    "omppropid": "Q042",
    "gisobjid": "100000301",
    "signname": "Poppenhusen Park",
    "address": null,
    "permitparent": "Q-07",
    "class": "PARK",
    "nys_senate": "11",
    "permitdistrict": "Q-07",
    "borough": "Q",
    "waterfront": "false"
  },
  "geometry": {
    "type": "MultiPolygon",
    "coordinates": [
      [
        [
          [
            -73.84575702371716,
            40.78796240884273
          ],
          [
            -73.84593393292693,
            40.78796857347548
          ],
          [
            -73.84577256469657,
            40.787651355629556
          ],
          [
            -73.84575702371716,
            40.78796240884273
          ]
        ]
      ]
    ]
  }
},

设置多边形数据地图项的样式

本例中的代码将特殊颜色应用于 typecategory 为“Undeveloped”或“Parkway”的数据地图项,并将所有其他地图项的颜色设为绿色。

TypeScript

function setStyle(/* FeatureStyleFunctionOptions */ params) {
    const datasetFeature = params.feature;
    // 'typecategory' is an attribute in this Dataset.
    const typeCategory = datasetFeature.datasetAttributes['typecategory'];

    switch (typeCategory) {
        case 'Undeveloped': // Color undeveloped areas blue.
            return /* FeatureStyleOptions */ {
                strokeColor: 'blue',
                strokeWeight: 2,
                strokeOpacity: 1,
                fillColor: 'blue',
                fillOpacity: 0.3,
            };
            break;
        case 'Parkway': // Color historical house sites red.
            return /* FeatureStyleOptions */ {
                strokeColor: 'red',
                strokeWeight: 2,
                strokeOpacity: 1,
                fillColor: 'red',
                fillOpacity: 0.5,
            };
            break;
        default: // Color other type categories green.
            return /* FeatureStyleOptions */ {
                strokeColor: 'green',
                strokeWeight: 2,
                strokeOpacity: 1,
                fillColor: 'green',
                fillOpacity: 0.3,
            };
            break;
    }
}

JavaScript

function setStyle(/* FeatureStyleFunctionOptions */ params) {
  const datasetFeature = params.feature;
  // 'typecategory' is an attribute in this Dataset.
  const typeCategory = datasetFeature.datasetAttributes["typecategory"];

  switch (typeCategory) {
    case "Undeveloped": // Color undeveloped areas blue.
      return /* FeatureStyleOptions */ {
        strokeColor: "blue",
        strokeWeight: 2,
        strokeOpacity: 1,
        fillColor: "blue",
        fillOpacity: 0.3,
      };
      break;
    case "Parkway": // Color historical house sites red.
      return /* FeatureStyleOptions */ {
        strokeColor: "red",
        strokeWeight: 2,
        strokeOpacity: 1,
        fillColor: "red",
        fillOpacity: 0.5,
      };
      break;
    default: // Color other type categories green.
      return /* FeatureStyleOptions */ {
        strokeColor: "green",
        strokeWeight: 2,
        strokeOpacity: 1,
        fillColor: "green",
        fillOpacity: 0.3,
      };
      break;
  }
}

完整示例代码

查看完整的示例源代码

TypeScript

let map;
function setStyle(/* FeatureStyleFunctionOptions */ params) {
    const datasetFeature = params.feature;
    // 'typecategory' is an attribute in this Dataset.
    const typeCategory = datasetFeature.datasetAttributes['typecategory'];

    switch (typeCategory) {
        case 'Undeveloped': // Color undeveloped areas blue.
            return /* FeatureStyleOptions */ {
                strokeColor: 'blue',
                strokeWeight: 2,
                strokeOpacity: 1,
                fillColor: 'blue',
                fillOpacity: 0.3,
            };
            break;
        case 'Parkway': // Color historical house sites red.
            return /* FeatureStyleOptions */ {
                strokeColor: 'red',
                strokeWeight: 2,
                strokeOpacity: 1,
                fillColor: 'red',
                fillOpacity: 0.5,
            };
            break;
        default: // Color other type categories green.
            return /* FeatureStyleOptions */ {
                strokeColor: 'green',
                strokeWeight: 2,
                strokeOpacity: 1,
                fillColor: 'green',
                fillOpacity: 0.3,
            };
            break;
    }
}

async function initMap() {
    // Request needed libraries.
    const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;

    const position = {lat: 40.580732, lng: -74.152826};
    const map = new Map(document.getElementById('map') as HTMLElement, {
        zoom: 14,
        center: position,
        mapId: 'b98e588c46685dd7',
        mapTypeControl: false,
    });

    // Dataset ID for NYC park data.
    const datasetId = '6fe13aa9-b900-45e7-b636-3236672c3f4f';
    //@ts-ignore
    const datasetLayer = map.getDatasetFeatureLayer(datasetId);
    datasetLayer.style = setStyle;

    // Create an attribution DIV and add the attribution to the map.
    const attributionDiv = document.createElement('div');
    const attributionControl = createAttribution(map);
    attributionDiv.appendChild(attributionControl);
    map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(attributionDiv);
}

function createAttribution(map) {
    const attributionLabel = document.createElement('div');
    // Define CSS styles.
    attributionLabel.style.backgroundColor = '#fff';
    attributionLabel.style.opacity = '0.7';
    attributionLabel.style.fontFamily = 'Roboto,Arial,sans-serif';
    attributionLabel.style.fontSize = '10px';
    attributionLabel.style.padding = '2px';
    attributionLabel.style.margin = '2px';
    attributionLabel.textContent = 'Data source: NYC Open Data';
    return attributionLabel;
}

initMap();

JavaScript

let map;

function setStyle(/* FeatureStyleFunctionOptions */ params) {
  const datasetFeature = params.feature;
  // 'typecategory' is an attribute in this Dataset.
  const typeCategory = datasetFeature.datasetAttributes["typecategory"];

  switch (typeCategory) {
    case "Undeveloped": // Color undeveloped areas blue.
      return /* FeatureStyleOptions */ {
        strokeColor: "blue",
        strokeWeight: 2,
        strokeOpacity: 1,
        fillColor: "blue",
        fillOpacity: 0.3,
      };
      break;
    case "Parkway": // Color historical house sites red.
      return /* FeatureStyleOptions */ {
        strokeColor: "red",
        strokeWeight: 2,
        strokeOpacity: 1,
        fillColor: "red",
        fillOpacity: 0.5,
      };
      break;
    default: // Color other type categories green.
      return /* FeatureStyleOptions */ {
        strokeColor: "green",
        strokeWeight: 2,
        strokeOpacity: 1,
        fillColor: "green",
        fillOpacity: 0.3,
      };
      break;
  }
}

async function initMap() {
  // Request needed libraries.
  const { Map } = await google.maps.importLibrary("maps");
  const position = { lat: 40.580732, lng: -74.152826 };
  const map = new Map(document.getElementById("map"), {
    zoom: 14,
    center: position,
    mapId: "b98e588c46685dd7",
    mapTypeControl: false,
  });
  // Dataset ID for NYC park data.
  const datasetId = "6fe13aa9-b900-45e7-b636-3236672c3f4f";
  //@ts-ignore
  const datasetLayer = map.getDatasetFeatureLayer(datasetId);

  datasetLayer.style = setStyle;

  // Create an attribution DIV and add the attribution to the map.
  const attributionDiv = document.createElement("div");
  const attributionControl = createAttribution(map);

  attributionDiv.appendChild(attributionControl);
  map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(attributionDiv);
}

function createAttribution(map) {
  const attributionLabel = document.createElement("div");

  // Define CSS styles.
  attributionLabel.style.backgroundColor = "#fff";
  attributionLabel.style.opacity = "0.7";
  attributionLabel.style.fontFamily = "Roboto,Arial,sans-serif";
  attributionLabel.style.fontSize = "10px";
  attributionLabel.style.padding = "2px";
  attributionLabel.style.margin = "2px";
  attributionLabel.textContent = "Data source: NYC Open Data";
  return attributionLabel;
}

initMap();

多段线数据的样式设置示例

本例演示了如何为基于多段线几何图形的数据地图项设置样式。

关于数据集

本例中使用的数据集描绘的是西雅图地区的桥梁。以下内容摘录自 GeoJSON 数据集文件,显示了一个具有代表性的地图项条目。

{
  "type": "Feature",
  "properties": {
      "OBJECTID": 1,
      "COMPTYPE": 66,
      "COMPKEY": 515774,
      "HANSEGKEY": 489781,
      "UNITID": "BRG-935",
      "UNITTYPE": " ",
      "BRGUNITID": "BRG-935",
      "UNITDESC_BRG": "YALE AVE BR REV LANE OC                                                                                                                                                                                                                                        ",
      "UNITDESC_SEG": "HOWELL ST ON RP BETWEEN HOWELL ST AND I5 SB                                                                                                                                                                                                                    ",
      "INSTDATE": null,
      "EXPDATE": null,
      "STATUS": " ",
      "STATUSDT": null,
      "CONDITION": " ",
      "CONDDT": null,
      "OWN": " ",
      "LSTVERIFY": null,
      "MAINTBY": " ",
      "ADDBY": "GARCIAA",
      "ADDDTTM": "2010-01-21T00:00:00Z",
      "MODBY": null,
      "MODDTTM": null,
      "BR_NBR": 935,
      "BR_CODE": " 935",
      "BR_TYPE": "ST",
      "BR_NAME": "YALE AVE BR REV LANE OC",
      "BR_FACILITIES": "YALE AVE-SR 5 ON RAMP",
      "BR_FEATURES": "SR 5 REV LANE",
      "BR_RATING": 0,
      "BR_INSET": 1,
      "BR_GEO": "DT",
      "BR_OWNER": "DOT",
      "BR_OWNER_NAME": "State of Washington",
      "GEOBASID": 0,
      "XGEOBASID": 0,
      "GISSEGKEY": 489781,
      "EARTHQUAKE_RESPONSE_TEAM": " ",
      "SHAPE_Length": 220.11891836147655
  },
  "geometry": {
      "type": "LineString",
      "coordinates": [
          [
              -122.329201929090928,
              47.616910448708538
          ],
          [
              -122.329206483407461,
              47.616976719821004
          ],
          [
              -122.32921802149356,
              47.617042137515213
          ],
          [
              -122.329236413912909,
              47.617105967923777
          ],
          [
              -122.329261454336034,
              47.617167494985758
          ],
          [
              -122.329292861855023,
              47.617226028479571
          ],
          [
              -122.329330284134699,
              47.617280911766009
          ],
          [
              -122.329373301365223,
              47.617331529154569
          ],
          [
              -122.329421430971635,
              47.617377312810319
          ],
          [
              -122.329474133027375,
              47.617417749124023
          ],
          [
              -122.32953081631139,
              47.617452384473893
          ]
      ]
  }
},

设置多段线数据地图项的样式

以下代码段会将相同的样式直接应用于所有数据地图项。由于不需要逻辑,因此本例中没有使用地图项样式函数。

TypeScript

// Apply style to all features.
datasetLayer.style = { strokeColor: 'green', strokeWeight: 4, };

JavaScript

// Apply style to all features.
datasetLayer.style = { strokeColor: "green", strokeWeight: 4 };

查看完整的示例源代码

TypeScript

let map;
async function initMap() {
    // Request needed libraries.
    const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;

    const position = {lat: 47.59, lng: -122.31};
    const map = new Map(document.getElementById('map') as HTMLElement, {
        zoom: 14,
        center: position,
        mapId: 'b98e588c46685dd7',
        mapTypeControl: false,
    });

    // Dataset ID for Seattle Bridges
    const datasetId = '3d0bd5fb-3f42-47fe-b50f-81c0932cd533';
    //@ts-ignore
    const datasetLayer = map.getDatasetFeatureLayer(datasetId);
    // Apply style to all features.
    datasetLayer.style = { strokeColor: 'green', strokeWeight: 4, };
    // Create an attribution DIV and add the attribution to the map.
    const attributionDiv = document.createElement('div');
    const attributionControl = createAttribution(map);
    attributionDiv.appendChild(attributionControl);
    map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(attributionDiv);
}

// Create a custom control to hold attribution text.
function createAttribution(map) {
    const attributionLabel = document.createElement('div');
    // Define CSS styles.
    attributionLabel.style.backgroundColor = '#fff';
    attributionLabel.style.opacity = '0.7';
    attributionLabel.style.fontFamily = 'Roboto,Arial,sans-serif';
    attributionLabel.style.fontSize = '10px';
    attributionLabel.style.padding = '2px';
    attributionLabel.style.margin = '2px';
    attributionLabel.textContent = 'Data source: Seattle GeoData';
    return attributionLabel;
}

initMap();

JavaScript

let map;

async function initMap() {
  // Request needed libraries.
  const { Map } = await google.maps.importLibrary("maps");
  const position = { lat: 47.59, lng: -122.31 };
  const map = new Map(document.getElementById("map"), {
    zoom: 14,
    center: position,
    mapId: "b98e588c46685dd7",
    mapTypeControl: false,
  });
  // Dataset ID for Seattle Bridges
  const datasetId = "3d0bd5fb-3f42-47fe-b50f-81c0932cd533";
  //@ts-ignore
  const datasetLayer = map.getDatasetFeatureLayer(datasetId);

  // Apply style to all features.
  datasetLayer.style = { strokeColor: "green", strokeWeight: 4 };

  // Create an attribution DIV and add the attribution to the map.
  const attributionDiv = document.createElement("div");
  const attributionControl = createAttribution(map);

  attributionDiv.appendChild(attributionControl);
  map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(attributionDiv);
}

// Create a custom control to hold attribution text.
function createAttribution(map) {
  const attributionLabel = document.createElement("div");

  // Define CSS styles.
  attributionLabel.style.backgroundColor = "#fff";
  attributionLabel.style.opacity = "0.7";
  attributionLabel.style.fontFamily = "Roboto,Arial,sans-serif";
  attributionLabel.style.fontSize = "10px";
  attributionLabel.style.padding = "2px";
  attributionLabel.style.margin = "2px";
  attributionLabel.textContent = "Data source: Seattle GeoData";
  return attributionLabel;
}

initMap();