宣传单 - 如何有条件地为特定国家/地区着色?

cbl*_*bll 4 javascript leaflet react-leaflet

我有一个离线的Leaflet地图,其中的国家/地区是从带有坐标的巨大Javascript变量中提取的.

index.html就是这样(来自codepen的一个例子,我在本地加载库):

<html>

<head>

  <title>Leaflet</title>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
  <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>

</head>

<body>

  <div id="mapid" style="width: 100%; height: 800px;"></div>

</body>

</html>
Run Code Online (Sandbox Code Playgroud)

而Map.js是这样的:

var map = L.map('mapid').setView([0, 0], 2);

// Huge geojson of every country, one country sample here. 
var countries =  "type": "FeatureCollection",
"features": [{
    "type": "Feature",
    "id": "AFG",
    "properties": {
        "name": "Afghanistan"
    },
    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
                [61.210817, 35.650072],
                [62.230651, 35.270664],
                [62.984662, 35.404041],
                [63.193538, 35.857166],
                [63.982896, 36.007957],
                [64.546479, 36.312073],
                [64.746105, 37.111818],
                [65.588948, 37.305217],
                [65.745631, 37.661164],
                [66.217385, 37.39379],
                [66.518607, 37.362784],
                [67.075782, 37.356144]
                // .... goes on
            ]
        ]
    }
}]};

L.geoJSON(countries, {
  style: function(feature) {
    return {
      fillColor: "#D3D3D3", // Default color of countries.
      fillOpacity: 1,
      stroke: true,
      color: "grey", // Lines in between countries.
      weight: 2
    };
  }
}).bindPopup(function(layer) {
  return layer.feature.properties.name;
}).addTo(map);
Run Code Online (Sandbox Code Playgroud)

这会产生漂亮的输出,可以在这里看到:http://codepen.io/anon/pen/zZNjBy

但是,我希望根据输入可能为每个国家着色.假设我们打开一个具有潜在输入的对象:

let colorratio = {
    1:"green",
    2:"blue",
    3:"yellow",
    4:"red"
};
Run Code Online (Sandbox Code Playgroud)

然后我收到以下内容:

let colorinput = {
    AFG: "1",
    DNK: "2",
    SWE: "3",
    USA: "1"
};
Run Code Online (Sandbox Code Playgroud)

我们在外行人的条件下想要为阿富汗绿色,丹麦蓝色,瑞典黄色和美国蓝色.其余国家应保持默认颜色值(灰色).

这些缩写与countries变量中的"ID"键匹配.

因此,我的问题是如何处理这个问题; 显然,我需要匹配巨大的GeoJSON文件中的键.但它差不多有13000行.

除此之外,在L.geoJSON我们称之为countries变量的地方,我们返回国家的默认颜色.我在哪里可以访问每个国家/地区的密钥?是否应将此变量移入countries每个国家/地区的变量中,作为随后被覆盖的密钥?

我已经尝试过查看Leaflet文档和示例; 但大多数人认为你在网上检索瓷砖,这在这里是不可能的.它不得不离线工作而不联系CDN或类似的东西 - 这无疑会带来一些挑战.

Iva*_*hez 5

请参阅Leaflet的choropleth教程.它显示了如何style选择in L.GeoJSON可以是一个函数,它根据GeoJSON功能中的属性返回不同的样式.