import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'package:connectivity/connectivity.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:geolocator/geolocator.dart'; import 'package:get_it/get_it.dart'; import 'package:image_picker/image_picker.dart'; export 'package:flutter_map/src/geo/crs/crs.dart'; import 'package:latlong/latlong.dart'; import 'package:localstorage/localstorage.dart'; import 'package:photolink_beta/Model/CustomResponse/APIResponse.dart'; import 'package:photolink_beta/Model/MapModel/CoordintaionModel.dart'; import 'package:photolink_beta/Model/Trip/Trip.dart'; import 'package:photolink_beta/customWidget/loader.dart'; import 'package:photolink_beta/offlineMap/cache_tile_map.dart'; import 'package:photolink_beta/secreens/login_secreen.dart'; import 'package:photolink_beta/services/Map/CoodinationServices.dart'; import 'package:photolink_beta/services/Trip/CreateNewTrips.dart'; import 'package:photolink_beta/services/Trip/GetAllMytripe.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:fluttertoast/fluttertoast.dart'; const TripName_Cache ="TripName_Cache"; const TripDescription_Cache ="TripDescription_Cache"; const TripImage_Cache ="TripImage_Cache"; class photolinkmap extends StatefulWidget { final Trip trip; const photolinkmap({Key key, this.trip}) : super(key: key); @override _photolinkmapState createState() => _photolinkmapState(); } class _photolinkmapState extends State { Geolocator _locationTracker = Geolocator(); final LocalStorage storage = new LocalStorage('TripLocalPath'); final CreateNewTrips TripServices = CreateNewTrips(); Duration TimeIterval = const Duration(seconds: 10); Trip Current_trip; Position firstpostion; StreamSubscription _locationSubscription; Position currentPos; bool StartTraking=false; List points = [] ; List pointsPosted = [] ; List PloyLinepoints = [] ; GetAllMytripe get tripservices => GetIt.I(); APIResponse _tripresponse = new APIResponse(); bool isLoading = false; bool Connection = false; bool ConnectionServer = false; /********************************************************/ final CoodinationServices coodinationServices = CoodinationServices(); _photolinkmapState({Trip trip}); /********************************************************/ File _image; final picker = ImagePicker(); /********************************************************/ @override void initState() { super.initState(); _checkServerPath(); } Future checkConnectionServer() async { var connectivityResult = await (Connectivity().checkConnectivity()); if (connectivityResult == ConnectivityResult.none) { setState(() { ConnectionServer = false; }); } else { setState(() { ConnectionServer = true; }); //await _fetchTrips(); } } void checkConnection() async { var connectivityResult = await (Connectivity().checkConnectivity()); if (connectivityResult == ConnectivityResult.none) { setState(() { Connection = false; isLoading = true; }); checkConnection(); } else { setState(() { Connection = true; }); //await _fetchTrips(); if (!Connection) { setState(() { isLoading = false; }); } } } Widget DroobLoader(){ return Center( child: Container( child: ColorLoader1(), ), ); } _checkServerPath() async { final prefs = await SharedPreferences.getInstance(); await checkConnectionServer(); setState(() { isLoading=true; }); if(prefs.get(TripName_Cache)!=null && prefs.get(TripDescription_Cache)!=null && prefs.get(TripImage_Cache)!=null){ if(ConnectionServer){ CreateNewTrips controller = new CreateNewTrips(); final TripServices = await controller.NewTrip( new File(prefs.get(TripImage_Cache)), prefs.get(TripName_Cache), prefs.get(TripDescription_Cache)); if ( (TripServices.statusCode == 200 || TripServices.statusCode == 201) && TripServices.data.id != null) { setState(() { photolinkmap(trip: TripServices.data,); }); prefs.remove(TripName_Cache); prefs.remove(TripDescription_Cache); prefs.remove(TripImage_Cache); } else { throw (TripServices.errorMessage); } } } if(ConnectionServer && widget.trip.id!=null && widget.trip.path.isNotEmpty){ firstpostion = Position(longitude: double.parse(widget.trip.path.first.longitude), latitude: double.parse(widget.trip.path.first.latitude), timestamp:DateTime.parse( widget.trip.path.first.date), accuracy: null, altitude: null, heading: null, speed: null, speedAccuracy: null); currentPos = Position(longitude: double.parse(widget.trip.path.last.longitude), latitude: double.parse(widget.trip.path.last.latitude), timestamp:DateTime.parse( widget.trip.path.last.date), accuracy: null, altitude: null, heading: null, speed: null, speedAccuracy: null); for(CoordintaionModel cor in widget.trip.path){ LatLng serverpos =new LatLng(double.parse(cor.latitude),double.parse(cor.longitude)); PloyLinepoints.add(serverpos); } setState(() { StartTraking=true; }); } setState(() { isLoading=false; }); } Future getImage() async { final pickedFile = await picker.getImage(source: ImageSource.camera); setState(() { if (pickedFile != null) { _image = File(pickedFile.path); } else { print('No image selected.'); } }); } Future getImagefromGallery() async { final pickedFile = await picker.getImage(source: ImageSource.gallery); setState(() { _image =File(pickedFile.path); }); } void getCurrentPosition() async { try { await checkConnectionServer(); if (firstpostion == null) { var location = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.best,forceAndroidLocationManager: true); setState(() { currentPos = location; LatLng pos =new LatLng(currentPos.latitude,currentPos.longitude); LatLng currentPosition =new LatLng(currentPos.latitude,currentPos.longitude); CoordintaionModel coordintaionModel = new CoordintaionModel(latitude: pos.latitude.toString(),longitude: pos.longitude.toString()); points.add(coordintaionModel); LatLng existpos = new LatLng(double.parse(points.first.latitude), double.parse(points.first.longitude)); if(calcDistance(existpos,currentPosition)) PloyLinepoints.add(pos); firstpostion = location; StartTraking=true; }); } if (_locationSubscription != null) { _locationSubscription.cancel(); } _locationSubscription= Geolocator .getPositionStream( desiredAccuracy: LocationAccuracy.best, intervalDuration: TimeIterval) .listen((Position position) { setState(() { currentPos =position; LatLng pos =new LatLng(currentPos.latitude,currentPos.longitude); LatLng currentPosition =new LatLng(currentPos.latitude,currentPos.longitude); CoordintaionModel coordintaionModel = new CoordintaionModel(latitude: pos.latitude.toString(),longitude: pos.longitude.toString()); points.add(coordintaionModel); LatLng existpos = new LatLng(double.parse(points.first.latitude), double.parse(points.first.longitude)); if(calcDistance(existpos,currentPosition)) PloyLinepoints.add(pos); //modified 100 to 1 if(points.length>=100){ if(ConnectionServer){ sendDataToServer(); }else{ storage.setItem('Paths', points); } } }); } ); } on PlatformException catch (e) { if (e.code == 'PERMISSION_DENIED') { debugPrint("Permission denied"); } } } Future sendDataToServer() async{ setState(() { isLoading=true; }); final prefs = await SharedPreferences.getInstance(); var Paths = storage.getItem('Paths'); if(Paths){ for(CoordintaionModel cor in Paths){ var dt =new DateTime.now(); var result = await coodinationServices.addCoordination(cor.latitude, cor.longitude, widget.trip.id, cor.comment, dt.toString() , cor.provenance); print(result.statusCode); if(result.statusCode!=200 && result.statusCode!=201) break; } storage.deleteItem('Paths'); }else{ for(CoordintaionModel cor in points){ var dt =new DateTime.now(); var result = await coodinationServices.addCoordination(cor.latitude, cor.longitude, widget.trip.id, cor.comment, dt.toString() , cor.provenance); print(result.statusCode); if(result.statusCode!=200 && result.statusCode!=201) break; pointsPosted.add(cor); } for(CoordintaionModel cor in pointsPosted){ points.remove(cor); } pointsPosted.clear(); } setState(() { isLoading=false; }); } bool calcDistance(LatLng Pre , LatLng Succ){ double distance = Geolocator.distanceBetween(Pre.latitude,Pre.longitude,Succ.latitude,Succ.longitude); print(distance); //10meter to 1 meter if(distance>=1) return true; return false; } @override void dispose() { super.dispose(); } /*************Connection faild************/ Widget NonPosition(BuildContext context){ return Scaffold( body: Center( child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.add_alert, color: Colors.green, size: 20.0, ), Text( 'Please press START to begin', style: TextStyle( fontSize: 15.0, fontFamily: 'Almarai extra Bold', color: Colors.red, ), ), ], )), floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Container( height: 80.0, width: 80.0, child: Padding( padding: EdgeInsets.all(10.0), child: FloatingActionButton( backgroundColor: Colors.green, heroTag: 'start', child: Text( 'start ', textAlign: TextAlign.center, style: TextStyle(fontSize: 12), ), tooltip: 'start', onPressed: () => { getCurrentPosition(), }, ), )) ], ), ], ) ); } /**********************************************************************************/ Widget build(BuildContext context) { if (!StartTraking) {return NonPosition(context);} if(isLoading){return DroobLoader();} return Scaffold( body: Column( children: [ Flexible( child: new FlutterMap( options: new MapOptions( crs: const Epsg4326(), center: new LatLng(currentPos.latitude,currentPos.longitude), zoom: 18.0, ), layers: [ new TileLayerOptions( urlTemplate: "https://1.base.maps.ls.hereapi.com/maptile/2.1/maptile/newest/normal.day/{z}/{x}/{y}/256/png8?apiKey={YOUR_API_KEY}", additionalOptions: { 'YOUR_API_KEY': 'I-cZ1Tg_IznIIBIXtBQxWgfVHQ0cV9IllFLkwCVGsVs', }, tileProvider: const CachedTileProvider(), ), new PolylineLayerOptions( polylines: [ new Polyline( points: PloyLinepoints, strokeWidth: 5.0, color: Colors.red ) ], ), new MarkerLayerOptions( markers: [ new Marker( width: 40.0, height: 40.0, point: new LatLng(currentPos.latitude,currentPos.longitude), builder: (ctx) => new Container( child:Icon( Icons.add_location_rounded, color: Colors.black, size: 30.0, ), ), ), ], ), ], ), ), ], ), floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Container( height: 80.0, width: 80.0, child: Padding( padding: EdgeInsets.all(10.0), child: FloatingActionButton( backgroundColor: Colors.black, heroTag: 'picture', child: Text( ' picture ', textAlign: TextAlign.center, style: TextStyle( fontSize: 12, color: Colors.amber), ), tooltip: 'picture', onPressed: () => {}, ), )) ], ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Container( height: 80.0, width: 80.0, child: Padding( padding: EdgeInsets.all(10.0), child: FloatingActionButton( backgroundColor: Colors.amber, heroTag: 'Gallery', child: Text( ' Gallery ', textAlign: TextAlign.center, style: TextStyle( fontSize: 12, color: Colors.black), ), tooltip: 'Gallery', onPressed: () => {}, ), )) ], ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Container( height: 80.0, width: 80.0, child: Padding( padding: EdgeInsets.all(10.0), child: FloatingActionButton( backgroundColor: Colors.green, heroTag: 'start2', child: Text( 'start ', textAlign: TextAlign.center, style: TextStyle(fontSize: 12), ), tooltip: 'start2', onPressed: () => { getCurrentPosition(), }, ), )) ], ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Container( height: 80.0, width: 80.0, child: Padding( padding: EdgeInsets.all(10.0), child: FloatingActionButton( backgroundColor: Colors.amber, heroTag: 'pause', child: Text( 'pause ', textAlign: TextAlign.center, style: TextStyle(fontSize: 12), ), tooltip: 'pause', onPressed: () => {}, ), )) ], ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Container( height: 80.0, width: 80.0, child: Padding( padding: EdgeInsets.all(10.0), child: FloatingActionButton( backgroundColor: Colors.red, heroTag: 'end', child: Text( 'end ', textAlign: TextAlign.center, style: TextStyle(fontSize: 12), ), tooltip: 'end', onPressed: () => { }, ), )) ], ), ], ) ); } }