5

我有一个离线传单地图,其中国家是从一个带有坐标的巨大 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>

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);

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

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

let colorratio = {
    1:"green",
    2:"blue",
    3:"yellow",
    4:"red"
};

然后我收到以下信息:

let colorinput = {
    AFG: "1",
    DNK: "2",
    SWE: "3",
    USA: "1"
};

通俗地说,阿富汗绿色、丹麦蓝色、瑞典黄色和美国蓝色。其余国家/地区应保持默认颜色值(灰色)。

这些缩写与countries变量中的“ID”键相匹配。

因此,我的问题是如何解决这个问题;显然,我需要匹配巨大的 GeoJSON 文件中的键。但它几乎有13000行长。

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

我试过查看 Leaflet 文档和示例;但大多数人假设您在线检索瓷砖,这在此处是不可能的。它必须在不联系 CDN 或类似的情况下脱机工作——这会带来一些挑战,不用说。

4

1 回答 1

9

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

于 2017-03-09T11:40:01.393 回答