Flutter – Geolocation

Hi Friends,

Hope you are all well. In this post let’s see how to do a simple geolocation call using your mobile’s location sensor and use the latitude and longitude coordinates to locate the spot on a map.

To learn the basics of flutter get my course – Click here.

Other flutter courses – here. (Affliate link)

Let’s begin.

A screencast of this post

 

Code for this post can be found – here.

First of all create a new project and then open up pubspec.yaml.

Add the below packages as dependecies.

Open android -> app -> src -> main -> AndroidManifest.xml and add the permission as shown below.

(For iOS this is slightly different. Please visit the plugin page here to know about it.)

Alright, Now simply open main.dart file and modify it as shown below.

Whoa, that’s a lot of code.

Let’s break this down.

  1. I am following a three step process:
    1. Ask for permission to use the device’s gps from the user. (getPermission())
    2. Once the user grants permission, then simply make a request to get the current location. (getLocation())
    3. Use the returned result to simply move the map to the specific coordinates.
  2. Simply load the map as we saw here.
  3. In the center: attribute call the buildMap() function.
  4. The build map function simply calls the getLocation() which in turn calls the getPermission() method which makes the call to the user, gets the permission to access Location.
  5. The getLocation() method then requests for the device’s location.
  6. The buildMap() method then uses this to move the map to the specific lat, lng values using the mapController.
  7. The Map Controller provides us a lot of options to manipulate and perform actions on the map (i.e., after the map is initialized)

Enough talk, Let’s run this app. You would see the below screen.

Screenshot_2018-07-10-22-09-40

Cool right? I mean, obviously it would be a different screen for you guys based on your location, I presume. But you get the feel of it right ?

Hope this helped you guys. If you found this helpful, kindly share it with someone and help them too.

Donations – here.

Join our flutter community – here.

 

 

 

Liked it? Take a second to support admin on Patreon!
  • equasar

    What would be interesting to see is an implementation of a background service to register the user location when the screen is off or the apps is running in the background

    • True that, but I think that’s illegal in several countries.

  • Gerwin

    Nice post, thanks! In case you did not notice yet, there’s a new kid on the block in this area: Geolocator ( https://pub.dartlang.org/packages/geolocator ). This one also supports (forward / reverse) geo coding which might fit your example app nicely.