使用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
};
});

概念验证小提琴

代码片段:

"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>

相关内容

  • 没有找到相关文章

最新更新