To summarize approach: you will send a network request to https://maps.googleapis.com/maps/api/geocode/json with various parameters.
In this example we will use reverse geocoding, which means converting coordinates to an address.
Once we are done with this example, I encourage you to try to convert human-readable address to coordinates.
Coordinates retrival from Embedded Map screen
In the previous part we added MapScreen under screens folder in map.dart file.
We will update this screen by letting user select a new location and showing a Save button in the top right corner.
Follow comments in the code snipped bellow to update the MapScreen:
Compile, run, and click on Show map button on the Home screen. You will see the familiar Map screen.
Now touch anywhere on the map, and you will see a Save button in the top right corner.
Before trying out the Save button, let’s update the Home screen to accept a correct object type when MapScreen is closed.
Now it should work, let’s try to tap on the Save button; the app will return to the Home screen with the selected User location.
Show coordinates on the Home screen
As a quick change we will add a new Text widget to show the selected location on the Home screen.
Restart the app, and you will see your coordinates above the Show Map button.
Open Map screen, and tap anywhere on the map. After tapping on the Save button, you will see the updated coordinates on the Home screen.
Try to open the Map screen again, and you will see Marker showing the last selected location.
Convert coordinates to Human readable address
We will focus on updating the Home screen to show the address instead of coordinates.
The core change is small, and I’ll hint about it in the code.
We will use http package introduced in the First post to call Google Maps API.
For this, we will also use dotenv package to read the API key from GOOGLE_MAPS_API_KEY environment variable.
As you can see, the main change is in the _fetchAddress method, where we send a GET request to Google Maps API and parse the response.
All the rest changes are up to you and a way how you want to show the address on the screen.
Now, restart the app, and you will see the address instead of coordinates above the Show Map button.
Since fetching address information from Google Maps API is asynchronous, we show a loading spinner while fetching the address (it also can take a while).
Summary
In this post, we have learned how to convert coordinates to an address and vice versa in Flutter Google Maps.
We have updated the Map screen to let the user select a new location and show a Save button.
We have also updated the Home screen to show the address instead of coordinates.
We used the http package to send a GET request to Google Maps API and the dotenv package to read the API key from the environment variable.
Optional: you can use dio package for network requests.
I’m happy for you; you have learned a new thing - how to manipulate addresses in Flutter Google Maps.