Integrating Maps and Geolocation Services Flutter
Last Updated :
08 Jul, 2024
In today's Android application, incorporating maps and geolocation services is essential. Whether it be finding the user's location, finding nearby travel places, or providing navigation, these features might really enhance the user experience and ease it down. Flutter, Google's UI toolkit for building natively compiled applications, makes it very easy and simple to integrate such functionalities using various plugins and packages.
In this article, we will be guided through the process of integrating maps and geolocation services in a Flutter application using the 'flutter_map' package with OpenStreetMap, which is a free and open-source solution. We'll also use the 'geolocator' package to access the device's location services and display the user's current location on the map.
Prerequisites
Before we start with map integration in Flutter, ensure that you have the following prerequisites:
- Basic understanding of Flutter and Dart programming language.
- Ensure that you have the Flutter development environment set up on your machine. If not, follow the Flutter Installation Guide.
- An emulator or a physical device for testing the application.
Dependencies and API Used
We'll use the following dependencies:
- flutter_map: A versatile Flutter package for displaying maps using OpenStreetMap.
- latlong2: A package for geographical calculations.
- geolocator: A package for accessing the device's location services.
Make sure to Add these above-mentioned dependencies to your pubspec.yaml file:
environment:
sdk: ">=2.12.0 <4.0.0"
dependencies:
flutter:
sdk: flutter
flutter_map: ^7.0.0
latlong2: ^0.9.1
geolocator: ^12.0.0
Run 'flutter pub get' to install these packages.
Directory Structure
Your project directory should look like this:
maps_and_geolocation/
└── lib/
├── main.dart
└── map_screen.dart
Configuring the Project
Let's Start making this flutter project and configure it to use the 'flutter_map' package .
1. Create a new Flutter project :
flutter create maps_and_geolocation
2. Update the pubspec.yaml file with the above mentioned dependencies .
Implementing Maps and Geolocation :
Step 1 : Import the required packages
After creating the project file , open the 'main.dart' file inside the 'lib/main.dart' and import required packages :
Dart
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:geolocator/geolocator.dart';
Step 2 : Create a StatefulWidget for the map screen
We'll create a StatefulWidget to manage the state of our map and location:
Dart
class MapScreen extends StatefulWidget {
@override
_MapScreenState createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
// Map and location-related code will go here
}
Step 3 : Initialize the MapController and user's location
Inside the '_MapScreenState' class, initialize the 'MapController' and the user's current location:
Dart
late final MapController _mapController;
LatLng _currentLocation = LatLng(28.6139, 77.2090); // Initial center (New Delhi, India)
@override
void initState() {
super.initState();
_mapController = MapController();
_getCurrentLocation(); // Get the user's current location on widget initialization
}
Step 4 : Get the user's current location
Implement the '_getCurrentLocation' method to get the user's current location using the 'geolocator' package:
Dart
Future<void> _getCurrentLocation() async {
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
setState(() {
_currentLocation = LatLng(position.latitude, position.longitude);
});
} catch (e) {
print('Error getting location: $e');
}
}
Create the map UI
In the build method of the '_MapScreenState' class, create the UI for the map screen:
Dart
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('OpenStreetMap'),
),
body: FlutterMap(
mapController: _mapController,
options: MapOptions(
center: _currentLocation,
zoom: 13.0,
),
children: [
TileLayer(
urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: ['a', 'b', 'c'],
),
MarkerLayer(
markers: [
Marker(
width: 80.0,
height: 80.0,
point: _currentLocation,
builder: (ctx) => Icon(
Icons.location_on,
size: 48.0,
color: Colors.red,
),
),
],
),
],
),
);
}
This code creates a Scaffold with an AppBar and a FlutterMap widget. The FlutterMap widget uses the MapController to control the map's state and the MapOptions to set the initial center and zoom level.
The TileLayer renders the OpenStreetMap tiles, and the MarkerLayer adds a marker at the user's current location, represented by an icon.
Run the Application
Connect an Android device or start an Android emulator, and run the app using the following command in your terminal:
flutter run
Complete Code for the Application
We have 2 files that are important in this project main.dart and map_screen.dart file .
1. main.dart file
Here is the complete code for that file :
main.dart
import 'package:flutter/material.dart';
import 'map_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GeeksforGeeks Demo',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: MapScreen(),
);
}
}
2. map_screen.dart file
map_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:geolocator/geolocator.dart';
class MapScreen extends StatefulWidget {
@override
_MapScreenState createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
late final MapController _mapController;
LatLng _center = LatLng(28.6139, 77.2090); // Initial center (New Delhi, India)
@override
void initState() {
super.initState();
_mapController = MapController();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GeeksforGeeks Maps'),
backgroundColor: Color(0xFF2F8D46), // GeeksforGeeks primary green color
),
body: FlutterMap(
mapController: _mapController,
options: MapOptions(
initialCenter: _center,
initialZoom: 13.0,
),
children: [
TileLayer(
urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: ['a', 'b', 'c'],
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: _getCurrentLocation,
tooltip: 'Get Location',
backgroundColor: Color(0xFF2F8D46), // GeeksforGeeks primary green color
child: Icon(Icons.my_location, color: Colors.white),
),
);
}
Future<void> _getCurrentLocation() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Location services are disabled.')),
);
return;
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Location permissions are denied')),
);
return;
}
}
if (permission == LocationPermission.deniedForever) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Location permissions are permanently denied, we cannot request permissions.'),
),
);
return;
}
// When permissions are granted, get the position of the device.
Position position = await Geolocator.getCurrentPosition();
setState(() {
_center = LatLng(position.latitude, position.longitude);
_mapController.move(_center, 13.0);
});
}
}
and when we run the main.dart file the output will be the Map of New Delhi , that is the initial location and when we click on the geolocation button , it will change to current location of the user (In this case to Ahmendabad)
Output:
Initial Map View
The app initially centers the map on New Delhi, India
User Location View
Upon clicking the floating action button, the map updates to the user location (simulated as Ahmedabad, India).
Conclusion
Integrating maps and geolocation services in a Flutter application can significantly enhance the functionality and user experience. By using the flutter_map package with OpenStreetMap, you can avoid the need for an API key and billing information, making it an excellent choice for small projects or those just getting started.
Note : Another free alternative is Mapbox, which offers a free tier and does not require card information for small-scale applications. You can use the mapbox_gl package for integrating Mapbox in Flutter.
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is a Neural Network?
Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read
Use Case Diagram - Unified Modeling Language (UML)
A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read