使用 Google 地图 API 访问嵌套的 geojson 数据

Access nested geojson data using the Google Maps API

我正在使用带有外部 json 的 Google 地图 API,它看起来像这样:

  {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [
            0,
            0
          ]
      },
      "properties": {
        "category": {
          "color": "#E91E63",
          "stroke-width": 1,
          "stroke-opacity": 1
        },
      },
    },

我正在努力达到 'colour' 像这样

        map.data.setStyle(function (feature) {
          var strokeColor = feature.getProperty('color');
            return {
              strokeColor: strokeColor,
              strokeWeight: 3
            }; 
        });

但由于它嵌套在类别中,我不确定如何访问它。有什么想法吗?

获取category属性,即returns一个具有GeoJSON中定义的属性的对象:

Object
color: "#E91E63"
stroke-opacity: 1
stroke-width: 1

在样式函数中这样获取:

map.data.setStyle(function(feature) {
  var category = feature.getProperty('category');
  var strokeColor = category.color;
  return {
    strokeColor: strokeColor,
    strokeWeight: 3
  };
});

proof of concept fiddle

代码片段:

"use strict";

let map;

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: {
      lat: 0,
      lng: 0
    }
  }); // NOTE: This uses cross-domain XHR, and may not work on older browsers.
  map.data.setStyle(function(feature) {
    var category = feature.getProperty('category');
    console.log(category);
    var strokeColor = category.color;
    return {
      strokeColor: strokeColor,
      strokeWeight: 3
    };
  });
  map.data.addGeoJson(geoJson);
}
var geoJson = {
  "type": "FeatureCollection",
  "features": [{
    "type": "Feature",
    "geometry": {
      "type": "LineString",
      "coordinates": [
        [
          0,
          0
        ],
        [10,
          10
        ]
      ]
    },
    "properties": {
      "category": {
        "color": "#E91E63",
        "stroke-width": 1,
        "stroke-opacity": 1
      },
    },
  }]
};
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Data Layer: Simple</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>
</body>

</html>