flutter 谁能告诉我如何添加地理定位器收听位置到谷歌标记?

nmpmafwu  于 2023-02-16  发布在  Flutter
关注(0)|答案(3)|浏览(136)

我试图在谷歌Map上做一个导航标记,对于用户位置,我使用geolocator pub dev的监听功能,但它返回为一个位置?因为它有空的可能性,它不能直接使用,有人能告诉我如何做吗?

Position? listenToLocation()
  {
    Position? userposition;
    final LocationSettings _locationSettings = LocationSettings(accuracy: LocationAccuracy.high,distanceFilter: 100);
    userStreamlocation = Geolocator.getPositionStream(locationSettings: _locationSettings).listen(
    (userposition) {
        print(userposition == null ? 'Unknown' : '${userposition.latitude.toString()}, ${userposition.longitude.toString()}');
        setState(){
          streamResult=userposition;
        }
    });
    return userposition;
  }
pcww981p

pcww981p1#

使用onDragEnd功能拖动并释放标记,并确保在下面给出的代码中使“draggable”为true u...
最新列表数据标记=widget.apiDataArray.map((值){

List<double> coords = value['']
    .split(',')
    .map<double>((c) => double.parse(c))
    .toList();
return Marker(
    icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue),
    onTap: () {
      AlertDialog(
        title: Text(value['']),
      );
    },
    infoWindow: InfoWindow(title: value['RECORD_NO']),
    markerId: MarkerId(value['']),
    position: LatLng(coords[0], coords[1]),
    draggable: true,
    onDragEnd: ((newPosition) async {
      try {
        final result = await InternetAddress.lookup('example.com');
        if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
          print('connected');
          setState(() {
            // coords = [newPosition.latitude,newPosition.longitude];
            print(newPosition.latitude);
            print(newPosition.longitude);
            CoolAlert.show(
                title: 'Click OK To Confirm',
                context: context,
                type: CoolAlertType.confirm,
                onConfirmBtnTap: () {
                  uploadLocation(newPosition, value);
                  Navigator.pop(context);
                });
            //uploadLocation(newPosition,value);
          });
        }
      } on SocketException catch (_) {
        print('not connected');
        return await QuickAlert.show(
          context: context,
          type: QuickAlertType.error,
          title: 'Oops...',
          text: 'Please Check Your Internet!!',
        );
      }
    }));

}).到列表();

wgxvkvu9

wgxvkvu92#

在发现标记未更新(因为它处于与主小部件不同的状态)后,我能够修复此问题,我通过使用状态构建器小部件修复了此问题,以下是代码片段

StatefulBuilder(
        builder: (context, setMapState) {
          setMapState(
            () {},
          );

          void _whenMapCreated(GoogleMapController controller) async {
            //debugPrint('>>>>>>>>> onMapCreated');
            mapController = controller;
            _Navmarkers.clear();
            _navPolylines.clear();
            var direction =
                await LocationService().getDirectionNoWP(userOrigin, userGoal);
            _setPolylines(direction['polyline_decoded']);
            setMapState(
              () {},
            );
          }

          return Column(children: [
            Expanded(
                child: GoogleMap(
              mapType: MapType.normal,
              initialCameraPosition:
                  CameraPosition(target: _kGooglePlex, zoom: 11),
              markers: _Navmarkers,
              polylines: _navPolylines,
              onMapCreated: _whenMapCreated,
            )),
            Row(
              children: [
                ButtonBar(
                  children: [
                    IconButton(
                        onPressed: () {
                          Position? userposition;

                          const LocationSettings _locationSettings =
                              LocationSettings(
                            accuracy: LocationAccuracy.high,
                            distanceFilter: 100,
                          );
                          userStreamlocation = Geolocator.getPositionStream(
                                  locationSettings: _locationSettings)
                              .listen((userposition) {
                            _Navmarkers.clear();
                            _Navmarkers.add(Marker(
                                markerId: MarkerId('User'),
                                position: LatLng(userposition.latitude,
                                    userposition.longitude),
                                icon: BitmapDescriptor.defaultMarkerWithHue(
                                    BitmapDescriptor.hueRose)));
                            setMapState(() {                            
                            });                            
                          });
                        },
                        icon: Icon(Icons.navigation)),
                    IconButton(
                        onPressed: () {
                          setMapState(
                            () {                             
                            },
                          );
                        },
                        icon: Icon(Icons.refresh)),
                    IconButton(
                        onPressed: () {
                          dispose();
                        },
                        icon: Icon(Icons.stop))
                  ],
                )
              ],
            )
          ]);
        },
      ),

这样,谷歌Map就有了自己的状态,并且可以刷新

qeeaahzv

qeeaahzv3#

试试下面,

  • 要开始拖动,您需要长按标记
  • 在标记上将“draggable”设置为true。
var marker = Marker(
  draggable: true,
  onDrag: ((position) {}), // will fire while drag
  onDragStart: ((position) {}), // will fire at the beginning ( only once )
  onDragEnd: ((position) { // will fire at the end of dragging ( only once )
  }),
  infoWindow: const InfoWindow(
  title: 'Hello',
  snippet: 'You are here',
  ),
);

相关问题