Skip to content

Instantly share code, notes, and snippets.

@stefanodecillis
Last active December 25, 2021 12:25
Show Gist options
  • Save stefanodecillis/c5c9fdb1900a128d03c0421bca533ca1 to your computer and use it in GitHub Desktop.
Save stefanodecillis/c5c9fdb1900a128d03c0421bca533ca1 to your computer and use it in GitHub Desktop.
Flutter app - Google Maps and Places snippet - main.dart
import 'package:flutter/material.dart';
import 'package:flutter_google_places/flutter_google_places.dart';
import 'package:google_map_polyline/google_map_polyline.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_webservice/places.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Map Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
GoogleMapController mapController;
TextEditingController departureController = new TextEditingController();
TextEditingController arrivalController = new TextEditingController();
List<Marker> markersList = [];
final String key = "here your api key";
LatLng _center = LatLng(
45.4654219, 9.1859243); //milan coordinates -- default location
GoogleMapsPlaces _places = GoogleMapsPlaces(apiKey: "here your key");
GoogleMapPolyline googleMapPolyline = new GoogleMapPolyline(apiKey: "here your key");
final List<Polyline> polyline = [];
List<LatLng> routeCoords = [];
PlaceDetails departure;
PlaceDetails arrival;
void onMapCreated(controller) {
setState(() {
mapController = controller;
});
}
Future<Null> displayPredictionDeparture(Prediction p) async {
if (p != null) {
// get detail (lat/lng)
PlacesDetailsResponse detail = await _places.getDetailsByPlaceId(
p.placeId);
final lat = detail.result.geometry.location.lat;
final lng = detail.result.geometry.location.lng;
setState(() {
departure = detail.result;
departureController.text = detail.result.name;
Marker marker = Marker(
markerId: MarkerId('arrivalMarker'),
draggable: false,
infoWindow: InfoWindow(
title: "This is where you will arrive",
),
onTap: () {
//print('this is where you will arrive');
},
position: LatLng(lat, lng)
);
markersList.add(marker);
});
mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: LatLng(lat, lng),
zoom: 10.0
)));
}
}
Future<Null> displayPredictionArrival(Prediction p) async {
if (p != null) {
// get detail (lat/lng)
PlacesDetailsResponse detail = await _places.getDetailsByPlaceId(
p.placeId);
final lat = detail.result.geometry.location.lat;
final lng = detail.result.geometry.location.lng;
setState(() {
arrival = detail.result;
arrivalController.text = detail.result.name;
Marker marker = Marker(
markerId: MarkerId('arrivalMarker'),
draggable: false,
infoWindow: InfoWindow(
title: "This is where you will arrive",
),
onTap: () {
//print('this is where you will arrive');
},
position: LatLng(lat, lng)
);
markersList.add(marker);
});
mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: LatLng(lat, lng),
zoom: 10.0
)));
computePath();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Demo"),
),
body: Stack(
children: <Widget>[
GoogleMap(
onMapCreated: onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
markers: Set.from(markersList),
polylines: Set.from(polyline),
),
Positioned(
top: 10.0,
right: 15.0,
left: 15.0,
child: Column(
children: <Widget>[
Container(
height: 50.0,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: Colors.white
),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(
hintText: 'Enter the departure place?',
border: InputBorder.none,
contentPadding: EdgeInsets.only(
left: 15.0, top: 15.0),
suffixIcon: IconButton(
icon: Icon(Icons.search),
iconSize: 30.0,
)
),
controller: departureController,
onTap: () async {
Prediction p = await PlacesAutocomplete.show(
context: context,
apiKey: key,
mode: Mode.overlay,
language: "en",
components: [
new Component(Component.country, "en")
]);
displayPredictionDeparture(p);
},
//onEditingComplete: searchAndNavigate,
),
],
)
),
SizedBox(
height: 10,
),
Container(
height: 50.0,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: Colors.white
),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(
hintText: 'Enter the arrival place?',
border: InputBorder.none,
contentPadding: EdgeInsets.only(
left: 15.0, top: 15.0),
suffixIcon: IconButton(
icon: Icon(Icons.search),
iconSize: 30.0,
)
),
controller: arrivalController,
onTap: () async {
Prediction p = await PlacesAutocomplete.show(
context: context,
apiKey: key,
mode: Mode.overlay,
language: "en",
components: [
new Component(Component.country, "en")
]);
displayPredictionArrival(p);
},
//onEditingComplete: searchAndNavigate,
),
],
)
),
],
)
),
],
),
);
}
computePath()async{
LatLng origin = new LatLng(departure.geometry.location.lat, departure.geometry.location.lng);
LatLng end = new LatLng(arrival.geometry.location.lat, arrival.geometry.location.lng);
routeCoords.addAll(await googleMapPolyline.getCoordinatesWithLocation(origin: origin, destination: end, mode: RouteMode.driving));
setState(() {
polyline.add(Polyline(
polylineId: PolylineId('iter'),
visible: true,
points: routeCoords,
width: 4,
color: Colors.blue,
startCap: Cap.roundCap,
endCap: Cap.buttCap
));
});
}
}
name: flutterdemo
description: A new Flutter application.
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
# Google maps flutter
google_maps_flutter: ^0.5.11
google_map_polyline: ^0.2.0
google_maps_webservice: ^0.0.16
flutter_google_places: ^0.2.0
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment