【问题标题】:Building a list of objects out of another list of lists parsed from a JSON file从从 JSON 文件解析的另一个列表列表中构建对象列表
【发布时间】:2019-06-16 09:55:15
【问题描述】:

我正在尝试构建一个显示带有路线的 Open Street Map 的页面。我已经设置了 OSM,并且应该通过 LatLng 对象列表添加路线/折线(由两个双精度组成的对象,标记由一条线连接的点的纬度和经度)。我想要做的是获取用户的位置,然后通过使用 Graphhopper API 获取从用户位置到其他位置的路径的经纬度。

API返回的JSON如下:

{  
   "hints":{  
      "visited_nodes.average":"40.0",
      "visited_nodes.sum":"40"
   },
   "info":{  
      "copyrights":[  
         "GraphHopper",
         "OpenStreetMap contributors"
      ],
      "took":5
   },
   "paths":[  
      {  
         "distance":689.229,
         "weight":408.670174,
         "time":496240,
         "transfers":0,
         "points_encoded":false,
         "bbox":[  
            15.23345,
            44.103858,
            15.238698,
            44.105704
         ],
         "points":{  
            "type":"LineString",
            "coordinates":[  
               [  
                  15.238079,
                  44.103858
               ],
               [  
                  15.238369,
                  44.104135
               ],
               [  
                  15.238698,
                  44.104337
               ],
               [  
                  15.238349,
                  44.104658
               ],
               [  
                  15.238155,
                  44.104889
               ],
               [  
                  15.237904,
                  44.105114
               ],
               [  
                  15.237713,
                  44.105236
               ],
               [  
                  15.237051,
                  44.105388
               ],
               [  
                  15.236858,
                  44.105457
               ],
               [  
                  15.236894,
                  44.105388
               ],
               [  
                  15.236866,
                  44.105314
               ],
               [  
                  15.236739,
                  44.105209
               ],
               [  
                  15.235663,
                  44.104713
               ],
               [  
                  15.234928,
                  44.105129
               ],
               [  
                  15.234886,
                  44.105037
               ],
               [  
                  15.234913,
                  44.10476
               ],
               [  
                  15.234786,
                  44.10476
               ],
               [  
                  15.234449,
                  44.105039
               ],
               [  
                  15.23355,
                  44.105704
               ],
               [  
                  15.23345,
                  44.105639
               ]
            ]
         },
         "legs":[  

         ],
         "details":{  

         },
         "ascend":2.619999408721924,
         "descend":3.4739990234375,
         "snapped_waypoints":{  
            "type":"LineString",
            "coordinates":[  
               [  
                  15.238079,
                  44.103858
               ],
               [  
                  15.23345,
                  44.105639
               ]
            ]
         }
      }
   ]
}

基本上,我需要从这个 JSON 中创建一个 LatLng 对象列表(例如:[LatLng(15.236866, 44.105314), LatLng(15.23355, 44.105704)]),但遗憾的是,我不知道该怎么做。任何帮助、建议或指导将不胜感激。

我曾尝试通过网络搜索并一起编写一些代码,但恐怕它并没有太大帮助。

Future<Points> _fetchCoordinates() async {
  final response = await http.get(
    'https://graphhopper.com/api/1/route?point=44.1035042,15.2385878&point=44.105091,15.2318734&vehicle=foot&locale=hr&key=<API_KEY>&points_encoded=false&instructions=false',
  );

  if (response.statusCode == 200) {
    return Points.fromJson(json.decode(response.body));
  } else {
    throw Exception('Error');
  }
}

class Points {
  List<List<double>> coordinates;

  Points({this.coordinates});

  factory Points.fromJson(Map<String, dynamic> json) => Points(
      coordinates: List<List<double>>.from(json["paths"]["points"]
              ["coordinates"]
          .map((x) => List<double>.from(x.map((x) => x.toDouble())))));

  Map<String, dynamic> toJson() => {
        "coordinates": List<dynamic>.from(
            coordinates.map((x) => List<dynamic>.from(x.map((x) => x))))
      };
}

class Routing extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Points>(
      future: _fetchCoordinates(),
      builder: (context, snapshot) {
        final List coordinates =
            snapshot.hasData ? snapshot.data.coordinates : <LatLng>[];
        if (snapshot.hasData) {
          return MyCustomMap(
            lat: 44.1035042,
            lng: 15.2385878,
            points: <List of LatLng objects, for example: [LatLng(41.234, 
              43.465)]>,
          );
        } else if (snapshot.hasError) {
          return [...]
        } else
          return [...]
      },
    );
  }
}

我的代码似乎有一些错误;返回的语句位于“else if (snapshot.hasError)”子句中。

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    像这样定义一个LatLng 类:

    class LatLng {
      double lat;
      double lng;
    
      LatLng(this.lat, this.lng);
    }
    

    然后你可以像这样解码 json:

      Map<String, dynamic> decoded = json.decode(j);
      List<dynamic> co1  = decoded['paths'][0]['points']['coordinates'];
      List<LatLng> coords = co1.map((pair) => LatLng(pair[0], pair[1])).toList();
    

    你仍然可以有一个 Points 类来包装 List&lt;LatLng&gt;...

    【讨论】:

    • 完美运行,非常感谢!我真的很感激。
    猜你喜欢
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    相关资源
    最近更新 更多