如何在传单上加载 json 文件并设置其样式

How to load json file on leaflet and style it?

本文关键字:文件 设置 样式 json 加载      更新时间:2023-09-26

我想从 json 文件加载 html 代码上的标记,并使用自定义标记加载另一个 json 文件。此文件具有需要指定为 lat 和 lng 的自定义坐标。X 坐标应为 lng,Y 坐标应为纬度。另外,可以使用单独的图标设置每个组的样式??我在处理 json 文件时遇到困难,对此了解不多。示例代码:

{
  "Resources": [
    {
      "Name": "AITokarServer",
      "coords": [
        {
          "x": -1210.0,
          "y": -1770.0
        },
        {
          "x": -1230.0,
          "y": -1810.0
        },

完整代码在这里:http://plnkr.co/edit/q0Jyi528X22KnXcRg2Fs?p=preview

下面是一个示例(希望注释很好),说明如何迭代 json 对象并使用数据创建标记。

// Pretend this is the response from reading a file
  var geoJson = {
    resources: [{
      x: 4288,
      y: -4288,
    }, {
      x: -2320,
      y: -4000,
    }, {
      x: -2320,
      y: -4080,
    }, {
      x: -2400,
      y: -804,
    }, {
      x: -2370,
      y: -1092,
    },
    {
      x: -2470,
      y: -1192,
    },
    {
      x: -2320,
      y: -1122,
    },
    {
      x: -2570,
      y: -1125,
    },
    {
      x: -1350,
      y: -1252,
    },
    {
      x: -1355,
      y: -2125,
    }]
  };

  // Iterate over the resources array of the geoJson object
  // Nested properties of object literals (JSON) can be accessed using dot notation or array syntax
  // eg: dot notation: geoJson.resources
  // eg: array syntax: geoJson["resources"]
  for (var i = 0; i < geoJson.resources.length; i++) {
    // Create a local variable pointing to the
    // coordinate pair object at index i in the resources array of objects
    var currentCoordPair = geoJson.resources[i];
    // Construct a 2 item array containing the x and y values of the current object
    var xyArray = [currentCoordPair.x, currentCoordPair.y];
    // Create a new marker object just like you did before
    var marker = L.marker(xyArray, {icon: icon01});

    // Add the marker to the map
    var addedMarker = marker.addTo(map);

    // Bind your popup
    addedMarker.bindPopup("Base");
  }

还有一个指向 plunker 的链接,它只是你代码的一个分支。http://plnkr.co/edit/O8xqcQlWJM3JiztQXePP

我注意到您正在处理您提供的 Plunker 的其他区域的 LatLng 值。假设您有一个如下所示的对象:

{lat: 152.25151, long: 125.51251} // Just example values

在这种情况下,您将能够以与上面显示的相同方式访问值并将其应用于标记。不同之处在于您将访问currentCoordPair.lat而不是currentCoordPair.x

希望有帮助