|

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

Flutter is an open-source mobile application development framework that is used to develop high-quality, high-performance and visually appealing applications for iOS and Android platforms. One of the most commonly used features of Flutter is the Google Maps widget, which provides a simple and convenient way to display maps and locate different places on the map. In this tutorial, we will see how to calculate the distance between two locations on the Google Maps in Flutter.

Prerequisites:

  • Basic knowledge of Dart programming language.
  • Flutter and Dart plugins installed in your IDE.
  • Google Maps API Key.

To calculate the distance between two locations, we will use the Haversine formula, which is a popular formula used for calculating the great-circle distance between two points on the surface of a sphere. The Haversine formula is defined as follows:

a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2) c = 2.atan2(√a, √(1−a)) d = R.c

Where R is the earth’s radius (mean radius = 6,371km), lat1 and lat2 are the latitude values of the two locations, and Δlat and Δlong are the differences between the latitude and longitude values of the two locations.

Now, let’s write the code to calculate the distance between two locations in Flutter.

Step 1: Create a new Flutter project.

Step 2: Import the following packages in the pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  google_maps_flutter: ^0.7.0

Step 3: Add the Google Maps API Key to the AndroidManifest.xml file.

<manifest ...
  <application ...
    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR_API_KEY"/>

Step 4: Create a new Dart file and name it “calculate_distance.dart”.

Step 5: In the calculate_distance.dart file, write the following code:

import 'dart:math';

class DistanceCalculator {
  static double distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {
    var earthRadiusKm = 6371;

    var dLat = degreesToRadians(lat2-lat1);
    var dLon = degreesToRadians(lon2-lon1);

    lat1 = degreesToRadians(lat1);
    lat2 = degreesToRadians(lat2);

    var a = sin(dLat/2) * sin(dLat/2) +
        sin(dLon/2) * sin(dLon/2) * cos(lat1) * cos(lat2);
    var c = 2 * atan2(sqrt(a), sqrt(1-a));
    return earthRadiusKm * c;
  }

  static double degreesToRadians(degrees) {
    return degrees * pi / 180;
  }
}

Step 6: Call the distanceInKmBetweenEarthCoordinates method in your main Flutter widget, passing the latitude and longitude values of the two locations as arguments.

import 'package:flutter/material.dart';
import 'calculate_distance.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Distance Calculator',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double lat1 = 37.3352;
  double lon1 = -121.8811;
  double lat2 = 37.4419;
  double lon2 = -122.1430;
  double distance;

  @override
  void initState() {
    super.initState();
    distance = DistanceCalculator.distanceInKmBetweenEarthCoordinates(
        lat1, lon1, lat2, lon2);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Distance Calculator'),
      ),
      body: Center(
        child: Text('The distance between the two locations is $distance km.'),
      ),
    );
  }
}


Step 7: Run the app.

And that’s it! You now have a complete Flutter app that calculates the distance between two locations on the Google Map.

Conclusion:

In this tutorial, we learned how to calculate the distance between two locations on the Google Map in Flutter. The Haversine formula is a convenient and simple way to calculate the distance between two points on a sphere, and with the help of the Dart programming language, we were able to implement this formula in a Flutter app. Whether you’re developing a mapping app or just need to calculate distances between locations, the code in this tutorial will provide a great starting point.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *