Make the Static Map Interactive

1. Make the Map Dynamic

Let's add the functionality for the map to display your current location. Thisstep has multiple parts:

  • Install Flutter location package.
  • Add a button that will get our location when pressed.
  • Rerender the map.

2. Flutter Location Package

We'll be using this package: Flutter Location.

This package is easy to use. Which is great if (like me) you have never developednatively on mobile.

To install the package:

In pubspec.yaml, under dependencies, add the package:

  1. dependencies:
  2. flutter:
  3. sdk: flutter
  4. location: ^1.1.6

Then, install the package:

  1. pub get

Then, you have to add the permissions to use the device location:

In the file tree, go to ios/runner/info.plist.

Add these lines four lines under the <dict> tag.

  1. <dict>
  2. <key>NSLocationWhenInUseUsageDescription</key>
  3. <string>The app would like to use your location</string>
  4. <key>NSLocationAlwaysUsageDescription</key>
  5. <string>The app would like to use your location</string>
  6. // ...

That's all for set up on iOS. To set up for Android also, follow theinstructions here.

3. Using the Package

The package is super easy to use. Import the package in your main.dartfile. You'll also need to import Dart's async library, so might as well pull that in:

  1. import 'dart:async';
  2. import 'package:location/location.dart';

Then, in your App's HomepageState widget, establish a new instance of the Location class. I'm also establishing a variable that we can assign our location values to.

  1. Location _location = new Location();
  2. dynamic deviceLocation;

Now, we can access the tools that this library gives us. I wrote a helperfunction that finds the devices current location.

  1. Future<Null> findUserLocation() async {
  2. Map<String, double> location;
  3. try {
  4. location = await _location.getLocation;
  5. setState(() {
  6. deviceLocation = location;
  7. });
  8. } catch (exception) {
  9. print(exception);
  10. }
  11. }

This library will return a map full of key's, which are location attributes(latitude, longitude, altitude, etc) and values which are doublerepresentations of the keys. As long as the user allows the app to use locationdata, then your deviceLocation will now look someting like this:

  1. {
  2. "latitude": 0.0,
  3. "longitude": 0.0,
  4. "altitude": 0.0,
  5. "accuracy": 0.0,
  6. }

4. Hook it up to the map:

Finally we need to add a button that:

  • Fetches our location.
  • Set's the state with the new location.
  • When the state is set, it will rebuild our staticMapProvider Widget, so we need to refactor that a bit too.

5. Refactor your StaticMapProvider

The SMP now needs to take in a location, and render the location it's given, or a default if none is given. To acheive this, give the SMP an optional argument:

  1. class StaticMapsProvider extends StatefulWidget {
  2. final String googleMapsApiKey;
  3. final Map<String, double> currentLocation;
  4. StaticMapsProvider(this.googleMapsApiKey, {this.currentLocation});
  5. // ...

Now in our _buildUrl() method, we'll want to keep the base URL, but then add query parameters if there's a location.

  1. _buildUrl(Map currentLocation) {
  2. var baseUri = new Uri(
  3. scheme: 'https',
  4. host: 'maps.googleapis.com',
  5. port: 443,
  6. path: '/maps/api/staticmap',
  7. queryParameters: {
  8. 'size': '${defaultWidth}x$defaultHeight',
  9. 'center':
  10. '${defaultLocation['latitude']},${defaultLocation['longitude']}',
  11. 'zoom': '4',
  12. '${widget.googleMapsApiKey}': ''
  13. });
  14. var finalUrl = baseUri;
  15. if (widget.currentLocation != null) {
  16. // this replaces the entire `queryParameters` property, so we have to pass in size, zoom, and apiKey again.
  17. finalUrl = baseUri.replace(queryParameters: {
  18. 'center': '${currentLocation['latitude']},${currentLocation['longitude']}',
  19. 'zoom': '15',
  20. '${widget.googleMapsApiKey}': '',
  21. 'size': '$defaultWidthx$defaultHeight',
  22. });
  23. }
  24. setState(() {
  25. renderUrl = finalUrl.toString();
  26. });
  27. }

6. Add the Button

Finally, back in our main.dart, add the raised button we'll need:

  1. //... the build method in _MyHomePageState:
  2. @override
  3. Widget build(BuildContext context) {
  4. return new Scaffold(
  5. appBar: new AppBar(
  6. title: new Text(widget.title),
  7. ),
  8. body: new Container(
  9. child: new Column(
  10. children: <Widget>[
  11. new StaticMapsProvider(googleMapsApiKey, currentLocation:deviceLocation),
  12. new Container(
  13. // Some extra layout code to save us time in the future:
  14. margin: const EdgeInsets.only(top: 5.0),
  15. child: new Row(
  16. mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  17. children: <Widget>[
  18. new RaisedButton(
  19. onPressed: findUserLocation,
  20. child: new Text('Get My Current Location'),
  21. color: Theme.of(context).primaryColor,
  22. ),
  23. ],
  24. ),
  25. ),
  26. ],
  27. )
  28. )
  29. );
  30. }
  31. }
  32. //...

What You Have So Far:

Gif demonstration

Nice! An app that renders static maps based on device location. This is nice, but we need to add a bit more functionality to see how this can be useful.

Aso, this is obviously ugly, but Flutter makes it really easy to solve thatproblem with transitions and animations. Here's an article I wrote on making those useful.

7. Reset Button

First, let's add the reset button quickly. This button will let you re-render the app back to default, which is nice for testing. Start by adding the Button to your main.dart build function:

  1. //...
  2. new Container(
  3. margin: const EdgeInsets.only(top: 5.0),
  4. child: new Row(
  5. mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  6. children: <Widget>[
  7. new RaisedButton(
  8. onPressed: findUserLocation,
  9. child: new Text('Get My Current Location'),
  10. color: Theme.of(context).primaryColor,
  11. ),
  12. // The new code:
  13. new RaisedButton(
  14. onPressed: resetMap,
  15. child: new Text('Reset Map'),
  16. color: Theme.of(context).primaryColor,
  17. ),
  18. ],
  19. //...

And now, add the resetMap method.

  1. void resetMap() {
  2. // Flutter knows to rerender, but it's passing null to our StaticMapsProvider, which means it'll render the default values.
  3. setState(() {
  4. deviceLocation = null;
  5. });
  6. }

8. Add Markers

If you look at the finished product, which can be found in this repository, you'll see thatthere are several different pieces of functionality we can add. I believe thatdynamically rendering markers is the most useful and the most difficult, so let's tackle that for now.

This requires a bit of a refactor.

Right now, our StaticMapProvider is expecting to possibly receive a location tocenter on. In order to place markers, you may want to pass multiple locations.So the first thing we need to do it refactor the StaticMapProvider to acceptthat.

  1. class StaticMapsProvider extends StatefulWidget {
  2. final String googleMapsApiKey;
  3. final List locations;
  4. final Map currentLocation;
  5. StaticMapsProvider(this.googleMapsApiKey, {this.locations});
  6. //...

Then we need to change our buildUrl method.

  • You can remove the query params from the baseUri declaration. From here onout, we will use the same baseUri no matter what, then add query params based on the locations passed in.
  • We need to check if there are markers on the map. The differencebetween this maps is that without markers there is only one location. So ifthere is only one location, we'll add certain query params.
  1. _buildUrl(Map currentLocation, List locations) {
  2. var finalUri;
  3. var baseUri = new Uri(
  4. scheme: 'https',
  5. host: 'maps.googleapis.com',
  6. port: 443,
  7. path: '/maps/api/staticmap',
  8. queryParameters: {});
  9. // the first case, which handles a user location but no markers
  10. if (currentLocation != null && widget.markers.length == 0) {
  11. finalUri = baseUri.replace(queryParameters: {
  12. 'center':
  13. '${currentLocation['latitude']},${currentLocation['longitude']}',
  14. 'zoom': widget.zoom.toString(),
  15. 'size': '${width ?? defaultWidth}x${height ?? defaultHeight}',
  16. '${widget.googleMapsApiKey}': ''
  17. });
  18. }
  19. setState(() {
  20. renderUrl = finalUrl.toString();
  21. });
  22. }
  23. // .. And then add a check in your build method:
  24. Widget build(BuildContext context) {
  25. // If locations is empty, then we need to render the default map.
  26. var currentLocation = widget.currentLocation;
  27. if (widget.currentLocation == null) {
  28. currentLocation = defaultLocation;
  29. }
  30. _buildUrl(currentLocation, widget.markers);
  31. }

Until we refactor main.dart to pass our StaticMapsProvider a list of locations, this won't work.

  1. class _MyHomePageState extends State<MyHomePage> {
  2. String googleMapsApiKey = 'AIzaSyCzxj6UFfx8uvDaaE9OSSPkjJXdou3jD9I';
  3. Location _location = new Location();
  4. Map<String, double> _currentLocation;
  5. List locations = [];
  6. Future<Null> findUserLocation() async {
  7. Map<String, double> location;
  8. try {
  9. location = await _location.getLocation;
  10. setState(() {
  11. _currentLocation = {
  12. "latitude": location["latitude"],
  13. "longitude": location['longitude'],
  14. };
  15. });
  16. } catch (exception) {}
  17. }
  18. void resetMap() {
  19. setState(() {
  20. _currentLocation = null;
  21. locations = [];
  22. });
  23. }
  24. //...

Then, in the build method, change the second argument to StaticMapsProvider constructor:

  1. children: <Widget>[
  2. new StaticMap(googleMapsApi,
  3. currentLocation: _currentLocation,
  4. markers: locations),

This refactor gets us back to where we need to be in order to start giving the map some markers.

Let's start by adding the UI, where the user can insert a Lat and Lng. Underneath your Current Location and Settings buttons, add this code to the Column widget's children.

  1. new Container(
  2. margin: new EdgeInsets.symmetric(horizontal: 25.0, vertical: 25.0),
  3. child: new Column(
  4. children: <Widget>[
  5. new TextField(
  6. controller: _latController,
  7. decoration: const InputDecoration(
  8. labelText: 'latitude',
  9. )),
  10. new TextField(
  11. controller: _lngController,
  12. decoration: const InputDecoration(
  13. labelText: 'longitude',
  14. )),
  15. new Container(
  16. margin: const EdgeInsets.symmetric(vertical: 10.0),
  17. child: new RaisedButton(
  18. onPressed: handleSubmitNewMarker,
  19. child: new Text('Place Marker'),
  20. color: Theme.of(context).primaryColor,
  21. ),
  22. ),
  23. ],
  24. ),
  25. ),

And, in order to make this work, we need to add some more functionality to our Widget. Add these text editing controllers to the widget:

  1. class _MyHomePageState extends State<MyHomePage> {
  2. Location _location = new Location();
  3. List locations = [];
  4. String googleMapsApi = 'AIzaSyCzxj6UFfx8uvDaaE9OSSPkjJXdou3jD9I';
  5. TextEditingController _latController = new TextEditingController();
  6. TextEditingController _lngController = new TextEditingController();

Text editing controllers are what allow us to get the values of text fields, clear text fields, etc. They're a bit outside the scope of this tutorial, but this is pretty much the extent of their use in 90% of cases I've come across.

We'll also need to write the method that gets the information from these text fields and turns it into something useful for us. This is what I wrote:

  1. void handleSubmitNewMarker() {
  2. String lat;
  3. String lng;
  4. // grab the values out of the text fields:
  5. lat = _latController.text;
  6. lng = _lngController.text;
  7. // Add the new location to the locations List.
  8. // Doing this inside SetState will cause a re-render:
  9. setState(() {
  10. locations.add({"latitude": lat, "longitude": lng});
  11. });
  12. // clear the text fields so its more user friendly:
  13. _lngController.clear();
  14. _latController.clear();
  15. }

This is all that the main.app state needs to do. But right now, if you tryto add a marker, all of the checks in StaticMapProvider class will fail. You'veonly written what to do if there's only one location in our markers List.By adding a marker, there are now two locations.

The bulk of the work is in the _buildUrl method.

Google's Static Maps api expects each marker's lat and lng to be passed in asa query parameter, separated by pipes (|). The approach here changes the waywe build the query params — the base URI stays the same.

  • Check the length of the markers List. (If it's 0, just center the map onthe user.)
  • If it's more than 1, we need to build the markers portion of query params.
  • First, add the users location.
  • Then, for each location, build a new String formatted like this: 'latitude, longitude'.
  • Join each of those mini strings with a |.The conditional statement that checks width should now look like this:
  1. if (currentLocation != null && widget.markers.length == 0) {
  2. // just center the map on the users location
  3. finalUri = baseUri.replace(queryParameters: {
  4. 'center':
  5. '${currentLocation['latitude']},${currentLocation['longitude']}',
  6. 'zoom': widget.zoom.toString(),
  7. 'size': '${width ?? defaultWidth}x${height ?? defaultHeight}',
  8. '${widget.googleMapsApiKey}': ''
  9. });
  10. } else {
  11. List<String> markers = new List();
  12. // Add a blue marker for the user
  13. var userLat = currentLocation['latitude'];
  14. var userLng = currentLocation['longitude'];
  15. String marker = '$userLat,$userLng';
  16. markers.add(marker);
  17. // Add a red marker for each location you decide to add
  18. widget.markers.forEach((location) {
  19. var lat = location['latitude'];
  20. var lng = location['longitude'];
  21. String marker = '$lat,$lng';
  22. markers.add(marker);
  23. });
  24. String markersString = markers.join('|');
  25. finalUri = baseUri.replace(queryParameters: {
  26. 'markers': markersString,
  27. 'size': '${width ?? defaultWidth}x${height ?? defaultHeight}',
  28. '${widget.googleMapsApiKey}': ''
  29. });
  30. }

Now, you should be able to Focus on your current location, reset the map, and place markers anywhere. Here's a screen shot:

Maps App

Fin

To add interactivity to the map (such as the zoom buttons), checkout the repo

In the next section, you'll see how to continuously update your device locationwith Dart Streams.