Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter draw route line between 2 markers

Tags:

flutter

dart

I am showing 2 markers on the map by giving long and lat there 2 values basically start and end. I need to know how can I draw a route line between these 2 points. I have APIs enable mean I have paid APIs. I need to just draw a route between these 2 points

Here is my code

import 'package:flutter/material.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class TripRouteScreen extends StatefulWidget {
  final data;

  const TripRouteScreen({Key key, @required this.data}) : super(key: key);
  @override
  _TripRouteScreenState createState() => _TripRouteScreenState();
}

class _TripRouteScreenState extends State<TripRouteScreen> {
  var start_currentPostion;
  var end_currentPostion;
  BitmapDescriptor pinLocationIcon;
  PolylinePoints polylinePoints = PolylinePoints();
  Map<PolylineId, Polyline> polylines = {};
  List<LatLng> polylineCoordinates = [];

  Map<MarkerId, Marker> setmarkers = {};
  List listMarkerIds = List(); // For store data of your markers

  @override
  void initState() {
    super.initState();
    setCustomMapPin();
    working();
  }

  void setCustomMapPin() async {
    pinLocationIcon = await BitmapDescriptor.fromAssetImage(
        ImageConfiguration(devicePixelRatio: 2.5), 'images/pin.png');
  }

  addPolyLine() {
    PolylineId id = PolylineId("poly");
    Polyline polyline = Polyline(
        polylineId: id, color: Colors.red, points: polylineCoordinates);
    polylines[id] = polyline;
    setState(() {});
  }

  working() async {
    double start_latitude = widget.data['start']['lat'].toDouble();
    double start_longitude = widget.data['start']['lon'].toDouble();

    double end_latitude = widget.data['end']['lat'].toDouble();
    double end_longitude = widget.data['end']['lon'].toDouble();

    start_currentPostion = LatLng(start_latitude, start_longitude);
    end_currentPostion = LatLng(end_latitude, end_longitude);

    await polylinePoints
        .getRouteBetweenCoordinates(
      'AIzaSyBNM_nCEEzp-MyApi',
      PointLatLng(start_latitude, start_longitude), //Starting LATLANG
      PointLatLng(end_latitude, end_longitude), //End LATLANG
      travelMode: TravelMode.driving,
    )
        .then((value) {
      value.points.forEach((PointLatLng point) {
        polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      });
    }).then((value) {
      addPolyLine();
    });

    setState(() {
      MarkerId markerId1 = MarkerId("1");
      MarkerId markerId2 = MarkerId("2");

      listMarkerIds.add(markerId1);
      listMarkerIds.add(markerId2);

      Marker marker1 = Marker(
        markerId: markerId1,
        position: LatLng(start_latitude, start_longitude),
        // ignore: deprecated_member_use
        icon: BitmapDescriptor.fromAsset("images/pin.png"),
      );

      Marker marker2 = Marker(
        markerId: markerId2,
        position: LatLng(end_latitude, end_longitude),
        // ignore: deprecated_member_use
        icon: BitmapDescriptor.fromAsset(
            "images/pin.png"), // you can change the color of marker
      );

      setmarkers[markerId1] =
          marker1; // I Just added here markers on the basis of marker id
      setmarkers[markerId2] = marker2;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          leading: GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Icon(Icons.arrow_back)),
          centerTitle: true,
          flexibleSpace: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('images/nav.jpg'),
                fit: BoxFit.cover,
              ),
            ),
          ),
          backgroundColor: Colors.transparent,
          title: Text(
            'Route Location',
            style: TextStyle(fontFamily: 'UbuntuBold'),
          ),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 15),
              child: Icon(
                Icons.notifications_none,
                size: 33,
              ),
            )
          ]),
      body: GoogleMap(
        mapType: MapType.normal,
        polylines: Set<Polyline>.of(polylines.values),

        initialCameraPosition: CameraPosition(
          target: start_currentPostion,
          zoom: 12,
        ),
        markers: Set.of(setmarkers.values), // YOUR MARKS IN MAP
      ),
    );
  }
}

Something simple like this

enter image description here

I have added code as in the answer but lines are not showing. I am using the same API which I am using for my Map. geo.API_KEY is it a different key for polylines? or I am doing something wrong in the code? because it is not showing any error.

Also, one more thing to add when I print(value.points); it is showing empty array []'

like image 400
Umaiz Khan Avatar asked Jan 29 '21 16:01

Umaiz Khan


People also ask

How do you draw on Google Maps in flutter?

A Stack widget with GoogleMap and CustomPaint will let you draw anything you want on top of the map. You have to convert map coordinates to device screen coordinates. Google has a cookbook on how to do that except it does not work in Flutter since the map plugin does not expose the complete API.


Video Answer


1 Answers

Assuming you have enabled the necessary APIs, drawing the Path is very simple,

For this you need 2 Plugins. (I think you already have these.)

  1. google_maps_flutter (LINK)
  2. flutter_polyline_points (LINK)

import those 2

import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';

Declare these inside your widget. the first one will hold the Poly-points from the Maps API. the second one will hold the polylines set we will be making. third is the one that will keep the decoded polylineCorrdinates.

PolylinePoints polylinePoints = PolylinePoints();
Map<PolylineId, Polyline> polylines = {};
List<LatLng> polylineCoordinates = [];

following function makes the polylines from polyoints.

 addPolyLine() {
    PolylineId id = PolylineId("poly");
    Polyline polyline = Polyline(
        polylineId: id,
        color: Colors.red,
        points: polylineCoordinates
    );
    polylines[id] = polyline;
    setState((){});
 }

now let's get the polypoints from Maps API. you can also set the TravelMode to driving, walking etc.... this will be the function you need to call to create the poly lines on your map. change the 'YOUR API KEY' and the LAT LANGS to your liking.

 void makeLines() async {
     await polylinePoints
          .getRouteBetweenCoordinates(
             'YOUR API KEY',
              PointLatLng(6.2514, 80.7642), //Starting LATLANG
              PointLatLng(6.9271, 79.8612), //End LATLANG
              travelMode: TravelMode.driving,
    ).then((value) {
        value.points.forEach((PointLatLng point) {
           polylineCoordinates.add(LatLng(point.latitude, point.longitude));
       });
   }).then((value) {
      addPolyLine();
   });
 }

finally in the google map widget add your polyLines!

GoogleMap(
    ...
    polylines: Set<Polyline>.of(polylines.values),
    ....),
like image 184
Srilal Sachintha Avatar answered Nov 09 '22 18:11

Srilal Sachintha