Follow Position
This example demonstrates how to create a Flutter app that follows the device’s location on a map using Maps SDK for Flutter, with an option to request location permissions if necessary.
How it works
The example app demonstrates the following features:
- Requesting location permissions on Android and iOS, with automatic handling on web platforms.
- Setting the live data source for the map (typically the device’s GPS).
- Following the device’s location on the map with optional animation.
UI and Map Integration
This code sets up the app’s user interface, including a map and a button to follow the device’s position.
Handling Location Permissions and Following Position
This code handles the process of requesting location permissions, setting the GPS as the live data source, and starting the map’s follow position mode.
Displaying Position Information
When the “Follow Position” button is pressed, the _onFollowPositionButtonPressed() callback is triggered. It requests location permission if it hasn’t been granted already, and sets the location data source to the device’s GPS sensor. Once the permission is granted and the data source is set, the map will follow the device’s location, centering the camera on the current position. The follow position feature is disabled if the user interacts with the map, such as by panning, until the button is pressed again.
- Android
- iOS
Add the following code to the android/app/src/main/AndroidManifest.xml
file, within the <manifest>
block:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
This example uses the Permission Handler package. Be sure to follow the setup guide.
Add the following to ios/Runner/Info.plist
inside the <dict>
:
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is needed for map localization and navigation</string>
This example uses the Permission Handler package. Follow the official setup instructions. Add this to your ios/Podfile
:
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
'PERMISSION_LOCATION=1',
]
end
end
end