颤振地图,setState不更新标记和多边形

时间:2020-01-28 09:12:38

标签: google-maps flutter dart

在初始化地图时直接给出标记和多边形似乎有效,但是在调用setState方法时不添加多边形和标记。

我不知道我似乎错过了什么,

以下是我到目前为止尝试过的。

有人可以帮我解决一下地图未更新的问题。

  import 'dart:async';
  import 'package:flutter/material.dart';
  import 'package:google_maps_flutter/google_maps_flutter.dart';
  import 'package:location/location.dart';

  class HomeWidget extends StatefulWidget {
  @override
    State<StatefulWidget> createState() => _MyHome();
  }

  class _MyHome extends State<HomeWidget> {
  Completer<GoogleMapController> _controller = Completer();

  double _latitude;
  double _longitude;

  CameraPosition _kGooglePlex = CameraPosition(
  target: LatLng(13.092191, 80.246994), zoom: 19.151926040649414);

  @override
  void initState() {
   this._getLocation().then((value) {
   this._latitude = value.latitude;
   this._longitude = value.longitude;
   _kGooglePlex = CameraPosition(
    target: LatLng(_latitude, _longitude),
    zoom: 14.4746,
   );
   });
   super.initState();
  }

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

  Map<String, double> userLocation;
  LocationData currentLocation;

  var location = new Location();
  Set<Marker> _markers = Set();
  Set<Polygon> _polygons = Set();
  GoogleMap map;

  CameraPosition _kLake =
  CameraPosition(target: LatLng(13.092191, 80.246994), tilt: 0, zoom: 14);
  @override
  Widget build(BuildContext context) {
   map = GoogleMap(
   mapType: MapType.hybrid,
   polygons: _polygons,
   markers: _markers,
   initialCameraPosition: _kGooglePlex,
   onMapCreated: (GoogleMapController controller) {
     _controller.complete(controller);
     addMarker(LatLng(_latitude, _longitude));
   },
   onTap: _addPolygon,
   );
   return new Scaffold(
   body: map,
  );
  }

  List<LatLng> polypoints = List();
  _addPolygon(LatLng points) {
    assert(points != null);
    polypoints.add(points);
    if (polypoints.length > 4) {
      print("called polygon");
      print(polypoints);
    setState(() {
       _polygons.add(Polygon(
        polygonId: PolygonId('test'),
        points: polypoints,
        strokeColor: Colors.blue));
    });
    polypoints.clear();
   }
  }

 void addMarker(LatLng mLatLng) {
  setState(() {
   _markers.add(Marker(
      // This marker id can be anything that uniquely identifies each marker.
      markerId: MarkerId('title'),
      position: mLatLng,
      infoWindow: InfoWindow(
        title: 'someTile',
        snippet: 'some desc',
      ),
      icon: BitmapDescriptor.defaultMarker));
   });
  }


 Future<LocationData> _getLocation() async {
  try {
   currentLocation = await location.getLocation();
  } catch (e) {
  if (e.code == 'PERMISSION_DENIED') {
    print('Permission denied');
  }
}
return currentLocation;
}
}

1 个答案:

答案 0 :(得分:1)

经过这么多时间,我似乎已经找到了解决自己问题的方法

问题似乎出在 polypoints.clear();

在多边形在UI中呈现之前清除了多点,所以引发了异常,我没有注意到。