skip to Main Content

I am trying to make a navigation marker on google map, for the user location I am using geolocator pub dev with the listen function however it returned as a Position? and since it have the posibility of null, it can’t be used directly can anyone tell me how to do it ?

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;
  }

3

Answers


  1. Chosen as BEST ANSWER

    I am able to fix this after finding out that the marker didn't got updated because it is in a different state than the main widget, I fix it trough the use of the statebuilder widget, here's the code snip

    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))
                      ],
                    )
                  ],
                )
              ]);
            },
          ),
    

    This way the googlemap have its own state and can be refreshed


  2. Use onDragEnd functionality to drag the marker and release it and make sure u make ‘draggable’ true in the code given below….

    late List dataMarkers = widget.apiDataArray.map((value) {

    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!!',
            );
          }
        }));
    

    }).toList();

    Login or Signup to reply.
  3. Try below,

    • In order to begin drag, you need to long press the marker

    • set ‘draggable’ as true on the marker.

      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',
        ),
      );
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search