Using maps in Flutter with Mapbox

Kürşat Fevzican Şayhan
5 min readFeb 17, 2023

--

Maps are used in many applications today, such as navigation, tracking applications, or showing certain things on the map. We will examine the map usage in Flutter via Mapbox.

Mapbox Settings

After logging in to the Mapbox site, we enter to the Styles settings via Studio. Here we choose the view we want. Then we click on the upload icon next to the view we selected on the list and the Share & develop window appears. In the window that opens, we choose the ThirdParty -> Carto options from the Developer Resources section. The Integration Url that comes out here will be the url we will use.

Mapbox Studio ( Share your style ) Integration Url

After obtaining the Integration Url, we have finished our work on the Mapbox side

Flutter Setup

We will use the Flutter_map library on the Flutter side for our application. First, we call our library under dependencies in the pubspec.yaml file, and then we run the Flutter pub get command.

dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_map: ^2.2.0
latlng: any

Code

In our code page, we first start by importing our libraries.

import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';

Then we add our Flutter Map Widget. In the widget, we first add the MapOptions property in the options variable and add the center/zoom property. Then we add the layers required for our application one by one in the layers variables. Since the first layer we will add will be Tile Layer, we add the TileLayerOptions property. In this feature, we enter the style url we get from the mapbox and the Access token variables that we will get from the account tab.

FlutterMap(
options: MapOptions(
center: LatLng(39.920740, 32.854072),
zoom: 5,
),
children: [
TileLayerWidget(
options: TileLayerOptions(

urlTemplate:"https://api.mapbox.com/styles/v1/account/clbtsrfif001014q353yh
59zw/tiles/256/{z}/{x}/{y}@2x?access_token=YOUR_API_KEY",
additionalOptions: {
'accessToken':'YOUR_API_KEY',
}),
),
],
)

I have my own information in the account and access_token=YOUR_API_KEY sections in the URL, I entered those sections as “account” and “Account Token”. You have to enter your own information.

After the necessary operations are performed, we will get an output as follows.

Code Output of Map

Live Location

Let’s show our instant location on the map, and now let’s start by adding the necessary libraries to our pubspec.yaml file. Libraries we will use
There will be geolocator, permission_handler and flutter_map_location_marker libraries.

dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_map:
geolocator:
permission_handler: ^9.2.0
flutter_map_location_marker: ^4.1.1

After adding the libraries, we make the minSdkVersion 23 under the defaultConfig in the build.grandle file at the app level.
Then, in order to get the location permission from the user, we ask the 3 permissions required for the location in the AndroidManifest.xml file.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

After writing our location permissions, we can move on to the code part. In the code section, first, let’s write the function to get the instant location and the function to get the permissions from the user.

We start by calling the variable that we will save the instant location of the user, and then we will get the instant location of the user with the method of the Geolocator library to which we have added the library.

Position? _currentPosition;
_determinePosition() { Geolocator.getPositionStream().listen((event) {

_currentPosition=event;
});
}

I will get the location permissions in initState, so we will request the permissions as soon as the user opens the page. For permission, we will first check whether the user’s location services are turned on, and if it is open, we will check whether this application has allowed location access, if not, we will ask the user for location permission.

@override
void initState() {
// TODO: implement initState
super.initState();
locationPermission();
}
Future<void> locationPermission()async{
if(await Permission.location.serviceStatus.isEnabled) {
var statuslocation = await Permission.location.status; if(statuslocation.isDenied)
{
Map<Permission,PermissionStatus> status = await [Permission.location].request();
}
}
}

After requesting the location permission, we take our Flutter Map widget into the StreamBuilder Widget so that the map is triggered every time the location changes, and we add the _determinePosition function that we wrote as a stream. In Flutter Map, we add LocationLayer to see the location on the map.

StreamBuilder(
stream: _determinePosition(),
builder: (context,snapshot){
return FlutterMap(
options: MapOptions(
center: LatLng(39.920740, 32.854072), zoom: 5,
),
children: [
TileLayerWidget(
options: TileLayerOptions(
urlTemplate:"https://api.mapbox.com/styles/v1/account/clbtsrfif001014q353yh 59zw/tiles/256/{z}/{x}/{y}@2x?access_token=YOUR_API_KEY",
additionalOptions: {
'accessToken': 'YOUR_API_KEY',
}), ),
LocationMarkerLayerWidget(options: LocationMarkerLayerOptions(),), ],
); }
Live Location Display on Map

Markers

We use markers to show specific points on the map. We can use any image, icon or gif-like image for the markers.

FlutterMap(
options: MapOptions(
center: LatLng(39.920740, 32.854072),
zoom: 5, ),
layers: [
TileLayerOptions(
urlTemplate:"https://api.mapbox.com/styles/v1/account/clbtsrfif001014q353yh 59zw/tiles/256/{z}/{x}/{y}@2x?access_token=YOUR_API_KEY",
additionalOptions: {
'accessToken':'YOUR_API_KEY',
}),
MarkerLayerOptions(
markers: [
Marker(
anchorPos: AnchorPos.align(AnchorAlign.top),
point: LatLng(39.920740, 32.854072),
builder: (context){
return Icon(FontAwesomeIcons.mapMarkerAlt); })
] )
], ),
Marker display on Map

Gif Marker

Sometimes when using a marker, you may need to use gifs instead of images such as png, jpg. Although this is not allowed in other libraries, the flutter_map library also supports it.

Marker(
anchorPos: AnchorPos.align(AnchorAlign.center),
point: LatLng(39.920740, 32.854072),
width: MediaQuery.of(context).size.width*0.2,
height: MediaQuery.of(context).size.height*0.2 ,
builder: (context){
return Image.asset("assets/gif.gif");
}
)
Gif Marker on Map

Image Marker

Marker(
anchorPos: AnchorPos.align(AnchorAlign.center),
point: LatLng(39.920740, 32.854072),
width: MediaQuery.of(context).size.width*0.1,
height: MediaQuery.of(context).size.height*0.1 ,
builder: (context){
return Image.asset("assets/wi-fi.png");
}
)
Image Marker on Map

Polygon

We use polygons to show a specific area on the map rather than a specific point. For example borders, plots, regions.

PolygonLayerWidget(options: PolygonLayerOptions(
polygons: [
Polygon(points: [LatLng(40.393331, 32.007729),LatLng(40.751213, 32.631318),LatLng(40.319412, 33.619823),LatLng(38.813266, 33.772256),LatLng(38.766461, 33.375006),LatLng(39.273446, 32.944274),LatLng(39.074858, 31.940196)],
color: Colors.purple.shade100.withOpacity(0.5),isFilled: true) ])
Polygon on Map

Polyline

We use it to show as a line outside a certain point or area on the map. Drawing a route is an example of this.

PolylineLayerWidget(options: PolylineLayerOptions(
polylines: [
Polyline(points: [LatLng(40.393331, 32.007729),LatLng(40.751213, 32.631318),LatLng(40.319412, 33.619823),LatLng(38.813266, 33.772256),LatLng(38.766461, 33.375006),LatLng(39.273446, 32.944274),LatLng(39.074858, 31.940196)],
color: Colors.purple.shade900)
] ))
Polyline on Map

--

--

Kürşat Fevzican Şayhan
Kürşat Fevzican Şayhan

Written by Kürşat Fevzican Şayhan

Hi, I am developing mobile and desktop applications. I use Flutter/Dart language in mobile programming and .Net/C# language in desktop programming.

Responses (1)