How to Calculate Distance between Two Locations on Google Map in Flutter

In this example, we are going to show you how to calculate the distance of the direction routes path between two locations. First, we will fetch polyline coordinates from Google Map API. It contains the list of longitude and latitude, after that we will calculate the distance in KM.

In this example, we will:

  1. Integrate Google Map in Flutter
  2. Fetch Polyline coordinates between two locations from Google API
  3. Put a marker at both starting and ending locations.
  4. Draw polyline direction routes in Google Map
  5. Calculate distance

Before, going to this tutorial, be sure you have fetched and drawn a polyline routes path on google map.

After fetching the list of polylines from Google Map API, we will use the following function to calculate the distance between two coordinates. Remember, a polyline path contains the list of coordinates, therefore we will loop through the polylines and calculate the distance between every two coordinates, and finally add all the distance to get the total distance.

import 'dart:math';
double calculateDistance(lat1, lon1, lat2, lon2){
  var p = 0.017453292519943295;
  var a = 0.5 - cos((lat2 - lat1) * p)/2 + 
        cos(lat1 * p) * cos(lat2 * p) * 
        (1 - cos((lon2 - lon1) * p))/2;
  return 12742 * asin(sqrt(a));
}

//it will return distance in KM

This function calculates the distance between two coordinates of longitude and latitude and returns distance in Kilometer (KM).

Now, calculate the distance after fetching the coordinates of the polyline from Google Map API:

PolylinePoints polylinePoints = PolylinePoints();

String googleAPiKey = "GOOGLE API KEY";

Set<Marker> markers = Set(); //markers for google map
Map<PolylineId, Polyline> polylines = {}; //polylines to show direction

LatLng startLocation = LatLng(27.6683619, 85.3101895);  
LatLng endLocation = LatLng(27.6875436, 85.2751138); 

double distance = 0.0;
List<LatLng> polylineCoordinates = [];

PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
    googleAPiKey,
    PointLatLng(startLocation.latitude, startLocation.longitude),
    PointLatLng(endLocation.latitude, endLocation.longitude),
    travelMode: TravelMode.driving,
);

if (result.points.isNotEmpty) {
      result.points.forEach((PointLatLng point) {
          polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      });
} else {
    print(result.errorMessage);
}

//polulineCoordinates is the List of longitute and latidtude.
double totalDistance = 0;
for(var i = 0; i < polylineCoordinates.length-1; i++){
      totalDistance += calculateDistance(
          polylineCoordinates[i].latitude, 
          polylineCoordinates[i].longitude, 
          polylineCoordinates[i+1].latitude, 
          polylineCoordinates[i+1].longitude);
}
print(totalDistance);

setState(() {
    distance = totalDistance;
});

The final code is given below:

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

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  GoogleMapController? mapController; //contrller for Google map
  PolylinePoints polylinePoints = PolylinePoints();

  String googleAPiKey = "AIzaSyDma7ThRPGokuU_cJ2Q_qFvowIpK35RAPs";
  
  Set<Marker> markers = Set(); //markers for google map
  Map<PolylineId, Polyline> polylines = {}; //polylines to show direction

  LatLng startLocation = LatLng(27.6683619, 85.3101895);  
  LatLng endLocation = LatLng(27.6875436, 85.2751138); 

  double distance = 0.0;
                            

  @override
  void initState() {

     markers.add(Marker( //add start location marker
        markerId: MarkerId(startLocation.toString()),
        position: startLocation, //position of marker
        infoWindow: InfoWindow( //popup info 
          title: 'Starting Point ',
          snippet: 'Start Marker',
        ),
        icon: BitmapDescriptor.defaultMarker, //Icon for Marker
      ));

      markers.add(Marker( //add distination location marker
        markerId: MarkerId(endLocation.toString()),
        position: endLocation, //position of marker
        infoWindow: InfoWindow( //popup info 
          title: 'Destination Point ',
          snippet: 'Destination Marker',
        ),
        icon: BitmapDescriptor.defaultMarker, //Icon for Marker
      ));
      
      getDirections(); //fetch direction polylines from Google API
      
    super.initState();
  }

  getDirections() async {
      List<LatLng> polylineCoordinates = [];
     
      PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
          googleAPiKey,
          PointLatLng(startLocation.latitude, startLocation.longitude),
          PointLatLng(endLocation.latitude, endLocation.longitude),
          travelMode: TravelMode.driving,
      );

      if (result.points.isNotEmpty) {
            result.points.forEach((PointLatLng point) {
                polylineCoordinates.add(LatLng(point.latitude, point.longitude));
            });
      } else {
         print(result.errorMessage);
      }

      //polulineCoordinates is the List of longitute and latidtude.
      double totalDistance = 0;
      for(var i = 0; i < polylineCoordinates.length-1; i++){
           totalDistance += calculateDistance(
                polylineCoordinates[i].latitude, 
                polylineCoordinates[i].longitude, 
                polylineCoordinates[i+1].latitude, 
                polylineCoordinates[i+1].longitude);
      }
      print(totalDistance);

      setState(() {
         distance = totalDistance;
      });

      //add to the list of poly line coordinates
      addPolyLine(polylineCoordinates);
  }

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

  double calculateDistance(lat1, lon1, lat2, lon2){
    var p = 0.017453292519943295;
    var a = 0.5 - cos((lat2 - lat1) * p)/2 + 
          cos(lat1 * p) * cos(lat2 * p) * 
          (1 - cos((lon2 - lon1) * p))/2;
    return 12742 * asin(sqrt(a));
  }
  
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
          appBar: AppBar( 
             title: Text("Calculate Distance in Google Map"),
             backgroundColor: Colors.deepPurpleAccent,
          ),
          body: Stack(
            children:[
                GoogleMap( //Map widget from google_maps_flutter package
                        zoomGesturesEnabled: true, //enable Zoom in, out on map
                        initialCameraPosition: CameraPosition( //innital position in map
                          target: startLocation, //initial position
                          zoom: 14.0, //initial zoom level
                        ),
                        markers: markers, //markers to show on map
                        polylines: Set<Polyline>.of(polylines.values), //polylines
                        mapType: MapType.normal, //map type
                        onMapCreated: (controller) { //method called when map is created
                          setState(() {
                            mapController = controller; 
                          });
                        },
                  ),

                  Positioned(
                    bottom: 200,
                    left: 50,
                    child: Container( 
                     child: Card( 
                         child: Container(
                            padding: EdgeInsets.all(20),
                            child: Text("Total Distance: " + distance.toStringAsFixed(2) + " KM",
                                         style: TextStyle(fontSize: 20, fontWeight:FontWeight.bold))
                         ),
                     )
                    )
                 )
            ]
          )
       );
  }
}

In this example, we have integrated Google Map, fetched polyline coordinates of direction routes path, drawn it on Google Map, and also calculated distance between starting and ending longitude and latitudes of points.

In this way, you can calculate the distance between two locations on Google Maps in the Flutter app.

1 Commet on this Article

Nisha Ranjan Sah

Thanks for wonderful documentation.
I need to update the polyline when i choose alternative route.

6 months ago


Please Wait...