【发布时间】: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)”子句中。
【问题讨论】: