Adrah Wynfred
Adrah Wynfred

Reputation: 13

Use current location to draw poly lines to a destination and also to add markers on google maps with markers flutter

I have an application with a google map, the application gets my current location, there are two markers on the map, one point of the marker and the polyline are coordinates passed from a previous screen. I want the starting point of the poly line to be my current location. I also want to use my current location for the first marker. If the polyline and marker will change position as the driver moves, that will be great. But this is not a priority now.

What I have done so far: I am able to get my current location. I am able to draw polyline from a hardcoded coordinates to a destination location(the destination location was provided by a previous screen)

What I want to do: Use my current location as the starting point of my polyline Use my current location to add a marker Update the polyline and the marker when the driver moves.

Here is the code I have so far.


class _MyAppState extends State<RoutePage> {
  late GoogleMapController mapController;
  // Starting point latitude
  // 5.6609595, -0.017155699999989338)
  double _originLatitude = 5.555700;
  // Starting point longitude
  double _originLongitude = -0.196300;
  // Destination latitude
  double? destLatitude;
  // Destination Longitude
  double? destLongitude;
  // Markers to show points on the map
  Map<MarkerId, Marker> markers = {};
  Map<PolylineId, Polyline> polylines = {};
  List<LatLng> polylineCoordinates = [];

  PolylinePoints polylinePoints = PolylinePoints();


  Completer<GoogleMapController> _controller = Completer();

  late Position currentPosition;

  var geoLocator = Geolocator();
  late Geolocator geolocatorTwo;
  var locationOptions = LocationOptions(accuracy: LocationAccuracy.bestForNavigation, distanceFilter: 4);

  Future<LatLng> getCurrentPositiion() async {
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.bestForNavigation);
    currentPosition = position;
    LatLng pos = LatLng(position.latitude, position.longitude);
    mapController.animateCamera((CameraUpdate.newLatLng(pos)));
    print('MyPosition');
    print(currentPosition);
    print(pos.longitude);
    print(pos.latitude);
    print(position.longitude);
    print(position.latitude);
    print(pos);
    return pos;
  }

  static const LatLng _center = const LatLng(45.521563, -122.677433);

  @override
  void initState() {

    /// add origin marker origin marker
    _addMarker(
      LatLng(_originLatitude, _originLongitude),
      "origin",
      BitmapDescriptor.defaultMarker,
    );

    // Add destination marker
    _addMarker(
      LatLng(double.parse(widget.vendors!.latitude), double.parse(widget.vendors!.longitude)),
      "destination",
      BitmapDescriptor.defaultMarkerWithHue(90),
    );
    _getPolyline();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(

        body: GoogleMap(
          padding: EdgeInsets.only(top: 135),
          myLocationButtonEnabled: true,
          myLocationEnabled: true,
          mapType: MapType.normal,
          initialCameraPosition: googlePlex,
          onMapCreated: (GoogleMapController controller){
            _controller.complete(controller);
            mapController=controller;
            getCurrentPositiion();
          },
          polylines: Set<Polyline>.of(polylines.values),
          markers: Set<Marker>.of(markers.values),
        ),
      ),
    );
  }


  // This method will add markers to the map based on the LatLng position
  _addMarker(LatLng position, String id, BitmapDescriptor descriptor) {
    MarkerId markerId = MarkerId(id);
    Marker marker =
    Marker(markerId: markerId, icon: descriptor, position: position);
    markers[markerId] = marker;
  }

  _addPolyLine(List<LatLng> polylineCoordinates) {
    PolylineId id = PolylineId("poly");
    Polyline polyline = Polyline(
      polylineId: id,
      points: polylineCoordinates,
      width: 8,
    );
    polylines[id] = polyline;
    setState(() {});
  }

  void _getPolyline() async {
    List<LatLng> polylineCoordinates = [];

    print("In the Polyline");
    print(currentPosition);
    print(currentPosition.longitude);


    PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
      "APP KEY",
      PointLatLng(_originLatitude, _originLongitude),
      PointLatLng(double.parse(widget.vendors!.latitude), double.parse(widget.vendors!.longitude)),
      travelMode: TravelMode.driving,
    );
    if (result.points.isNotEmpty) {
      result.points.forEach((PointLatLng point) {
        polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      });
    } else {
      print(result.errorMessage);
    }
    _addPolyLine(polylineCoordinates);
  }

  void getLocationUpdates(){
    var homeTabPositionStream = Geolocator.getPositionStream().listen((Position position) {
      currentPosition = position;
      LatLng pos = LatLng(position.latitude, position.longitude);
      mapController.animateCamera(CameraUpdate.newLatLng(pos));
    });
  }
}

What am I missing, why can't I just use currentPosition.latitude and currentPosition.longitude?

Upvotes: 0

Views: 2703

Answers (1)

Nelson Jr.
Nelson Jr.

Reputation: 1207

I tried to modify your code in such a way that it uses your current location as a starting point of the polyline and latlng for the origin marker. Please see that attached screenshot.

My default location is in GooglePlex and I just set the destination latlng (dest_location ) near it. You can set yours somewhere near your location.

Also, this article may help so check it out. :)

const LatLng dest_location = LatLng(37.42796133580664, -122.085749655962);

class _TrackingState extends State<Tracking> {
  GoogleMapController mapController;

  // Markers to show points on the map
  Map<MarkerId, Marker> markers = {};
  Map<PolylineId, Polyline> polylines = {};
  List<LatLng> polylineCoordinates = [];

  PolylinePoints polylinePoints = PolylinePoints();

  Completer<GoogleMapController> _controller = Completer();
  static final CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );

  Position currentPosition;
  var geoLocator = Geolocator();
  var locationOptions = LocationOptions(
      accuracy: LocationAccuracy.bestForNavigation, distanceFilter: 4);

  void getCurrentPosition() async {
    currentPosition = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.bestForNavigation);
  }

  @override
  void initState() {
    super.initState();
    getCurrentPosition();
  }

  @override
  Widget build(BuildContext context) {
    CameraPosition initialCameraPosition = _kGooglePlex;
    if (currentPosition != null) {
      initialCameraPosition = CameraPosition(
          target: LatLng(currentPosition.latitude, currentPosition.longitude),
          zoom: 14.4746);
    }
    return MaterialApp(
      home: Scaffold(
        body: GoogleMap(
          padding: EdgeInsets.only(top: 135),
          myLocationButtonEnabled: true,
          myLocationEnabled: true,
          mapType: MapType.normal,
          initialCameraPosition: initialCameraPosition,
          onMapCreated: (GoogleMapController controller) {
            _controller.complete(controller);
            mapController = controller;
            _getPolyline();
          },
          polylines: Set<Polyline>.of(polylines.values),
          markers: Set<Marker>.of(markers.values),
        ),
      ),
    );
  }

  // This method will add markers to the map based on the LatLng position
  _addMarker(LatLng position, String id, BitmapDescriptor descriptor) {
    MarkerId markerId = MarkerId(id);
    Marker marker =
        Marker(markerId: markerId, icon: descriptor, position: position);
    markers[markerId] = marker;
  }

  _addPolyLine(List<LatLng> polylineCoordinates) {
    PolylineId id = PolylineId("poly");
    Polyline polyline = Polyline(
      polylineId: id,
      points: polylineCoordinates,
      width: 8,
    );
    polylines[id] = polyline;
    setState(() {});
  }

  void _getPolyline() async {
    /// add origin marker origin marker
    _addMarker(
      LatLng(currentPosition.latitude, currentPosition.longitude),
      "origin",
      BitmapDescriptor.defaultMarker,
    );

    // Add destination marker
    _addMarker(
      LatLng(dest_location.latitude, dest_location.longitude),
      "destination",
      BitmapDescriptor.defaultMarkerWithHue(90),
    );

    List<LatLng> polylineCoordinates = [];

    PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
      "API KEY",
      PointLatLng(currentPosition.latitude, currentPosition.longitude),
      PointLatLng(dest_location.latitude, dest_location.longitude),
      travelMode: TravelMode.walking,
    );
    if (result.points.isNotEmpty) {
      result.points.forEach((PointLatLng point) {
        polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      });
    } else {
      print(result.errorMessage);
    }
    _addPolyLine(polylineCoordinates);
  }
}

enter image description here

Upvotes: 1

Related Questions