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

问题描述

我正在使用带有外部json的Google Maps API,

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

我正试图像这样“变色”

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

但是由于它嵌套在类别中,所以我不确定如何获取它。有什么想法吗?

解决方法

获取category属性,该属性返回具有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>