如何使用MapShapeSource.network()加载API请求返回的GeoJSON数据
解决Syncfusion SfMaps加载API返回的GeoJSON数据问题
两种场景的解决方案
1. API支持GET请求:直接用MapShapeSource.network
如果你的API可以通过GET请求获取GeoJSON,MapShapeSource.network能直接帮你完成请求和加载,无需手动写http请求。它内部会发起GET请求,只需传入API地址、必要请求头和shape匹配字段:
dataSource = MapShapeSource.network( 'https://your-api-url.com/geojson', shapeDataField: 'name', // API需要请求头时添加,比如Token headers: { 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': 'Bearer your-token', }, );
2. API仅支持POST请求:先获取数据再用MapShapeSource.data加载
你的场景是用POST请求获取GeoJSON,MapShapeSource.network不支持POST方法,所以需要先通过http包拿到数据,再用MapShapeSource.data加载解析后的JSON对象。修改代码如下:
// 定义状态变量 late Map<String, dynamic> geojsonData; bool loading = true; String? errorMessage; // 调整后的POST请求函数 Future<void> loadGeojsonDataFromAPI() async { setState(() { loading = true; errorMessage = null; }); try { final response = await http.post( Uri.parse("your-api-url"), headers: { 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(yourRequestBody), // 确保body是JSON字符串格式 ); if (response.statusCode >= 400) { throw Exception('请求失败,状态码:${response.statusCode}'); } final parsedData = jsonDecode(response.body); setState(() { loading = false; geojsonData = parsedData; }); } catch (e) { setState(() { loading = false; errorMessage = e.toString(); }); debugPrint("加载数据错误: $e"); } } // 构建地图的build方法 @override Widget build(BuildContext context) { return Scaffold( body: loading ? const Center(child: CircularProgressIndicator()) : errorMessage != null ? Center(child: Text('加载失败: $errorMessage')) : SfMaps( layers: [ MapShapeLayer( source: MapShapeSource.data( data: geojsonData, shapeDataField: 'name', // 如需绑定业务数据,可设置以下参数 // dataCount: yourBusinessData.length, // shapeDataMapper: (int index) => yourBusinessData[index]['name'], ), ), ], ), ); }
关键注意事项
- 确保API返回的是标准GeoJSON格式,否则SfMaps无法正确解析渲染
- POST请求的body如果是JSON格式,必须用
jsonEncode()将对象转为字符串,避免请求格式错误 - 加载过程中处理好状态(加载中、失败),提升用户体验
内容的提问来源于stack exchange,提问作者Afdul Rohmat
相关产品推荐
相关产品推荐

