flutter 如何将MapShapeSource.network()与来自API调用的数据一起使用(从服务器发布/获取)

qpgpyjmq  于 2023-01-27  发布在  Flutter
关注(0)|答案(1)|浏览(179)

我正在使用SfMaps syncfusion map,当我尝试使用MapShapeSource.asset()属性从本地assets文件夹加载geojson数据时,一切都很正常。但当我想使用http包flutter加载由于API调用(GET / POST)而导致的geojson数据时,我遇到了问题。

// Function to load data json from API
Future<void> loadGeojsonDataFromAPI() async {
    setState(() => loading = true);
    try {
      final response = await http.post(
          Uri.parse("some url"),
          headers: {
            'Content-Type': 'application/json; charset=UTF-8',
          },
          body: body);
      if (response.statusCode >= 400) {
        throw Exception('statusCode=${response.statusCode}');
      }
      setState(() {
        loading = false;
        data = jsonDecode(response.body);
      });
    } catch (e) {
      setState(() => loading = false);
      debugPrint("Error load data: $e");
      return;
    }
  }

// Loadjson data from API in Map Shape Source.network() but not sure how to do it
dataSource = MapShapeSource.network(
    'url',
     shapeDataField: 'name',
  );

我相信这个问题可以通过MapShapeSource.network()来解决,但是我仍然不知道如何使用它。
任何形式的帮助都非常感谢

nue99wik

nue99wik1#

您可以使用Map小部件中提供的www.example.com()构造函数从Web/网络加载区域形状JSON数据。我们共享了以下用户指南文档和示例供您参考。MapShapeSource.network() constructor available in the maps widget. We have shared the user guide documentation and sample below for your reference.
通用电气公司,www.example.comhttps://help.syncfusion.com/flutter/maps/getting-started#from-network
代码片段:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_maps/maps.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Syncfusion Flutter Maps',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Syncfusion Flutter Maps'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late MapShapeSource _dataSource;
  late List<IndiaMap> _mapDetails;
  Future<bool> _fetchNetworkJsonDetails() async {
    if (_mapDetails.isNotEmpty) {
      return true;
    }

    final http.Response response = await http
        .get(Uri.tryParse('https://api.npoint.io/b127f79b6e9c883d0aba')!);
    if (response.statusCode == 200) {
      Map<String, dynamic> responseJson = json.decode(response.body);
      List<dynamic> countriesCoordinates = responseJson['features'];

      for (int i = 0; i < countriesCoordinates.length; i++) {
        Map<String, dynamic> data = countriesCoordinates[i]['properties'];
        IndiaMap mapDetail = IndiaMap.fromJsonMap(data);
        _mapDetails.add(mapDetail);
      }

      _dataSource = MapShapeSource.network(
        'https://api.npoint.io/b127f79b6e9c883d0aba',
        shapeDataField: 'name',
        dataCount: _mapDetails.length,
        primaryValueMapper: (index) => _mapDetails[index].state,
      );
      return true;
    } else {
      throw Exception('Failed to load JSON');
    }
  }

  @override
  void initState() {
    _mapDetails = [];
    super.initState();
  }

  @override
  void dispose() {
    _mapDetails.clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: FutureBuilder(
          future: _fetchNetworkJsonDetails(),
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            if (snapshot.hasData) {
              return Padding(
                padding: const EdgeInsets.all(15),
                child: SfMaps(
                  layers: [
                    MapShapeLayer(
                      source: _dataSource,
                      color: const Color.fromRGBO(15, 59, 177, 0.5),
                      strokeColor: Colors.white,
                      strokeWidth: 0.5,
                    ),
                  ],
                ),
              );
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          }),
    );
  }
}

class IndiaMap {
  late String state;
  late String country;

  IndiaMap(this.state, this.country);

  IndiaMap.fromJsonMap(Map data) {
    state = data['name'];
    country = data['admin'];
  }
}

相关问题