-
Notifications
You must be signed in to change notification settings - Fork 158
/
main.dart
544 lines (505 loc) · 18.9 KB
/
main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
import 'package:flutter/material.dart';
import 'package:flutter_maps/secrets.dart'; // Stores the Google Maps API Key
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'dart:math' show cos, sqrt, asin;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Maps',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MapView(),
);
}
}
class MapView extends StatefulWidget {
@override
_MapViewState createState() => _MapViewState();
}
class _MapViewState extends State<MapView> {
CameraPosition _initialLocation = CameraPosition(target: LatLng(0.0, 0.0));
GoogleMapController mapController;
final Geolocator _geolocator = Geolocator();
Position _currentPosition;
String _currentAddress;
final startAddressController = TextEditingController();
final destinationAddressController = TextEditingController();
String _startAddress = '';
String _destinationAddress = '';
String _placeDistance;
Set<Marker> markers = {};
PolylinePoints polylinePoints;
Map<PolylineId, Polyline> polylines = {};
List<LatLng> polylineCoordinates = [];
final _scaffoldKey = GlobalKey<ScaffoldState>();
Widget _textField({
TextEditingController controller,
String label,
String hint,
double width,
Icon prefixIcon,
Widget suffixIcon,
Function(String) locationCallback,
}) {
return Container(
width: width * 0.8,
child: TextField(
onChanged: (value) {
locationCallback(value);
},
controller: controller,
decoration: new InputDecoration(
prefixIcon: prefixIcon,
suffixIcon: suffixIcon,
labelText: label,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
),
borderSide: BorderSide(
color: Colors.grey[400],
width: 2,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
),
borderSide: BorderSide(
color: Colors.blue[300],
width: 2,
),
),
contentPadding: EdgeInsets.all(15),
hintText: hint,
),
),
);
}
// Method for retrieving the current location
_getCurrentLocation() async {
await _geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
.then((Position position) async {
setState(() {
_currentPosition = position;
print('CURRENT POS: $_currentPosition');
mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(position.latitude, position.longitude),
zoom: 18.0,
),
),
);
});
await _getAddress();
}).catchError((e) {
print(e);
});
}
// Method for retrieving the address
_getAddress() async {
try {
List<Placemark> p = await _geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress =
"${place.name}, ${place.locality}, ${place.postalCode}, ${place.country}";
startAddressController.text = _currentAddress;
_startAddress = _currentAddress;
});
} catch (e) {
print(e);
}
}
// Method for calculating the distance between two places
Future<bool> _calculateDistance() async {
try {
// Retrieving placemarks from addresses
List<Placemark> startPlacemark =
await _geolocator.placemarkFromAddress(_startAddress);
List<Placemark> destinationPlacemark =
await _geolocator.placemarkFromAddress(_destinationAddress);
if (startPlacemark != null && destinationPlacemark != null) {
// Use the retrieved coordinates of the current position,
// instead of the address if the start position is user's
// current position, as it results in better accuracy.
Position startCoordinates = _startAddress == _currentAddress
? Position(
latitude: _currentPosition.latitude,
longitude: _currentPosition.longitude)
: startPlacemark[0].position;
Position destinationCoordinates = destinationPlacemark[0].position;
// Start Location Marker
Marker startMarker = Marker(
markerId: MarkerId('$startCoordinates'),
position: LatLng(
startCoordinates.latitude,
startCoordinates.longitude,
),
infoWindow: InfoWindow(
title: 'Start',
snippet: _startAddress,
),
icon: BitmapDescriptor.defaultMarker,
);
// Destination Location Marker
Marker destinationMarker = Marker(
markerId: MarkerId('$destinationCoordinates'),
position: LatLng(
destinationCoordinates.latitude,
destinationCoordinates.longitude,
),
infoWindow: InfoWindow(
title: 'Destination',
snippet: _destinationAddress,
),
icon: BitmapDescriptor.defaultMarker,
);
// Adding the markers to the list
markers.add(startMarker);
markers.add(destinationMarker);
print('START COORDINATES: $startCoordinates');
print('DESTINATION COORDINATES: $destinationCoordinates');
Position _northeastCoordinates;
Position _southwestCoordinates;
// Calculating to check that
// southwest coordinate <= northeast coordinate
if (startCoordinates.latitude <= destinationCoordinates.latitude) {
_southwestCoordinates = startCoordinates;
_northeastCoordinates = destinationCoordinates;
} else {
_southwestCoordinates = destinationCoordinates;
_northeastCoordinates = startCoordinates;
}
// Accommodate the two locations within the
// camera view of the map
mapController.animateCamera(
CameraUpdate.newLatLngBounds(
LatLngBounds(
northeast: LatLng(
_northeastCoordinates.latitude,
_northeastCoordinates.longitude,
),
southwest: LatLng(
_southwestCoordinates.latitude,
_southwestCoordinates.longitude,
),
),
100.0,
),
);
// Calculating the distance between the start and the end positions
// with a straight path, without considering any route
// double distanceInMeters = await Geolocator().bearingBetween(
// startCoordinates.latitude,
// startCoordinates.longitude,
// destinationCoordinates.latitude,
// destinationCoordinates.longitude,
// );
await _createPolylines(startCoordinates, destinationCoordinates);
double totalDistance = 0.0;
// Calculating the total distance by adding the distance
// between small segments
for (int i = 0; i < polylineCoordinates.length - 1; i++) {
totalDistance += _coordinateDistance(
polylineCoordinates[i].latitude,
polylineCoordinates[i].longitude,
polylineCoordinates[i + 1].latitude,
polylineCoordinates[i + 1].longitude,
);
}
setState(() {
_placeDistance = totalDistance.toStringAsFixed(2);
print('DISTANCE: $_placeDistance km');
});
return true;
}
} catch (e) {
print(e);
}
return false;
}
// Formula for calculating distance between two coordinates
// https://stackoverflow.com/a/54138876/11910277
double _coordinateDistance(lat1, lon1, lat2, lon2) {
var p = 0.017453292519943295;
var c = cos;
var a = 0.5 -
c((lat2 - lat1) * p) / 2 +
c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p)) / 2;
return 12742 * asin(sqrt(a));
}
// Create the polylines for showing the route between two places
_createPolylines(Position start, Position destination) async {
polylinePoints = PolylinePoints();
PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
Secrets.API_KEY, // Google Maps API Key
PointLatLng(start.latitude, start.longitude),
PointLatLng(destination.latitude, destination.longitude),
travelMode: TravelMode.transit,
);
if (result.points.isNotEmpty) {
result.points.forEach((PointLatLng point) {
polylineCoordinates.add(LatLng(point.latitude, point.longitude));
});
}
PolylineId id = PolylineId('poly');
Polyline polyline = Polyline(
polylineId: id,
color: Colors.red,
points: polylineCoordinates,
width: 3,
);
polylines[id] = polyline;
}
@override
void initState() {
super.initState();
_getCurrentLocation();
}
@override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
return Container(
height: height,
width: width,
child: Scaffold(
key: _scaffoldKey,
body: Stack(
children: <Widget>[
// Map View
GoogleMap(
markers: markers != null ? Set<Marker>.from(markers) : null,
initialCameraPosition: _initialLocation,
myLocationEnabled: true,
myLocationButtonEnabled: false,
mapType: MapType.normal,
zoomGesturesEnabled: true,
zoomControlsEnabled: false,
polylines: Set<Polyline>.of(polylines.values),
onMapCreated: (GoogleMapController controller) {
mapController = controller;
},
),
// Show zoom buttons
SafeArea(
child: Padding(
padding: const EdgeInsets.only(left: 10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ClipOval(
child: Material(
color: Colors.blue[100], // button color
child: InkWell(
splashColor: Colors.blue, // inkwell color
child: SizedBox(
width: 50,
height: 50,
child: Icon(Icons.add),
),
onTap: () {
mapController.animateCamera(
CameraUpdate.zoomIn(),
);
},
),
),
),
SizedBox(height: 20),
ClipOval(
child: Material(
color: Colors.blue[100], // button color
child: InkWell(
splashColor: Colors.blue, // inkwell color
child: SizedBox(
width: 50,
height: 50,
child: Icon(Icons.remove),
),
onTap: () {
mapController.animateCamera(
CameraUpdate.zoomOut(),
);
},
),
),
)
],
),
),
),
// Show the place input fields & button for
// showing the route
SafeArea(
child: Align(
alignment: Alignment.topCenter,
child: Padding(
padding: const EdgeInsets.only(top: 10.0),
child: Container(
decoration: BoxDecoration(
color: Colors.white70,
borderRadius: BorderRadius.all(
Radius.circular(20.0),
),
),
width: width * 0.9,
child: Padding(
padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'Places',
style: TextStyle(fontSize: 20.0),
),
SizedBox(height: 10),
_textField(
label: 'Start',
hint: 'Choose starting point',
prefixIcon: Icon(Icons.looks_one),
suffixIcon: IconButton(
icon: Icon(Icons.my_location),
onPressed: () {
startAddressController.text = _currentAddress;
_startAddress = _currentAddress;
},
),
controller: startAddressController,
width: width,
locationCallback: (String value) {
setState(() {
_startAddress = value;
});
}),
SizedBox(height: 10),
_textField(
label: 'Destination',
hint: 'Choose destination',
prefixIcon: Icon(Icons.looks_two),
controller: destinationAddressController,
width: width,
locationCallback: (String value) {
setState(() {
_destinationAddress = value;
});
}),
SizedBox(height: 10),
Visibility(
visible: _placeDistance == null ? false : true,
child: Text(
'DISTANCE: $_placeDistance km',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
SizedBox(height: 5),
RaisedButton(
onPressed: (_startAddress != '' &&
_destinationAddress != '')
? () async {
setState(() {
if (markers.isNotEmpty) markers.clear();
if (polylines.isNotEmpty)
polylines.clear();
if (polylineCoordinates.isNotEmpty)
polylineCoordinates.clear();
_placeDistance = null;
});
_calculateDistance().then((isCalculated) {
if (isCalculated) {
_scaffoldKey.currentState.showSnackBar(
SnackBar(
content: Text(
'Distance Calculated Sucessfully'),
),
);
} else {
_scaffoldKey.currentState.showSnackBar(
SnackBar(
content: Text(
'Error Calculating Distance'),
),
);
}
});
}
: null,
color: Colors.red,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Show Route'.toUpperCase(),
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
),
),
],
),
),
),
),
),
),
// Show current location button
SafeArea(
child: Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.only(right: 10.0, bottom: 10.0),
child: ClipOval(
child: Material(
color: Colors.orange[100], // button color
child: InkWell(
splashColor: Colors.orange, // inkwell color
child: SizedBox(
width: 56,
height: 56,
child: Icon(Icons.my_location),
),
onTap: () {
mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(
_currentPosition.latitude,
_currentPosition.longitude,
),
zoom: 18.0,
),
),
);
},
),
),
),
),
),
),
],
),
),
);
}
}