Calculating Distance Between Two Locations on Google Map in Flutter: A Step-by-Step Guide
Introduction
In today’s mobile app development landscape, GPS navigation and location-based services have become an integral part of many applications. Users expect seamless navigation experiences, accurate location identification, and easy distance calculations. As a Flutter developer, you can utilize Google Maps to provide such features in your app. In this article, we will delve into the process of calculating the distance between two locations on Google Map in Flutter.
Prerequisites
Before we begin, ensure that you have the following set up in your Flutter project:
1. Install the `googlemapsflutter` package using the following command in your terminal: `flutter pub add googlemapsflutter`.
2. Get an API key from the Google Cloud Console and add it to your app’s `googlemapsapi_key` setting.
Required Libraries and Packages
To calculate the distance between two locations, we will use the `googlemapsflutter` package and Geolocator package for location services. We will also use the Plugin Geolocator package for location based services.
“`json
dependencies:
flutter:
sdk: flutter
googlemapsflutter: ^2.3.1
geolocator: ^9.0.1
flutterpolylinepoints: ^1.0.1
“`
Step 1: Setting up Google Maps
First, import the necessary libraries and create a `GoogleMap` widget to display the map:
“`dart
import ‘package:flutter/material.dart’;
import ‘package:googlemapsflutter/google_map.dart’;
class GoogleMapExample extends StatefulWidget {
@override
GoogleMapExampleState createState() => GoogleMapExampleState();
}
class _GoogleMapExampleState extends State
late GoogleMapController _mapController;
final LatLng _initialPosition = const LatLng(37.7749, -122.4194);
List
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(‘Google Map Example’),
),
body: GoogleMap(
onMapCreated: (GoogleMapController controller) {
_mapController = controller;
_mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: _initialPosition,
zoom: 13.0,
),
),
);
},
initialCameraPosition: CameraPosition(
target: _initialPosition,
zoom: 13.0,
),
markers: const
Marker(
markerId: MarkerId(‘marker’),
position: LatLng(37.7749, -122.4194),
),
].toSet(),
polyLinePoints: polylinePoints != null
? PolylinePoints(polylinePoints)
: null,
),
);
}
}
“`
Step 2: Get the Users Current Location and Choose Destination
Get the users currnt location from the `Geolocator` package, show the current location on the map and create Chooser button to let the user select second point of the route
“`dart
import ‘package:flutter/material.dart’;
import ‘package:geolocator/geolocator.dart’;
import ‘package:googlemapsflutter/google_map.dart’;
class GoogleMapExample extends StatefulWidget {
@override
GoogleMapExampleState createState() => GoogleMapExampleState();
}
class _GoogleMapExampleState extends State
late GoogleMapController _mapController;
final LatLng _initialPosition = const LatLng(37.7749, -122.4194);
List
_currentIndex = 0;
double? _originLat;
double? _originLng;
double? _destinationLat;
double? _destinationLng;
LatLng? _destinationPoint;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(‘Google Map Example’),
),
body: Column(
children: [
ElevatedButton(
onPressed:() async {
final position = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
_originLat = position.latitude;
_originLng = position.longitude;
},
child: Text(‘Current Location’),
),
ElevatedButton(
onPressed:() async {
Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return Chooser();
}),
);
},
child: Text(‘Select Destination’),
),
Expanded(child: GoogleMap(
onMapCreated: (GoogleMapController controller) {
_mapController = controller;
_mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: _initialPosition,
zoom: 13.0,
),
),
);
Marker marker = Marker(
markerId: MarkerId(‘marker’),
position: LatLng(originLat??0, originLng??0)
);
if(null != originLat && null != originLng)
_mapController.addMarker(marker);
},
initialCameraPosition: CameraPosition(
target: _initialPosition,
zoom: 13.0,
),
markers: {originLat != null && originLng != null
?Marker(
markerId: MarkerId(‘marker’),
position: LatLng(originLat??0, originLng??0)
) :const{} }.toSet(),
polyLinePoints: polylinePoints != null
? PolylinePoints(polylinePoints)
: null,
))
],
),
);
}
}
class Chooser extends StatefulWidget {
@override
ChooserState createState() => ChooserState();
}
class _ChooserState extends State
LatLng? _choosenPoint;
void _openMap(BuildContext context) {
final result = await navigatorOptions(
context: context,
preferGoogleMaps: false,
// showPartners: true,
mode: Mode.fullscreen,
initialPosition: LatLng(37.7749, -122.4194),
onSelected: (result) {
setState(() {
_choosenPoint = result;
});
},
title: ‘Select a place.’,
);
if (result != null) {
setState(() {
_choosenPoint = result;
});
} else {
_choosenPoint = null;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(‘Select Destination’),
),
body: ElevatedButton(
onPressed: _openMap,
child: Text(‘${choosenPoint != null ? “${choosenPoint!.latitude}, ${_choosenPoint!.longitude}” : ”}’),
),
);
}
}
“`
Step 3: Calculate Distance
When the user selects the destination point, use the `Google Maps` `Directions API` to calculate the distance between the origin and destination points:
https://developers.google.com/maps/documentation/directions/overview
“`dart
import ‘package:flutter/material.dart’;
import ‘package:http/http.dart’ as http;
import ‘dart:convert’;
class GoogleMapExample extends StatefulWidget {
@override
GoogleMapExampleState createState() => GoogleMapExampleState();
}
class _GoogleMapExampleState extends State
// … (rest of your code)
void _calculateDistance() {
String _apiUrl =
‘https://maps.googleapis.com/maps/api/directions/json?origin=$originLat,$originLng&destination=$destinationLat,$destinationLng’;
http.get(Uri.parse(apiurl))
.then((response) {
Map
// Extract the distance from the API response
double distance = map[‘routes’][0][‘legs’][0][‘distance’][‘value’];
// Convert meters to miles
double distanceInMiles = distance / 1609.34;
// Print the result
print(‘Distance: $distanceInMiles miles’);
// to perform an update to the UI
setState(() {
// You can add code inside the setState method
// Update the UI to display the calculated distance
// by calling setState.
displayText = “Distance= ${distanceInMiles} miles”;}
);
}).catchError((error) {
print(‘Error fetching the distance from the API’);
});
}
}
“`
Conclusion
Calculating the distance between two locations on Google Map in Flutter can be achieved by using the Google Maps API, Geolocator, and googlemapsflutter package. By following the steps outlined in this article, you can create a robust and accurate distance calculation feature for your Flutter app.
Need Help Implementing in Your App?
Contact me for help implementing this feature in your app or for any question concering Flutter
FAQs
Q: How can I get started with the Google Maps API?
=============================================
A: First, enable the Google Maps API for your project in the Google Cloud Console. Then, install the googlemapsflutter package in your Flutter project.
Q: What is the Geolocator package?
=====================================
A: Geolocator is a Flutter package used for location-based services, such as GPS navigation, geolocation, and geocoding.
Q: How can I calculate the distance between two points in Google Maps?
=====================================================================
A: Use the Google Maps API’s Directions API to calculate the distance between two points. Pass the origin and destination coordinates to the API, and extract the distance from the response.
Q: Can I use this code in my ionic app?
======================================
A: No, this code is specific to Flutter and uses Flutter packages, which are not available in Ionic apps. However, you can achieve similar results using the ionic native plugins.
Q: What if the user does not allow location services?
=====================================================
A: Handle the location service permission denied error by displaying an alert box explaining the need for location services. This is a standard practice in mobile app development.