【问题标题】:How to load json file on leaflet and style it?如何在传单上加载 json 文件并设置样式?
【发布时间】:2016-01-22 16:51:46
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript json maps leaflet


    【解决方案1】:

    这是一个(希望得到很好的评论)示例,说明如何迭代 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

    希望有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-05
      • 2018-06-07
      • 2018-04-21
      • 2015-02-12
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      相关资源
      最近更新 更多