如何解决使用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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。