# 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.

## First, you need to Learn:

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. ## How to Calculate Distance between Two Coordinates?

``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();

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(
PointLatLng(startLocation.latitude, startLocation.longitude),
PointLatLng(endLocation.latitude, endLocation.longitude),
travelMode: TravelMode.driving,
);

if (result.points.isNotEmpty) {
result.points.forEach((PointLatLng point) {
});
} 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:

## Full Dart/Flutter App Example:

``````import 'package:flutter/material.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.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> {

PolylinePoints polylinePoints = PolylinePoints();

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() {

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

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(
PointLatLng(startLocation.latitude, startLocation.longitude),
PointLatLng(endLocation.latitude, endLocation.longitude),
travelMode: TravelMode.driving,
);

if (result.points.isNotEmpty) {
result.points.forEach((PointLatLng point) {
});
} 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
}

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:[
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(
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.

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