I am reading Chapter 11 of the Flutter Cookbook – Second Edition by Simone Alessandria. I follow the following steps:
-
Create a new Flutter app, and call it map_recipe.
-
flutter pub add google_maps_flutter
-
flutter pub add location
-
flutter pub add http
-
I obtained Google Maps API key from here.
-
In the Android manifest file, which you can find at
android/app/src/main/AndroidManifest.xml
, add the following node to the Manifest node (before the application node):
But how to do it for the Web?
The code below displays the Google Maps heading, but the map is missing.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:http/http.dart' as http;
// API set up /questions/78675785/how-to-add-google-maps-api-to-flutter-web
/*One of the platform-independent plugins currently available is the flutter_map
plugin, available at https://pub.dev/packages/flutter_map.*/
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Map Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyMap(),
);
}
}
class MyMap extends StatefulWidget {
const MyMap({super.key});
@override
State<MyMap> createState() => _MyMapState();
}
class _MyMapState extends State<MyMap> {
late LatLng userPosition;
List<Marker> markers = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Google Maps'),
actions: [
IconButton(
icon: const Icon(Icons.map),
onPressed: () => findPlaces(),
)
],
),
body: FutureBuilder(
future: findUserLocation(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return GoogleMap(
initialCameraPosition:
CameraPosition(target: snapshot.data, zoom: 12),
markers: Set<Marker>.of(markers),
);
} else {
return Container();
}
}));
}
Future<LatLng> findUserLocation() async {
Location location = Location();
LocationData userLocation;
PermissionStatus hasPermission = await location.hasPermission();
bool active = await location.serviceEnabled();
if (hasPermission == PermissionStatus.granted && active) {
userLocation = await location.getLocation();
userPosition = LatLng(userLocation.latitude!, userLocation.longitude!);
} else {
userPosition = const LatLng(51.5285582, -0.24167);
}
return userPosition;
}
Future findPlaces() async {
const key = 'AIzaSyC3QnqXZv40jODoLsl9NYKSzn-wxrhaENo';
const placesUrl =
'https://maps.googleapis.com/maps/api/place/nearbysearch/json?';
String url = placesUrl +
'key=$key&type=restaurant&location=${userPosition.latitude},${userPosition.longitude}' +
'&radius=1000';
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final data = json.decode(response.body);
showMarkers(data);
} else {
throw Exception('Unable to retrieve places');
}
}
showMarkers(data) {
List places = data['results'];
markers.clear();
for (var place in places) {
markers.add(Marker(
markerId: MarkerId(place['reference']),
position: LatLng(place['geometry']['location']['lat'],
place['geometry']['location']['lng']),
infoWindow:
InfoWindow(title: place['name'], snippet: place['vicinity'])));
}
setState(() {
markers = markers;
});
}
}
The full code can be found on the author’s GitHub