The hard part of creating a good single player game is the implementation of a challenging but not unbeatable opponent. In case of quizzes, the opponent is a knowledge base. Let’s use the huge amount of geological knowledge bases to create a geo quiz game.
The idea is as follows:
The user is presented a random city or town on a map that has a circle on top indicating a radius. The user is then asked to guess the amount of random entity types within that area (for example: How many McDonald’s do you think are inside of that radius?). The user makes a guess, taps a button and is presented with the correct answer.
You would be surprised how hard it is to actually guess the correct amount!
So basically there are two different screens that look like this:
So what are the pieces we need to put together for this to work:
- Display a map inside of the app
- Display a certain radius around a given center
- Choose a random city or town (fetching its coordinates)
- Get the coordinates of all entities of a certain type inside of an area
Fetching the geo data
Before we start implementing anything with Flutter, let’s take care of getting the geo data we need.
There are quite some options we can choose from but if we require our API to be free and open source, the options decrease. Luckily, there is a huge collaborative project called OpenStreetMap. It is said to have more than 6000 contributors every day that voluntarily enhance the data. The data might not be as accurate as it is for Google Maps for some areas, but in any case it’s sufficient for our use case.
OpenStreetMap itself provides a REST API, but this is primarily for editing and updating map data. An alternative is Overpass API. It is a read-only API that gives the data consumer access to the underlying data of OSM, which is exactly what we want.
Let’s get familiar with the API. Unlike common web services like REST or SOAP, this API has its own query language called Overpass QL. The idea is to have a quantity of statements that manipulate the set containing the resulting nodes (or ways or relations).
Nodes are described using tags, which are basically key value pairs. For example places have the tag “population” with the number of citizens as the key.
Every statement written in Overpass QL ends with a semicolon.
Before we dive too deep into the semantics of the language, I will explain some basics based on a real working query:
1[out:json][timeout:80];
2
3area["ISO3166-1"="DE"][admin_level=2]->.germany;
4(
5 node["place"="town"](if: t["population"] > 20000)(area.germany);
6 node["place"="city"](area.germany);
7);
8
9out;
We start by defining the output format (JSON in this case). We also define a timeout of 80 seconds because the query will take some time to be completed. That’s because the result set will be quite big.
We then define an area. That’s because otherwise, we would query the whole world which would take too long. In our case, it’s the area with the tag “DE” for the key “ISO3166-1”. This norm defines the country codes. That means we restrict the area to Germany (country code: DE).
Within brackets we define the result set. We let it consist of all nodes with the tag being either town (with a population greater than 20.000) or city.
More information about places can be found in the official wiki.
But how do we test if our query produces a proper result? Thanks to Martin Raifer, there is a website called Overpass Turbo. This website lets the user query the overpass API and inspect the results on an embedded map (or as raw data).
The visualized response as JSON looks as follows (shortened to the first two elements):
1{
2 "version":0.6,
3 "generator":"Overpass API 0.7.56.7 b85c4387",
4 "osm3s":{
5 "timestamp_osm_base":"2020-10-26T12:50:03Z",
6 "timestamp_areas_base":"2020-10-26T11:40:02Z",
7 "copyright":"The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
8 },
9 "elements":[
10{
11 "type": "node",
12 "id": 12101533,
13 "lat": 49.6810158,
14 "lon": 8.6227577,
15 "tags": {
16 "ele": "115",
17 "is_in": "Bergstraße,Darmstadt,Hessen,Bundesrepublik Deutschland,Europe",
18 "name": "Bensheim",
19 "name:de": "Bensheim",
20 "name:ru": "Бенсхайм",
21 "openGeoDB:loc_id": "14285",
22 "place": "town",
23 "population": "39642",
24 "wikidata": "Q14872"
25 }
26},
27{
28 "type": "node",
29 "id": 13355228,
30 "lat": 48.7427584,
31 "lon": 9.3071685,
32 "tags": {
33 "alt_name": "Esslingen",
34 "is_in": "Esslingen,Stuttgart,Baden-Württemberg,Bundesrepublik Deutschland,Europe",
35 "name": "Esslingen am Neckar",
36 "name:ru": "Эсслинген-на-Неккаре",
37 "openGeoDB:loc_id": "16357",
38 "openGeoDB:postal_codes": "73728,73730,73732,73733,73734",
39 "place": "town",
40 "population": "92261",
41 "wikidata": "Q3786"
42 }
43},
44 ...
45 ]
46}
We may not need all of the information, but what we definitely need for our game are the coordinates (lon
and lat
) and the name
.
Implementation
The main part of the implementation is about the geo data. Let’s start with the static data we acquired by executing the previous query and then proceed with dynamic API calls.
Fetching cities and towns
The geo data we just fetched, is static. There won’t be lots of positional changes regarding the towns and cities in Germany in the next years. That’s why we download the data once and access that local data on the file system instead of making a new request to the Overpass API every time.
We take the JSON from the response and put it into a file. Then we create a new project and put it in a folder that we name “assets”:
I downloaded both the German and English cities and put their respective JSON files in a directory called “locations”, which is located directly under the assets folder.
We also need to edit the pubpsec.yml
to make the files under the assets folder accessible during runtime:
Let’s create a service that encapsulates the functionalities that are connected to geographic locations:
1import 'dart:convert';
2
3import 'package:flutter/services.dart' show rootBundle;
4
5class GeoService {
6 GeoService({
7 this.fileName = 'cities_de'
8 }): assert(fileName != '');
9
10 final String fileName;
11
12 List<Location> _cachedList;
13
14 Future<List<Location>> getLocations() async {
15 if (_cachedList == null) {
16 Map<dynamic, dynamic> json = await _getJsonFromFile(fileName);
17 _cachedList = _jsonToLocations(json);
18 }
19
20 return _cachedList;
21 }
22
23 Future<Map<dynamic, dynamic>> _getJsonFromFile(String fileName) async {
24 String jsonString = await rootBundle.loadString('assets/locations/$fileName.json');
25
26 return jsonDecode(jsonString);
27 }
28
29 List<Location> _jsonToLocations(Map<dynamic, dynamic> json) {
30 List<Location> locations = [];
31
32 for (var element in json["elements"]) {
33 locations.add(
34 Location.fromJson(element)
35 );
36 }
37
38 return locations;
39 }
40}
41
42class Location {
43 final double longitude;
44 final double latitude;
45 final String name;
46
47 Location({
48 this.longitude,
49 this.latitude,
50 this.name,
51 });
52
53 Location.fromJson(Map<dynamic, dynamic> json) :
54 longitude = json['lon'],
55 latitude = json['lat'],
56 name = json['tags']['name'];
57}
We add one public method to our newly created service: getLocations()
. This method returns a list of a new model named Location
, which holds the coordinates and a name.
The service’s constructor argument is the file name. Since we have a file for German cities (cities_de
) and one for English cities (cities_en
), we let the caller decide, which one to use and let the German cities be the fallback.
For converting JSON to the Location
model, we follow the official guidelines on serializing JSON inside model class and add a fromJson()
method.
We then iterate over every child of the elements
key inside the JSON data.
Fetching entities
When a new task in the game starts, we need to fetch the respective entities in the given area around the city. The request looks like this:
1[out:json][timeout:25];
2
3(
4 node["brand"="McDonald's"]["amenity"="fast_food"]["cuisine"="burger"](around:50000,52.520008,13.404954);
5);
6out body;
In this example, we query all the McDonald’s restaurants that are in a 50 km radius around Berlin.
Let’s abstract from the text form of the query by creating a OverpassQuery
class, that holds the parts of the query we need:
1class OverpassQuery {
2 String output;
3 int timeout;
4 List<SetElement> elements;
5
6 OverpassQuery({
7 this.output,
8 this.timeout,
9 this.elements
10 });
11
12 Map<String, String> toMap() {
13 String elementsString = '';
14
15 for (SetElement element in elements) {
16 elementsString += '$element;';
17 }
18
19 String data = '[out:$output][timeout:$timeout];($elementsString);out;';
20
21 return <String, String> {
22 'data': data
23 };
24 }
25}
26
27class SetElement {
28 final Map<String, String> tags;
29 final LocationArea area;
30
31 SetElement({
32 this.tags,
33 this.area
34 });
35
36 @override
37 String toString() {
38 String tagString = '';
39
40 tags.forEach((key, value) {
41 tagString += '["$key"="$value"]';
42 });
43
44 String areaString = '(around:${area.radius},${area.latitude},${area.longitude})';
45
46 return 'node$tagString$areaString';
47 }
48}
49
50class LocationArea {
51 final double longitude;
52 final double latitude;
53 final double radius;
54
55 LocationArea({
56 this.longitude,
57 this.latitude,
58 this.radius
59 });
60}
61
62class ResponseLocation {
63 double longitude;
64 double latitude;
65 String name;
66 String city;
67 String street;
68
69 ResponseLocation({
70 this.longitude,
71 this.latitude,
72 this.name,
73 this.city,
74 this.street,
75 });
76
77 ResponseLocation.fromJson(Map<dynamic, dynamic> json) {
78 this.longitude = json['lon'];
79 this.latitude = json['lat'];
80
81 Map<String, dynamic> tags = json['tags'];
82
83 if (tags == null) {
84 return;
85 }
86
87 this.name = json['tags']['name'];
88 this.city = json['tags']['addr:city'];
89 this.street = json['tags']['addr:street'];
90 }
91}
92
93class QueryLocation {
94 final double longitude;
95 final double latitude;
96
97 QueryLocation({
98 this.longitude,
99 this.latitude,
100 });
101}
We know that a query (at least the one we need) consists of three parts:
- Options (timeout; output format)
- Defining the result set
- Instruction to output the data
The most relevant part is defining the result set. This is modeled as a list of SetElement
s. Every SetElement
has a list of Tag
s (being a String Map
) and an to limit the space.
A crucial part of our OverpassQuery
is the toMap()
method because this method brings the query into a form that can be used as the body of our HTTP request to the Overpass API.
Now that we have a class representing an OverpassQuery
, let’s use this query to perform an actual request to the Overpass-API. So in addition to the query class, we add an API class:
1import 'dart:convert';
2
3import 'package:xml/xml.dart';
4import 'package:http/http.dart';
5
6import '../models/overpass_query.dart';
7
8
9class OverpassApi {
10 static String _apiUrl = 'overpass-api.de';
11 static String _path = '/api/interpreter';
12
13 Future<List<ResponseLocation>> fetchLocationsAroundCenter(QueryLocation center, Map<String, String> filter, double radius) async {
14 Request request = Request('GET', Uri.https(_apiUrl, _path));
15 request.bodyFields = _buildRequestBody(center, filter, radius);
16
17 String responseText;
18
19 try {
20 StreamedResponse response = await Client()
21 .send(request)
22 .timeout(const Duration(seconds: 5));
23
24 responseText = await response.stream.bytesToString();
25 }
26 catch (exception) {
27 print(exception);
28 return Future.error(exception);
29 }
30
31 var responseJson;
32
33 try {
34 responseJson = jsonDecode(responseText);
35 }
36 catch (exception) {
37 String error = '';
38 final document = XmlDocument.parse(responseText);
39 final paragraphs = document.findAllElements("p");
40
41 paragraphs.forEach((element) {
42 if (element.text.trim() == '') {
43 return;
44 }
45
46 error += '${element.text.trim()}';
47 });
48
49 return Future.error(error);
50 }
51
52 if (responseJson['elements'] == null) {
53 return [];
54 }
55
56 List<ResponseLocation> resultList = [];
57
58 for (var location in responseJson['elements']) {
59 resultList.add(ResponseLocation.fromJson(location));
60 }
61
62 return resultList;
63 }
64
65 Map<String, String> _buildRequestBody(QueryLocation center, Map<String, String> filter, double radius) {
66 OverpassQuery query = new OverpassQuery(
67 output: 'json',
68 timeout: 25,
69 elements: [
70 SetElement(
71 tags: filter,
72 area: LocationArea(
73 longitude: center.longitude,
74 latitude: center.latitude,
75 radius: radius
76 )
77 )
78 ],
79 );
80
81 return query.toMap();
82 }
83}
There is a lot going on in this class so I will explain step by step:
The only public method we have is fetchLocationsAroundCenter()
. This method receives a location, a filter and a radius. A filter is a list of an associative array (Map). This represents the tag filters. This is useful if we e. g. only want to fetch the trees. A tree in OSM is determined by the tag "natural": "tree"
. A McDonald’s entity is determined by "brand": "McDonald's"
.
So the filter
Map says: only if the tags of the entities meet the structure of the given map, they will be queried.
The radius
argument determines the km around the center in which the filtered entities should be searched.
The _buildRequestBody()
‘s responsibility is to convert the given OverpassQuery
to a valid body that meets the requirements of the HTTP-Library of Dart. In this case, the bodyFields
field of the Request
is basically a Map<String, String>
. That’s why this is the return value of our method.
Now why do we need XML-parsing here? Well, the API acts a little bit strange here. In case of success, the response is a JSON string. If there was an error, it’s embedded into an XML document. That’s the reason why try to parse the JSON string. If there was an error parsing it, we know there was an error, parse the XML document and extract the error from the XML. Otherwise, we return the “elements” value from the JSON.
Putting everything in the GeoService
Now that we have an API class that handles Overpass-API requests for us, we need to use that class in our GeoService
:
1class GeoService {
2 GeoService({
3 @required this.overpassApi,
4 this.fileName = 'cities_de'
5 }): assert(overpassApi != null);
6
7 final OverpassApi overpassApi;
8 final String fileName;
9
10 ...
11
12 Future<List<Location>> getEntitiesInArea({
13 Location center, SearchType type, double radiusInMetres = 5000
14 }) async {
15 List<ResponseLocation> fetchResult = await this.overpassApi.fetchLocationsAroundCenter(
16 QueryLocation(
17 longitude: center.longitude,
18 latitude: center.latitude
19 ),
20 type.tags,
21 radiusInMetres
22 );
23
24 List<Location> result = [];
25
26 fetchResult.forEach((element) {
27 result.add(
28 Location(
29 longitude: element.longitude,
30 latitude: element.latitude,
31 name: element.name
32 )
33 );
34 });
35
36 return result;
37 }
38
39 ...
40
41}
With the constructor now expecting the OverpassAPI class in its constructor, we are now able to call it inside our newly created function. We pass the QueryLocation
, the tags and the radius and iterate over the result set, turning it into a List<Location>
.
Search types
As an observant reader you might have noticed that the getEntitiesInArea()
method of our GeoService
expects a SearchType
. This is a class we haven’t introduced yet. The idea is to have different search types like trees, bars etc. of which a random one is picked when the user wants a new geo guessing exercise round and passed to the API call.
For this, we need a place to define the available search types and a service that returns them.
Let’s define a search_types.json
that is located under assets/
and define our search types like this:
1{
2 "elements": [
3 {
4 "name": {
5 "singular": "bar",
6 "plural": "bars"
7 },
8 "tags": {
9 "amenity": "bar"
10 }
11 },
12 {
13 "name": {
14 "singular": "pub",
15 "plural": "pubs"
16 },
17 "tags": {
18 "amenty": "pub"
19 }
20 },
21 {
22 "name": {
23 "singular": "McDonald's",
24 "plural": "McDonald's"
25 },
26 "tags": {
27 "brand": "McDonald's",
28 "amenity": "fast_food",
29 "cuisine": "burger"
30 }
31 },
32 {
33 "name": {
34 "singular": "street lamp",
35 "plural": "street lamps"
36 },
37 "tags": {
38 "highway": "street_lamp"
39 }
40 },
41 {
42 "name": {
43 "singular": "tree",
44 "plural": "trees"
45 },
46 "tags": {
47 "natural": "tree"
48 }
49 },
50 {
51 "name": {
52 "singular": "memorial",
53 "plural": "memorials"
54 },
55 "tags": {
56 "historic": "memorial"
57 }
58 },
59 {
60 "name": {
61 "singular": "bus stop",
62 "plural": "bus stops"
63 },
64 "tags": {
65 "highway": "bus_stop"
66 }
67 },
68 {
69 "name": {
70 "singular": "fire station",
71 "plural": "fire stations"
72 },
73 "tags": {
74 "amenity": "fire_station"
75 }
76 },
77 {
78 "name": {
79 "singular": "bench",
80 "plural": "benches"
81 },
82 "tags": {
83 "amenity": "bench"
84 }
85 },
86 {
87 "name": {
88 "singular": "village",
89 "plural": "villages"
90 },
91 "tags": {
92 "place": "village"
93 }
94 },
95 {
96 "name": {
97 "singular": "post box",
98 "plural": "post boxes"
99 },
100 "tags": {
101 "amenity": "post_box"
102 }
103 },
104 {
105 "name": {
106 "singular": "recycling container",
107 "plural": "recycling containers"
108 },
109 "tags": {
110 "amenity": "recycling"
111 }
112 }
113 ]
114}
By having a JSON file with its search type definitions, we have a very extendible game.
Apart from the tags the search type should have, we also define the singular and plural of the word so that we can display meaningful sentences with the search type like: “How many bars are around Hamburg?”
Now we need a service to retrieve these search type from the JSON file and put it into a new class:
1import 'dart:convert';
2
3import 'package:flutter/services.dart' show rootBundle;
4
5class SearchTypeService {
6 List<SearchType> _cachedList;
7
8 Future<List<SearchType>> getSearchTypes() async {
9 if (_cachedList == null) {
10 List<dynamic> json = await _getJsonFromFile('search_types');
11 _cachedList = _jsonToSearchTypes(json);
12 }
13
14 return _cachedList;
15 }
16
17 Future<List<dynamic>> _getJsonFromFile(String fileName) async {
18 String jsonString = await rootBundle.loadString('assets/$fileName.json');
19
20 return jsonDecode(jsonString)['elements'];
21 }
22
23 List<SearchType> _jsonToSearchTypes(List<dynamic> json) {
24 List<SearchType> searchTypes = [];
25
26 for (var element in json) {
27 searchTypes.add(
28 SearchType.fromJson(element)
29 );
30 }
31
32 return searchTypes;
33 }
34}
35
36class SearchType {
37 String singular;
38 String plural;
39 Map<String, String> tags;
40
41 SearchType({
42 this.singular,
43 this.plural,
44 this.tags
45 });
46
47 SearchType.fromJson(Map<dynamic, dynamic> json) {
48 this.singular = json['name']['singular'];
49 this.plural = json['name']['plural'];
50
51 Map<String, String> tags = new Map();
52
53 json['tags'].forEach((key, value) {
54 tags[key] = value;
55 });
56
57 this.tags = tags;
58 }
59}
This happens in a similar fashion like the GeoService
fetches the cities from the cities_xx.json
.
Displaying a map
Now it’s time to actually display a map in the UI. Because we are working with OSM, we can’t use the google_maps_flutter package. Instead, we are going to use flutter_map. It’s an implementation of the popular Javascript library Leaflet. Let’s add this dependency to our pubspec:
Now that we have the possibility to display a map, we are going to implement the main widget, showing the map and enabling the user to interact with the quiz:
1import 'dart:math';
2
3import 'package:flutter/material.dart';
4import 'package:flutter_geo_guesser/api/overpass_api.dart';
5import 'package:flutter_geo_guesser/services/geo_service.dart';
6import 'package:flutter_geo_guesser/services/search_type_service.dart';
7import 'package:flutter_map/flutter_map.dart';
8import 'package:latlong/latlong.dart';
9
10class Quiz extends StatefulWidget {
11 @override
12 _QuizState createState() => _QuizState();
13}
14
15class _QuizState extends State<Quiz> {
16 final MapController _mapController = new MapController();
17 final OverpassApi _overpassApi = new OverpassApi();
18 GeoService _geoService;
19
20 List<SearchType> _searchTypes = [];
21 List<Location> _locations = [];
22
23 Location _currentLocation;
24 List<Location> _entities = [];
25 SearchType _currentType;
26 bool _answered = false;
27
28 @override
29 void initState() {
30 _geoService = new GeoService(overpassApi: _overpassApi);
31
32 WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
33 _initialize();
34 });
35
36 super.initState();
37 }
38
39 @override
40 Widget build(BuildContext context) {
41 return Scaffold(
42 appBar: AppBar(
43 backgroundColor: Colors.white,
44 title: Center(child: Text("Guess what! 🤔", style: TextStyle(color: Colors.black))),
45 ),
46 body: Center(
47 child: Stack(
48 children: [
49 _getMap(),
50 _getTopContainer()
51 ],
52 )
53 ),
54 floatingActionButton: FloatingActionButton(
55 onPressed: _proceed,
56 child: Icon(Icons.check),
57 ),
58 );
59 }
60
61 ...
62
63}
First, we’re initializing a bunch of member variables. The first three are just to keep single instances of the controller and services we are using. These are initialized once.
_searchedTypes
and _locations
represent the static data we are reading from our JSON files (cities_xy.json
and search_types.json
).
The rest of the variables exist to store the current state of the quiz. This is necessary so that we can adjust what the widget shows accordingly.
The main layout is pretty simple: we have a Stack
with the map at the bottom and a top container on top. This container shows either the current quiz question (“How many entities of type xy are there around z?”) or the answer (“There are x entitites of type y around z”).
The FloatingActionButton
exists to let the user proceed. Either to the next question or from the unanswered state to answered state.
Let’s have a look at the _initialize()
method we are calling inside of initState()
after the first frame was rendered:
1void _initialize() async {
2 _searchTypes = await SearchTypeService().getSearchTypes();
3 _locations = await _geoService.getLocations();
4
5 _getNewLocation();
6 _getNewSearchType();
7 }
8
9 void _getNewLocation() {
10 if (_locations.isEmpty) {
11 return;
12 }
13
14 setState(() {
15 _currentLocation = _locations[Random().nextInt(_locations.length)];
16 });
17
18 _mapController.move(
19 new LatLng(_currentLocation.latitude, _currentLocation.longitude),
20 11
21 );
22 }
23
24 void _getNewSearchType() {
25 _currentType = _searchTypes[Random().nextInt(_searchTypes.length)];
26 }
Initially, we are fetching the search types we have set in our search_type.json
. We also fetch the locations from cities_xx.json
. After that, we let our algorithm choose a new random location and let the MapController
move there which centers this location in our map. After having chosen a new location, we also choose a new SearchType
.
Now that we’ve had a look at the initialization, let’s inspect what happens when the user taps the FloatingActionButton
which calls the _proceed()
method:
1void _proceed() async {
2 if (_answered == true) {
3 _showNewQuestion();
4 return;
5 }
6
7 _answerQuestion();
8 }
9
10 void _showNewQuestion() {
11 setState(() {
12 _getNewLocation();
13 _getNewSearchType();
14 _entities = [];
15 _answered = false;
16 });
17 }
18
19 Future _answerQuestion() async {
20 _indicateLoading();
21
22 _entities = await GeoService(overpassApi: _overpassApi).getEntitiesInArea(
23 center: _currentLocation,
24 type: _currentType
25 );
26
27 Navigator.of(context).pop();
28
29 setState(() {
30 _answered = true;
31 });
32 }
There are two states in which the FAB can be tapped: when the current question is display or when the current answer is displayed.
We differentiate these two states by evaluation the _answered
variable.
If _answered
equals true, it means that tapping the FAB should display a new question. That’s why we choose a new location, a new search type and reset the entities and the answered flag.
Otherwise, if _answered
equals false, we need to display the answer to the previous question. First, we indicate a loading because the following procedure can take some time as it’s out of our control how quickly the Overpass API responds to our query. Then we fetch the entities in the current location, await the result, dismiss the loading indicator and set the _answered
flag to true.
Great! Now that we have the necessary data in place, we’re only left to use this data to display a map that visualizes it.
1FlutterMap _getMap() {
2 return FlutterMap(
3 mapController: _mapController,
4 options: new MapOptions(
5 interactive: false,
6 center: _currentLocation != null ? new LatLng(_currentLocation.latitude, _currentLocation.longitude) : null,
7 zoom: 11,
8 ),
9 layers: [
10 new TileLayerOptions(
11 urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
12 subdomains: ['a', 'b', 'c']
13 ),
14 new MarkerLayerOptions(
15 markers: _getMarkers(),
16 ),
17 new MarkerLayerOptions(
18 markers: _getAreaMarkers(),
19 ),
20 ],
21 );
22 }
23
24 List<Marker> _getMarkers() {
25 List<Marker> markers = [];
26
27 for (Location location in _entities) {
28 markers.add(
29 new Marker(
30 width: 6,
31 height: 6,
32 point: new LatLng(location.latitude, location.longitude),
33 builder: (ctx) =>
34 new Container(
35 decoration: BoxDecoration(
36 shape: BoxShape.circle,
37 color: Colors.red
38 ),
39 ),
40 )
41 );
42 }
43
44 return markers;
45 }
46
47 List<Marker> _getAreaMarkers() {
48 if (_currentLocation == null) {
49 return [];
50 }
51
52 return [new Marker(
53 width: 230.0,
54 height: 230.0,
55 point: new LatLng(_currentLocation.latitude, _currentLocation.longitude),
56 builder: (ctx) =>
57 new Container(
58 decoration: BoxDecoration(
59 shape: BoxShape.circle,
60 color: Colors.blue.withOpacity(0.1),
61 border: Border.all(color: Colors.blueAccent)
62 ),
63 ),
64 )];
65 }
66
67 Container _getTopContainer() {
68 return Container(
69 alignment: Alignment.topCenter,
70 child: Container(
71 padding: EdgeInsets.all(32),
72 height: 160,
73 alignment: Alignment.center,
74 width: double.infinity,
75 color: Colors.white.withOpacity(0.8),
76 child: Text(
77 _getText(),
78 style: TextStyle(fontSize: 24),
79 textAlign: TextAlign.center,
80 )
81 ),
82 );
83 }
84
85 String _getText() {
86 if (_currentLocation == null) {
87 return '';
88 }
89
90 if (_currentType == null) {
91 return '';
92 }
93
94 if (_answered == false) {
95 return "How many ${_currentType.plural} are there 5 km around ${_currentLocation.name}?";
96 }
97
98 return "${_entities.length.toString()} ${_currentType.plural}\naround ${_currentLocation.name}";
99 }
The FlutterMap
itself receives the controller and some MapOptions
. We don’t want the map to be interactive (that would include the ability to pan and zoom) because it would make things too easy for the user. If we have a _currentLocation
, we want the center to be this location.
Without layers, the map does not display anything. That’s why we need to specify them. At the bottom we want the OSM map to be displayed (Leaflet supports other providers as well).
On top of that, we display a red dot for every entity of the current SearchType
.
Last but not least, we display the area circle indicating the radius in which we are searching for the current SearchType
. Being semi-transparent, it still displays the underlying red dots.
Result
That’s it, we’re done. Let’s look at the result from the user perspective:
Final words
The existing map plugins make it very easy to embed a map into a Flutter app. Utilizing the enormous amount of free data provided by the Overpass API in combination with a map plugin, we were able to create a quiz game that makes the user guess how many entities of a certain type surround a given town or city.
The application is kept extendable. All of the static data like cities and search types is stored in separate JSON files instead of the code.
GET FULL CODE
Comment this 🤌