【问题标题】:Flutter Google Maps Polyline - The argument type 'LatLng' can't be assigned to the parameter type 'List<LatLng>'Flutter Google Maps Polyline - 参数类型“LatLng”无法分配给参数类型“List<LatLng>”
【发布时间】:2020-03-22 18:02:51
【问题描述】:

我在我的 Flutter 项目中使用 Google 地图。我正在尝试解析资产中的两个 JSON 文件,以便可以在折线和标记中使用它们的纬度和经度。标记工作正常,但现在我正在为折线的Future 构建器添加另一个未来,我收到以下错误:

参数类型LatLng不能赋值给参数类型List&lt;LatLng&gt;

Future _future;

Future _futuree;

Future<String> loadString() async => await rootBundle.loadString('assets/busStops/stops_${widget.selectStation}.json');
List<Marker> allMarkers = [];
GoogleMapController _controller;

@override
void initState() {
  // TODO: implement initState
  super.initState();

  //future 1
  _future = loadString();

  //future 2
  _futuree = loadMyCoord();

}

Future<String> loadMyCoord() async {
  var x = await rootBundle
      .loadString('assets/route/coords_Centurion.json');
  return x;
}

@override
Widget build(BuildContext context) {
  createMarker(context);
  return Scaffold(
    appBar: AppBar(
      title: Text("Bus Routes"),
      centerTitle: true,
      backgroundColor: Color.fromRGBO(59, 62, 64, 1),
      actions: <Widget>[
        FlatButton(
          textColor: Colors.white,
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => busStationList()),
            );
          },
          child: Icon(Icons.add),
        ),
      ],
    ),
    body: Stack(children: [
      Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        child: FutureBuilder(

          // Futures
          future: Future.wait(
            [
              //[0]
              _future,

              //[1]
              _futuree,
            ]
          ),

          builder: (
                  context, 
                  AsyncSnapshot<List<dynamic>> snapshot,
          ) {
            // Check hasData once for all futures.
            if (!snapshot.hasData) {
              return CircularProgressIndicator();
            }

            List<dynamic> parsedJson = jsonDecode(snapshot.data[0]);
            allMarkers = parsedJson.map((element) {
              return Marker(
                  icon: customIcon,
                  markerId: MarkerId(element["Latitude"].toString()),
                  position: LatLng(element['Latitude'] ?? 0.0,
                      element['Longitude'] ?? 0.0));
            }).toList();

            List<dynamic> parseJson = jsonDecode(snapshot.data[1]);
            List<Polyline> allPolylinesByPosition = [];
            parseJson.forEach((element){
              List<dynamic> coords = element["coords"];

              coords.forEach((i) {
                double lat = double.tryParse(i["latitude"]);
                double lng = double.tryParse(i["longitude"]);

                allPolylinesByPosition.add(Polyline(
                  polylineId: PolylineId('lines'),
                  points: points: LatLng(lat ?? 0.0, lng ?? 0.0);
                  visible: true,
                  color: Colors.red

                ));
              }

              );
            });

            return GoogleMap(
              initialCameraPosition: CameraPosition(
                  target: LatLng(-26.1711459, 27.9002758), zoom: 9.0),
              markers: Set.from(allMarkers),
              onMapCreated: mapCreated,
              polylines: Set.from(allPolylinesByPosition),
            );
          },
        ),
      ),
    ]),
  );
}

void mapCreated(controller) {
  setState(() {
    _controller = controller;
  });
}

【问题讨论】:

    标签: json google-maps flutter dart polyline


    【解决方案1】:

    您好,我现在已经完成了以下操作,并提取了数据,但它没有显示在地图上

    List<dynamic> parseJson = jsonDecode(snapshot.data[1]);
    
                 Set<Polyline> allPolylinesByPosition = {};
    
                 parseJson.forEach((element) {
                   List<dynamic> coords = element["coords"];
    
                   coords.forEach((i) {
    
                     List<LatLng> latlng = [
    
                       LatLng( double.tryParse(i["latitude"]) ?? 0.0 ,double.tryParse(i["longitude"]) ?? 0.0)
                  ];
    
                     allPolylinesByPosition.add(Polyline(
                         polylineId: PolylineId((_lastMapPosition.toString())),
                         points:latlng,
                         visible: true,
                         width: 4,
                         color: Colors.red
    
                     ));
                     print(PolylineId);
                   }
    
                   );
                 });
    
    
                 return GoogleMap(
                   initialCameraPosition: CameraPosition(
                       target: LatLng(-26.1711459, 27.9002758), zoom: 2.0),
                   markers: Set.from(allMarkers),
                   onMapCreated: mapCreated,
                   polylines: allPolylinesByPosition,
                 );
               },
             ),
    
    '''
    

    【讨论】:

      【解决方案2】:

      需要注意的一点是,Polylinepoints 参数只接受 LatLng (List&lt;LatLng&gt;) 的列表,而不接受 LatLng

      应该在您的代码中更改此行。尝试添加 LatLng 列表,而不是在 points 参数中传递单个 LatLng 实例。

      points: LatLng(lat ?? 0.0, lng ?? 0.0);
      

      Polyline.dart

      class Polyline {
        const Polyline({
          @required this.polylineId,
          this.consumeTapEvents = false,
          this.color = Colors.black,
          this.endCap = Cap.buttCap,
          this.geodesic = false,
          this.jointType = JointType.mitered,
          this.points = const <LatLng>[],
          this.patterns = const <PatternItem>[],
          this.startCap = Cap.buttCap,
          this.visible = true,
          this.width = 10,
          this.zIndex = 0,
          this.onTap,
        });
      

      【讨论】:

      • 嗨 Joshua,我已经完成了以下操作,但现在我没有收到任何错误,但折线不显示
      • 嗨丹尼尔,我相信这可能是一个不同的问题。但是您能否查看此链接以了解Polyline 的实现? stackoverflow.com/questions/53171531/…
      • 嗨丹尼尔,这能回答你的问题吗?
      猜你喜欢
      • 1970-01-01
      • 2022-10-07
      • 2022-08-13
      • 2020-03-22
      • 2021-06-04
      • 2021-06-26
      • 2021-11-10
      • 2023-01-13
      • 1970-01-01
      相关资源
      最近更新 更多