Files
rog_app/lib/pages/destination/destination_controller.dart

1953 lines
71 KiB
Dart
Raw Normal View History

2022-10-12 21:46:17 +05:30
import 'dart:io';
2023-12-06 11:16:17 +05:30
import 'dart:typed_data';
2022-10-12 21:46:17 +05:30
import 'package:camera_camera/camera_camera.dart';
2022-05-12 02:17:08 +05:30
import 'package:flutter/material.dart';
2022-12-27 18:52:37 +05:30
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_location_marker/flutter_map_location_marker.dart';
2023-12-06 11:16:17 +05:30
import 'package:geojson_vi/geojson_vi.dart';
2022-06-04 20:16:29 +05:30
import 'package:geolocator/geolocator.dart';
2022-05-12 02:17:08 +05:30
import 'package:get/get.dart';
2022-11-05 22:02:21 +05:30
import 'package:intl/intl.dart';
2022-06-14 14:37:59 +05:30
import 'package:latlong2/latlong.dart';
import 'package:permission_handler/permission_handler.dart';
2023-09-11 00:45:54 +05:30
import 'package:rogapp/main.dart';
2022-07-09 22:51:34 +05:30
import 'package:rogapp/model/destination.dart';
2023-10-31 14:12:48 +05:30
import 'package:rogapp/model/gps_data.dart';
2022-10-30 21:43:29 +05:30
import 'package:rogapp/pages/camera/camera_page.dart';
2024-05-25 11:05:02 +09:00
import 'package:rogapp/pages/camera/custom_camera_view.dart';
2022-05-12 02:17:08 +05:30
import 'package:rogapp/pages/index/index_controller.dart';
2024-08-05 03:08:12 +09:00
import 'package:rogapp/pages/team/team_controller.dart';
2022-05-12 02:17:08 +05:30
import 'package:rogapp/routes/app_pages.dart';
2024-02-04 19:14:41 +05:30
import 'package:rogapp/services/DatabaseService.dart';
2022-05-12 02:17:08 +05:30
import 'package:rogapp/services/destination_service.dart';
2022-10-19 08:53:17 +05:30
import 'package:rogapp/services/external_service.dart';
2022-12-27 18:52:37 +05:30
import 'package:rogapp/services/location_service.dart';
2022-05-18 19:09:26 +05:30
import 'package:rogapp/services/maxtrix_service.dart';
2022-12-27 18:52:37 +05:30
import 'package:rogapp/services/perfecture_service.dart';
2023-10-31 14:12:48 +05:30
import 'package:rogapp/utils/database_gps.dart';
2022-07-09 22:51:34 +05:30
import 'package:rogapp/utils/database_helper.dart';
2023-12-07 10:20:44 +05:30
import 'package:rogapp/utils/location_controller.dart';
2024-04-20 12:34:49 +09:00
import 'package:rogapp/widgets/bottom_sheet_new.dart';
2022-06-04 20:16:29 +05:30
import 'dart:async';
2022-05-12 02:17:08 +05:30
2022-11-05 22:02:21 +05:30
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
2023-11-29 10:20:19 +05:30
import 'package:rogapp/widgets/debug_widget.dart';
2023-09-04 22:46:53 +05:30
import 'package:shared_preferences/shared_preferences.dart';
2023-12-06 11:16:17 +05:30
import 'package:image_gallery_saver/image_gallery_saver.dart';
2024-04-24 11:30:38 +09:00
import 'package:rogapp/utils/const.dart';
import 'package:logger/logger.dart';
2022-06-14 14:37:59 +05:30
import 'package:rogapp/pages/permission/permission.dart';
2024-04-07 10:56:51 +09:00
// 目的地に関連する状態管理とロジックを担当するクラスです。
//
2022-05-12 02:17:08 +05:30
class DestinationController extends GetxController {
2024-04-07 10:56:51 +09:00
late LocationSettings locationSettings; // 位置情報の設定を保持する変数です。
2022-05-12 02:17:08 +05:30
2024-08-05 03:08:12 +09:00
//late TeamController teamController = TeamController();
//Timer? _GPStimer; // GPSタイマーを保持する変数です。
2023-10-08 19:13:14 +05:30
2024-04-07 10:56:51 +09:00
var destinationCount = 0.obs; // 目的地の数を保持するReactive変数です。
List<Destination> destinations = <Destination>[].obs; // 目的地のリストを保持するObservable変数です。
double currentLat = 0.0; // 現在の緯度と経度を保持する変数です。
2023-10-06 16:25:21 +05:30
double currentLon = 0.0;
double lastValidLat = 0.0; // 最後に中・強信号で拾ったGPS位置。
// ロゲ開始を屋内でやったら 0 のままなので、屋外で行うこと。
double lastValidLon = 0.0;
2024-04-07 10:56:51 +09:00
DateTime lastGPSCollectedTime = DateTime.now(); // 最後にGPSデータが収集された時刻を保持する変数です。
2022-05-25 21:00:10 +05:30
2024-04-07 10:56:51 +09:00
bool shouldShowBottomSheet = true; // ボトムシートを表示すべきかどうかを示すフラグです。
2023-12-18 09:22:18 +05:30
2024-04-07 10:56:51 +09:00
static bool gps_push_started = false; // ゲームの状態を示す静的変数です。
2023-11-27 14:57:25 +05:30
static bool game_started = false;
static bool ready_for_goal = false;
2023-11-27 13:22:18 +05:30
2024-04-07 10:56:51 +09:00
bool skip_10s = false; // 10秒間のスキップフラグを示す変数です。
2023-01-26 23:30:48 +05:30
2024-04-07 10:56:51 +09:00
List<Destination> currentSelectedDestinations = <Destination>[].obs; // 現在選択されている目的地のリストを保持するObservable変数です。
2022-07-10 23:50:43 +05:30
2024-04-07 10:56:51 +09:00
var isInCheckin = false.obs; // ゲームの状態を示すReactive変数です。
2023-10-06 16:25:21 +05:30
var isInRog = false.obs;
var isAtStart = false.obs;
var isAtGoal = false.obs;
var isPhotoShoot = false.obs;
2024-04-07 10:56:51 +09:00
DateTime lastGoalAt = DateTime.now().subtract(const Duration(days: 1)); // 最後にゴールした時刻を保持する変数です。
2022-10-30 21:43:29 +05:30
//List<Rogaining> rogainings = <Rogaining>[].obs;
2022-10-12 21:46:17 +05:30
2024-04-07 10:56:51 +09:00
bool checkingIn = false; // チェックイン中かどうかを示すフラグです。
var isGpsSelected = true.obs; // GPSが選択されているかどうかを示すReactive変数です。
BuildContext? context; // ビルドコンテキストを保持する変数です。
2022-06-14 14:37:59 +05:30
2024-04-07 10:56:51 +09:00
List<String> gps = <String>["-- stating --"].obs; // GPSと位置情報の許可に関する情報を保持するObservable変数です。
2022-07-20 15:57:40 +05:30
List<String> locationPermission = <String>[" -- starting -- "].obs;
2024-04-07 10:56:51 +09:00
var travelMode = 0.obs; // 移動モードを保持するReactive変数です。
bool skipGps = false; // GPSをスキップするかどうかを示すフラグです。
bool okToUseGPS = false; // 最新のGPS情報を使用して良いかを示すフラグ。
2024-04-07 10:56:51 +09:00
Map<String, dynamic> matrix = {}; // 行列データを保持する変数です。
final photos = <File>[].obs; // 写真のリストを保持するReactive変数です。
final IndexController indexController = Get.find<IndexController>(); // IndexControllerのインスタンスを保持する変数です。
final LocationController locationController = Get.put(LocationController()); // LocationControllerのインスタンスを保持する変数です。
final DatabaseService dbService = DatabaseService(); // DatabaseServiceのインスタンスを保持する変数です。
2022-09-22 20:36:56 +05:30
2024-04-07 10:56:51 +09:00
int _start = 0; // 開始時刻を保持する変数です。
int chekcs = 0; // チェックポイントの数を保持する変数です。
2024-04-07 10:56:51 +09:00
var rogainingCounted = false.obs; // ロゲイニングがカウントされたかどうかを示すReactive変数です。
// destinationController.rogainingCountedは、現在のロゲイニングセッションでポイントがカウントされたかどうかを管理するフラグです。
//
// このフラグは以下のような状況で使用されます:
//
// ロゲイニングを開始したとき、rogainingCountedはfalseに初期化されます。これは、まだポイントがカウントされていないことを示します。
// チェックポイントに到着し、チェックインが成功したとき、rogainingCountedはtrueに設定されます。これは、そのセッションでポイントがカウントされたことを示します。
// ロゲイニングを終了したとき、rogainingCountedは再びfalseに設定されます。これは、次のセッションに備えてフラグをリセットするためです。
// このフラグは、主に以下の目的で使用されます:
//
// ゴール地点でのロジックの制御rogainingCountedがtrueの場合、つまりポイントがカウントされている場合にのみ、ゴール処理を実行できます。
// UI の更新rogainingCountedの状態に基づいて、適切なメッセージやボタンを表示することができます。
bool isMapControllerReady = false;
LatLng lastValidGPSLocation = LatLng(0, 0);
DateTime lastGPSDataReceivedTime = DateTime.now();
DateTime lastPopupShownTime = DateTime.now().subtract(Duration(minutes: 10));
bool isPopupShown = false;
bool hasReceivedGPSData = true;
2022-10-30 21:43:29 +05:30
var isCheckingIn = false.obs; // チェックイン操作中はtrueになり、重複してポップアップが出ないようにするもの。
2024-05-25 11:05:02 +09:00
var isRouteShowing = false.obs; // ルートが表示されているかどうかを示すReactive変数
/*
2024-04-07 10:56:51 +09:00
//==== Akira .. GPS信号シミュレーション用 ===== ここから、2024-4-5
//
bool kDebugMode = true;
// シミュレーションモードのフラグ
2024-04-07 23:35:00 +09:00
RxBool isSimulationMode = RxBool(true);
2024-04-07 10:56:51 +09:00
// シミュレーションモードを切り替えるための関数
void toggleSimulationMode(bool value) {
isSimulationMode.value = value;
}
2022-05-12 02:17:08 +05:30
// 現在位置の取得メソッドを追加
LatLng getCurrentLocation() {
return LatLng(lastValidLat, lastValidLon);
}
2024-04-07 10:56:51 +09:00
//
// GPS信号の強弱を判断するメソッドを追加します。
//
String getGpsSignalStrength() {
// デバッグモードかつシミュレーションモードの場合は、シミュレートされた信号強度を返す
2024-04-07 23:35:00 +09:00
print("kDebugMode : ${kDebugMode}, isSimulationMode : ${isSimulationMode.value}");
2024-04-07 10:56:51 +09:00
if (kDebugMode && isSimulationMode.value) {
return locationController.getSimulatedSignalStrength();
}
2022-10-12 21:46:17 +05:30
2024-04-07 10:56:51 +09:00
// 通常モードの場合は、実際の信号強度を返す
final accuracy = locationController.currentPosition.value?.accuracy ?? double.infinity;
if (accuracy <= 10) {
return 'high';
} else if (accuracy <= 30) {
return 'medium';
} else {
return 'low';
}
}
2022-05-12 02:17:08 +05:30
2024-04-07 10:56:51 +09:00
//
//==== Akira .. GPS信号シミュレーション用 ======= ここまで
*/
2022-10-12 21:46:17 +05:30
2024-08-05 03:08:12 +09:00
2024-05-25 11:05:02 +09:00
// ルートをクリアする関数です。
void clearRoute() {
indexController.routePoints.clear();
indexController.routePointLenght.value = 0;
isRouteShowing.value = false;
}
void showGPSDataNotReceivedPopup() {
if (Get.context != null) {
Get.dialog(
AlertDialog(
title: Text('GPS信号が受信できません'),
content: Text('GPS信号が受信できる場所に移動してください。'),
actions: [
TextButton(
onPressed: () => Get.back(),
child: Text('OK'),
),
],
),
);
} else {
// Get.contextがnullの場合の処理を追加
print('GPS signal not received, but context is null');
}
}
// 最後に有効なGPSデータを受け取ってから10分以上経過している場合にのみメッセージを表示するようにします。
//
void checkGPSDataReceived() {
if (!hasReceivedGPSData) {
//debugPrint("GPS信号を全く受信していない。");
if (!isPopupShown) {
// ポップアップしていない。
showGPSDataNotReceivedPopup();
lastPopupShownTime = DateTime.now();
isPopupShown = true;
}
} else {
if (DateTime.now().difference(lastGPSDataReceivedTime).inSeconds >= 600) {
// 前回GPS信号を受信してから10分経過。
if (!isPopupShown && DateTime.now().difference(lastPopupShownTime).inMinutes >= 3) {
// 前回ポップアップしてから3分経過してなければ
showGPSDataNotReceivedPopup();
lastPopupShownTime = DateTime.now();
isPopupShown = true;
}
} else {
isPopupShown = false;
}
}
}
2024-04-07 10:56:51 +09:00
// 日時をフォーマットされた文字列に変換する関数です。
//
2023-09-04 22:46:53 +05:30
String getFormatedTime(DateTime datetime) {
return DateFormat('yyyy-MM-dd HH:mm:ss').format(datetime);
2022-11-14 22:22:41 +05:30
}
2024-04-07 10:56:51 +09:00
// 追加Akira 2024-4-5
// GPS信号の精度が一定値以上の場合、GPS信号が弱いと判断する
//
bool isGpsSignalWeak() {
final accuracy = locationController.currentPosition.value?.accuracy;
if (accuracy == null) {
return true; // 位置情報が取得できていない場合、GPS信号が弱いと見なす
}
return accuracy > 60;
2024-04-07 10:56:51 +09:00
//return locationController.currentPosition.value?.accuracy ?? double.infinity > 50;
}
//
2023-12-06 11:16:17 +05:30
Destination festuretoDestination(GeoJSONFeature fs) {
GeoJSONMultiPoint mp = fs.geometry as GeoJSONMultiPoint;
LatLng pt = LatLng(mp.coordinates[0][1], mp.coordinates[0][0]);
2023-09-04 22:46:53 +05:30
//print("----- ${indexController.currentFeature[0].properties} -----");
return Destination(
name: fs.properties!["location_name"],
2023-09-15 12:05:05 +05:30
sub_loc_id: fs.properties!["sub_loc_id"],
2023-09-04 22:46:53 +05:30
address: fs.properties!["address"],
phone: fs.properties!["phone"],
email: fs.properties!["email"],
webcontents: fs.properties!["webcontents"],
videos: fs.properties!["videos"],
category: fs.properties!["category"],
series: 1,
lat: pt.latitude,
lon: pt.longitude,
location_id: fs.properties!["location_id"],
list_order: 1,
photos: fs.properties!["photos"],
checkin_radious: fs.properties!["checkin_radius"],
auto_checkin: fs.properties!["auto_checkin"] == true ? 1 : 0,
cp: fs.properties!["cp"],
checkin_point: fs.properties!["checkin_point"],
buy_point: fs.properties!["buy_point"],
selected: false,
checkedin: false,
2023-11-20 14:01:28 +05:30
hidden_location: fs.properties!["hidden_location"] == true ? 1 : 0,
tags: fs.properties!["tags"]);
2022-10-30 21:43:29 +05:30
}
2024-04-07 10:56:51 +09:00
// 指定された目的地の位置情報に基づいてタイマーを開始する関数です。
2024-04-20 12:34:49 +09:00
// CP情報(fs)と現在位置からCPまでの距離distance を引数として渡します。
2024-04-07 10:56:51 +09:00
//
2023-12-06 11:16:17 +05:30
Future<void> startTimerLocation(GeoJSONFeature fs, double distance) async {
2023-10-08 19:13:14 +05:30
//print("---- in startTimer ----");
2023-10-06 16:25:21 +05:30
// print("---- is in rog is $is_in_rog ----");
2024-04-20 12:34:49 +09:00
2023-08-16 14:53:32 +05:30
double checkinRadious = fs.properties!['checkin_radius'] ?? double.infinity;
2024-04-20 12:34:49 +09:00
// CPのcheckin_radiusを取得し、checkinRadius に代入。値がなければinfinityとする。
2023-09-12 12:57:45 +05:30
if (checkinRadious >= distance) {
2024-04-20 12:34:49 +09:00
// checkinRadious以内に入ったら、
2022-11-01 23:47:35 +05:30
indexController.currentFeature.clear();
2024-04-20 12:34:49 +09:00
// indexController.currentFeatureを空にします。
2022-10-30 21:43:29 +05:30
Destination d = festuretoDestination(fs);
2024-04-20 12:34:49 +09:00
// festuretoDestination(fs)を呼び出し、GeoJSONFeatureオブジェクトfsからDestinationオブジェクトdを作成します。
2023-10-06 16:25:21 +05:30
// print("----- destination lenght is ${destinations.length} -----");
2024-04-20 12:34:49 +09:00
2022-11-01 23:47:35 +05:30
indexController.currentFeature.add(fs);
2024-04-20 12:34:49 +09:00
// indexController.currentFeatureにfsを追加します。
2023-10-06 16:25:21 +05:30
//print("---- before calling startTimer ----");
2023-09-14 00:08:53 +05:30
await startTimer(d, distance);
2024-04-20 12:34:49 +09:00
// startTimer(d, distance)を非同期で呼び出し、その完了を待機します。
2023-09-12 12:57:45 +05:30
return;
}
2022-10-30 21:43:29 +05:30
}
2024-04-07 10:56:51 +09:00
// 指定された目的地に対してタイマーを開始する関数です。
// 目的地の位置情報を取得し、チェックイン半径内にいるかどうかを確認します。
// 写真撮影モードの場合は、ボトムシートを表示して写真撮影を行います。
// 目的地がデータベースに存在しない場合は、新しい目的地としてデータベースに挿入します。
// 目的地に応じて、チェックイン、ゴール、買い物ポイントの処理を行います。
//
// 2024-4-8 akira: GPS信号が弱い場合でも、最後に取得した位置情報を使用してチェックインやゴールの処理を続行できるようになります。また、チェックインやゴールの処理では、GPS信号の精度チェックを緩和することで、GPS信号が弱い場合でもボタンを押せるようになります。
//
// 要検討:エラーが発生した場合のエラーハンドリングを追加し、適切なメッセージを表示することを検討してください。
//
2024-04-20 12:34:49 +09:00
// 引数CPオブジェクトと現在地からCPまでの距離を渡す。
//
2023-09-14 00:08:53 +05:30
Future<void> startTimer(Destination d, double distance) async {
2023-11-27 14:57:25 +05:30
//print("=== passed dest is ${d.location_id} ${d.checkedin} ====");
2023-10-06 16:25:21 +05:30
skipGps = true;
2024-04-20 12:34:49 +09:00
//debugPrint("---- in startTimer ----");
2023-09-08 21:19:12 +05:30
DatabaseHelper db = DatabaseHelper.instance;
List<Destination> ds = await db.getDestinationByLatLon(d.lat!, d.lon!);
2024-04-20 12:34:49 +09:00
//指定位置のオブジェクトのリストを取得。
2023-09-14 00:08:53 +05:30
Destination? dss;
2023-09-14 22:53:51 +05:30
if (ds.isNotEmpty) {
2024-04-20 12:34:49 +09:00
dss = ds.first; // 取得したリストが空でない場合、dss変数に最初の要素を代入します。
2023-09-14 00:08:53 +05:30
}
2023-09-08 21:19:12 +05:30
2024-04-20 12:34:49 +09:00
// 変数を計算
double checkinRadious = d.checkin_radious ?? double.infinity; // 反応半径
bool autoCheckin = d.auto_checkin == 0 ? false : true; // 自動チェックイン
bool buyPoint = dss != null && dss.buy_point != null && dss.buy_point! > 0 // 買い物ポイント
2023-09-14 22:53:51 +05:30
? true
: false;
2024-04-20 12:34:49 +09:00
bool buyPointImageAdded = // 買い物画像
2023-09-14 22:53:51 +05:30
dss != null && dss.buypoint_image != null ? true : false;
2024-04-20 12:34:49 +09:00
bool buyPointCanceled = // 買い物キャンセル
2023-10-06 16:25:21 +05:30
dss != null && dss.buy_point != null && dss.buy_point == 0
? true
: false;
2024-04-20 12:34:49 +09:00
bool locationAlreadyCheckedIn = // チェックイン済みか
2023-10-06 16:25:21 +05:30
ds.isNotEmpty && ds[0].checkedin == true ? true : false;
2024-04-20 12:34:49 +09:00
bool isuserLoggedIn = indexController.currentUser.isNotEmpty ? true : false; // ログイン済みか
/*
// スタートとゴールは除外
debugPrint("startTimer CP=${d.cp}");
if (d.cp == -1 || d.cp == 0 || d.cp == -2) {
skipGps = false;
return;
}
*/
2024-04-20 12:34:49 +09:00
// 初期化。GPS信号が強くても弱くても
if (checkinRadious >= distance || checkinRadious == -1) {
2022-10-30 21:43:29 +05:30
//currentSelectedDestinations.add(d);
2024-04-20 12:34:49 +09:00
// 目的地として登録する。
//debugPrint("目的地の初期化");
2022-10-30 21:43:29 +05:30
indexController.currentDestinationFeature.clear();
indexController.currentDestinationFeature.add(d);
2023-10-06 16:25:21 +05:30
// print(
// "---- checked in as ${indexController.currentDestinationFeature[0].checkedin.toString()} ----");
2023-09-04 22:46:53 +05:30
} else {
2024-04-20 12:34:49 +09:00
// ここには来ないのでは?
debugPrint("検出範囲外...");
2024-04-07 10:56:51 +09:00
// GPS信号が弱い場合でも、チェックインやゴールの処理を続行する
// comment out by Akira, 2024-4-5
// skipGps = false;
// return;
// GPS信号が弱い場合、最後に取得した高いまたは中程度の位置情報を使用
if (okToUseGPS) {
double lastValidDistance = Geolocator.distanceBetween(
lastValidLat, lastValidLon,
d.lat!, d.lon!
);
/*
double lastValidDistance = distance.as(
LengthUnit.Meter,
LatLng(lastValidLat, lastValidLon),
LatLng(d.lat!, d.lon!),
);
*/
2024-04-20 12:34:49 +09:00
if (checkinRadious >= lastValidDistance || checkinRadious == -1) { // 反応半径内か、距離無視CPなら
indexController.currentDestinationFeature.clear();
indexController.currentDestinationFeature.add(d);
} else {
skipGps = false;
return;
}
} else {
skipGps = false;
return;
}
2022-10-30 21:43:29 +05:30
}
2024-04-20 12:34:49 +09:00
if (isPhotoShoot.value == true) { // 写真撮影するなら ... isPhotoShoot=True にしてる場所がない。
debugPrint("isPhotoShoot.value == true ... will camera popup");
photos.clear(); // まず既存の写真をクリア
if (shouldShowBottomSheet) { // ボトムシートを使うべきなら
2023-12-18 09:22:18 +05:30
shouldShowBottomSheet = false;
2024-04-20 12:34:49 +09:00
if (d.cp == -1) return; // CPは開始点なら戻る。
// カメラページをポップアップ
2023-12-18 09:22:18 +05:30
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(destination: d)))
.whenComplete(() {
shouldShowBottomSheet = true;
skipGps = false;
chekcs = 0;
isInCheckin.value = false;
});
}
2022-11-05 22:02:21 +05:30
return;
}
2024-04-20 12:34:49 +09:00
// 写真撮影モードでない場合
2023-09-04 22:46:53 +05:30
if (ds.isEmpty) {
2024-04-20 12:34:49 +09:00
debugPrint("* 目的地がない場合 ==> 検知半径=-1の場合");
2023-10-06 16:25:21 +05:30
// print("----- in location popup cp - ${d.cp}----");
if ((d.cp == -1 || d.cp==0 ) && DateTime.now().difference(lastGoalAt).inHours >= 10) {
2024-04-20 12:34:49 +09:00
debugPrint("**1: 開始CPで、最後にゴールしてから時間経過していれば、");
2022-11-01 23:47:35 +05:30
chekcs = 1;
2022-10-30 21:43:29 +05:30
//start
2023-10-06 16:25:21 +05:30
// print("~~~~ calling start ~~~~");
2024-04-20 12:34:49 +09:00
print("---- in start -----");
2024-04-24 11:30:38 +09:00
chekcs = 1; // スタート地点で前のゴールから24時間経過
2024-04-20 12:34:49 +09:00
2023-10-06 16:25:21 +05:30
isInCheckin.value = true;
isAtStart.value = true;
2023-12-18 09:22:18 +05:30
if (shouldShowBottomSheet) {
2024-04-24 11:30:38 +09:00
shouldShowBottomSheet = false; // bottom_sheet を起動させない。
2024-04-20 12:34:49 +09:00
Widget bottomSheet = BottomSheetNew(destination: d);
2023-12-18 09:22:18 +05:30
await showModalBottomSheet(
constraints:
2024-04-24 11:30:38 +09:00
BoxConstraints.loose(Size(Get.width, Get.height * 0.85)),
2023-12-18 09:22:18 +05:30
context: Get.context!,
isScrollControlled: true,
builder: ((context) => bottomSheet)
).whenComplete(() {
2024-04-20 12:34:49 +09:00
shouldShowBottomSheet = true; // bottom_sheet 起動許可
2023-12-18 09:22:18 +05:30
skipGps = false;
2024-04-24 11:30:38 +09:00
chekcs = 0; // ボトムシートモード=1,
2023-12-18 09:22:18 +05:30
isAtStart.value = false;
isInCheckin.value = false;
});
}
2023-09-14 00:08:53 +05:30
return;
2024-04-24 11:30:38 +09:00
// 以下の条件分岐を追加
} else if (ds.isNotEmpty && ds[0].checkedin == true) {
// 目的地がDBに存在し、すでにチェックインしている場合は自動ポップアップを表示しない
debugPrint("チェックイン済み");
return;
2024-04-20 12:34:49 +09:00
2024-03-08 15:31:49 +05:30
} else if (isInRog.value == true &&
indexController.rogMode.value == 1 &&
2024-04-20 12:34:49 +09:00
(locationAlreadyCheckedIn==null || locationAlreadyCheckedIn==false) &&
d.cp != -1 && d.cp != 0 && d.cp != -2) {
debugPrint("**2: 標準CP まだチェックインしていない。");
2023-10-06 16:25:21 +05:30
// print("----- in location popup checkin cp - ${d.cp}----");
2024-04-20 12:34:49 +09:00
chekcs = 2; // 標準CP
2023-10-06 16:25:21 +05:30
isInCheckin.value = true;
2023-12-18 09:22:18 +05:30
if (shouldShowBottomSheet) {
shouldShowBottomSheet = false;
2024-04-20 12:34:49 +09:00
Widget bottomSheet = BottomSheetNew(destination: d);
2023-12-18 09:22:18 +05:30
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => bottomSheet)
).whenComplete(() {
2023-12-18 09:22:18 +05:30
shouldShowBottomSheet = true;
skipGps = false;
chekcs = 0;
isInCheckin.value = false;
});
}
2023-09-14 00:08:53 +05:30
return;
2022-10-30 21:43:29 +05:30
}
}
2024-04-20 12:34:49 +09:00
// 以降、検知範囲にある場合。
//debugPrint("検知範囲にある場合");
2023-10-06 16:25:21 +05:30
// print("---- location checkin radious ${d.checkin_radious} ----");
// print("---- already checked in $locationAlreadyCheckedIn ----");
2024-01-14 23:01:09 +05:30
if ((checkinRadious >= distance || checkinRadious == -1) &&
2023-09-04 22:46:53 +05:30
locationAlreadyCheckedIn == false &&
isInRog.value == true &&
!isCheckingIn.value) {
2024-04-20 12:34:49 +09:00
debugPrint("* 検知範囲または距離無視CPで、ゲーム中でまだチェックインしていない。");
if (autoCheckin) { // 自動チェックインなら
2023-10-06 16:25:21 +05:30
if (!checkingIn) {
2024-04-20 12:34:49 +09:00
debugPrint("** 自動チェックインの場合");
2023-10-06 16:25:21 +05:30
//print(
// "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ make checkin ${d.sub_loc_id}@@@@@@@@@@@");
2024-04-20 12:34:49 +09:00
makeCheckin(d, true, ""); // チェックインして
if (d.cp != -1 && d.cp != -2 && d.cp != 0 ) {
rogainingCounted.value = true; // ゴール用チェックイン済み
2022-10-30 21:43:29 +05:30
}
2023-10-06 16:25:21 +05:30
skipGps = false;
2022-10-30 21:43:29 +05:30
}
2024-04-20 12:34:49 +09:00
return; // 戻る
2023-09-04 22:46:53 +05:30
} else {
2024-04-20 12:34:49 +09:00
// それ以外
debugPrint("* 自動チェックイン以外の場合");
2023-10-06 16:25:21 +05:30
// print("--- hidden loc ${d.hidden_location} ----");
2023-09-04 22:46:53 +05:30
// ask for checkin
if (d.hidden_location != null &&
2024-04-20 12:34:49 +09:00
d.hidden_location == 0 && // 隠しCPフラグ==0 ... 通常CP
2023-10-06 16:25:21 +05:30
isInRog.value == true &&
2024-04-20 12:34:49 +09:00
d.cp != -1 && d.cp != -2 && d.cp != 0) {
// 隠しCPの場合、
debugPrint("**3 通常CPの場合");
2023-09-04 22:46:53 +05:30
chekcs = 3;
2023-10-06 16:25:21 +05:30
isInCheckin.value = true;
isCheckingIn.value = true;
2023-09-04 22:46:53 +05:30
photos.clear();
2023-10-06 16:25:21 +05:30
// print("--- calling checkin ---");
2023-12-18 09:22:18 +05:30
if (shouldShowBottomSheet) {
shouldShowBottomSheet = false;
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(
destination: d,
))).whenComplete(() {
shouldShowBottomSheet = true;
skipGps = false;
rogainingCounted.value = true;
chekcs = 0;
isInCheckin.value = false;
isCheckingIn.value = false;
2023-12-18 09:22:18 +05:30
});
}
2023-09-14 00:08:53 +05:30
return;
2024-04-20 12:34:49 +09:00
} else if (isInRog.value == true &&
(locationAlreadyCheckedIn==null || locationAlreadyCheckedIn==false) &&
d.cp != -1 && d.cp != -2 && d.cp != 0) {
// 通常CP
debugPrint("**4 通常CP以外の場合....どんな場合?");
2023-09-04 22:46:53 +05:30
chekcs = 4;
2023-10-06 16:25:21 +05:30
isInCheckin.value = true;
2023-12-18 09:22:18 +05:30
if (shouldShowBottomSheet) {
shouldShowBottomSheet = false;
2024-04-20 12:34:49 +09:00
Widget bottomSheet = BottomSheetNew(destination: d);
2023-12-18 09:22:18 +05:30
await showMaterialModalBottomSheet(
expand: true,
context: Get.context!,
backgroundColor: Colors.transparent,
builder: (context) => bottomSheet
).whenComplete(() {
2023-12-18 09:22:18 +05:30
shouldShowBottomSheet = true;
skipGps = false;
chekcs = 0;
isInCheckin.value = false;
});
}
2023-09-14 00:08:53 +05:30
return;
2023-09-04 22:46:53 +05:30
}
}
2024-01-14 23:01:09 +05:30
} else if ((checkinRadious >= distance || checkinRadious == -1) &&
2023-09-14 00:08:53 +05:30
locationAlreadyCheckedIn == true &&
buyPointImageAdded == false &&
ds.isNotEmpty &&
buyPoint == true &&
2023-09-15 17:19:26 +05:30
buyPointCanceled == false &&
2023-10-06 16:25:21 +05:30
isInRog.value == true) {
2024-04-20 12:34:49 +09:00
// チェックイン後で買い物ポイントの場合。
debugPrint("**5 チェックイン後で買い物ポイントの場合");
2023-09-14 00:08:53 +05:30
chekcs = 5;
2023-10-06 16:25:21 +05:30
isInCheckin.value = true;
2023-09-14 00:08:53 +05:30
photos.clear();
2023-10-06 16:25:21 +05:30
//print("--- open buy point $buyPointImageAdded ${d.buypoint_image} ----");
2023-12-18 09:22:18 +05:30
if (shouldShowBottomSheet) {
shouldShowBottomSheet = false;
2024-04-20 12:34:49 +09:00
if (d.cp == -1 && d.cp != -2 && d.cp != 0) return;
2023-12-18 09:22:18 +05:30
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(
destination: d,
buyPointPhoto: true,
dbDest: ds.first,
))).whenComplete(() {
2023-12-18 09:22:18 +05:30
shouldShowBottomSheet = true;
skipGps = false;
rogainingCounted.value = true;
chekcs = 0;
isInCheckin.value = false;
});
}
2023-09-14 00:08:53 +05:30
return;
2023-09-04 22:46:53 +05:30
}
2023-10-06 16:25:21 +05:30
// print("---- cp --- ${d.cp} -----");
// print("--- at goal $is_at_goal ---");
// print("--- rog counted $rogaining_counted ---");
// print("--- loc already checked in $locationAlreadyCheckedIn ---");
// print(
// "==== date diff is ${DateTime.now().difference(last_goal_at).inHours} ====");
2023-09-04 22:46:53 +05:30
if (isuserLoggedIn &&
2024-04-24 11:30:38 +09:00
(d.cp == -2 || d.cp == 0 || d.cp == -1 ) && // Goal CP
2023-09-04 22:46:53 +05:30
locationAlreadyCheckedIn &&
skip_10s == false) {
//check for rogaining
2023-10-06 16:25:21 +05:30
if (isAtGoal.value == false && rogainingCounted.value) {
2023-09-04 22:46:53 +05:30
//goal
2023-10-06 16:25:21 +05:30
//print("---- in goal -----");
2024-04-20 12:34:49 +09:00
debugPrint("**5 ゴールで時計撮影の場合");
chekcs = 5; // Goal 時計撮影
2023-10-06 16:25:21 +05:30
isAtGoal.value = true;
2023-09-04 22:46:53 +05:30
photos.clear();
2023-12-18 09:22:18 +05:30
if (shouldShowBottomSheet) {
shouldShowBottomSheet = false;
if (d.cp == -1) return;
2023-12-18 09:22:18 +05:30
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(
destination: d,
))).whenComplete(() {
shouldShowBottomSheet = true;
skipGps = false;
chekcs = 0;
isAtGoal.value = false;
});
}
2023-09-14 00:08:53 +05:30
return;
2024-04-20 12:34:49 +09:00
2023-10-06 16:25:21 +05:30
} else if (isInRog.value == false &&
indexController.rogMode.value == 1 &&
DateTime.now().difference(lastGoalAt).inHours >= 10) {
2023-09-04 22:46:53 +05:30
//start
2023-10-06 16:25:21 +05:30
//print("---- in start -----");
2024-04-20 12:34:49 +09:00
debugPrint("**5 スタートの場合で最後のゴールから10時間経過している場合");
2024-04-20 12:34:49 +09:00
chekcs = 6; // start point
2023-10-06 16:25:21 +05:30
isAtStart.value = true;
2023-12-18 09:22:18 +05:30
if (shouldShowBottomSheet) {
shouldShowBottomSheet = false;
2024-04-20 12:34:49 +09:00
if (d.cp != -1 && d.cp != 0) return;
Widget bottomSheet = BottomSheetNew(destination: d);
2023-12-18 09:22:18 +05:30
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => bottomSheet)
).whenComplete(() {
2023-12-18 09:22:18 +05:30
shouldShowBottomSheet = true;
//print("----- finished start -------");
skipGps = false;
chekcs = 0;
isAtStart.value = false;
});
}
2023-09-14 00:08:53 +05:30
return;
2023-09-04 22:46:53 +05:30
}
}
2023-10-06 16:25:21 +05:30
//print("==== _chekcs $chekcs ====");
2023-09-04 22:46:53 +05:30
if (chekcs == 0) {
2024-04-20 12:34:49 +09:00
//debugPrint("いずれにも当てはまらないので、処理スキップ");
2023-10-06 16:25:21 +05:30
skipGps = false;
2023-09-04 22:46:53 +05:30
}
2023-09-12 12:57:45 +05:30
return;
2022-10-30 21:43:29 +05:30
}
2024-04-07 10:56:51 +09:00
// ロゲイニングをリセットする関数です。
// ゲームの状態をリセットし、データベースからデータを削除します。
//
2024-03-08 18:19:18 +05:30
Future<void> resetRogaining({bool isgoal = false}) async {
2023-10-06 16:25:21 +05:30
//print("----- resetting --------");
2022-11-08 15:29:42 +05:30
2023-10-06 16:25:21 +05:30
isInCheckin.value = false;
isInRog.value = false;
isAtStart.value = false;
isAtGoal.value = false;
isGpsSelected.value = true;
skipGps = false;
ready_for_goal = false;
2022-10-30 21:43:29 +05:30
_start = 0;
2022-11-01 23:47:35 +05:30
chekcs = 0;
2023-10-06 16:25:21 +05:30
rogainingCounted.value = false;
2023-01-26 20:09:33 +05:30
DatabaseHelper db = DatabaseHelper.instance;
2024-03-08 18:19:18 +05:30
if (isgoal == false) {
await db.deleteAllDestinations();
await db.deleteAllRogaining();
}
2023-10-06 16:25:21 +05:30
int? latgoal = await db.latestGoal();
if (latgoal != null) {
lastGoalAt = DateTime.fromMicrosecondsSinceEpoch(latgoal);
//print("===== last goal : $last_goal_at =====");
2023-01-31 10:14:23 +05:30
}
2024-02-04 19:14:41 +05:30
dbService.updateDatabase();
2023-09-12 22:08:03 +05:30
}
2024-04-07 10:56:51 +09:00
// すべての目的地を削除する関数です。
//
2023-09-12 22:08:03 +05:30
void deleteAllDestinations() {
DatabaseHelper db = DatabaseHelper.instance;
2023-09-04 22:46:53 +05:30
db.deleteAllDestinations().then((value) {
2023-10-06 16:25:21 +05:30
populateDestinations();
2023-01-26 20:09:33 +05:30
});
2022-10-30 21:43:29 +05:30
}
2024-04-07 10:56:51 +09:00
// カメラを開いて写真を撮影する関数です。
//
2023-09-14 22:53:51 +05:30
void openCamera(BuildContext context, Destination? destination) {
2022-10-12 21:46:17 +05:30
photos.clear();
Navigator.push(
context,
MaterialPageRoute(
2024-05-25 11:05:02 +09:00
builder: (_) => CustomCameraView(
onImageCaptured: (imagePath) {
photos.add(File(imagePath));
},
2024-05-26 11:00:06 +09:00
destination: destination,
2024-05-25 11:05:02 +09:00
),
/*
2022-10-12 21:46:17 +05:30
builder: (_) => CameraCamera(
2023-09-12 12:57:45 +05:30
resolutionPreset: ResolutionPreset.medium,
2023-09-04 22:46:53 +05:30
onFile: (file) {
photos.add(file);
Navigator.pop(context);
2023-10-06 16:25:21 +05:30
//print("----image file is : $file----");
2022-10-12 21:46:17 +05:30
//setState(() {});
},
2024-05-25 11:05:02 +09:00
)
*/
),
);
2022-10-12 21:46:17 +05:30
}
2024-04-07 10:56:51 +09:00
// ルートポイントを取得する関数です。
//
2022-09-22 20:36:56 +05:30
void getRoutePoints() {
indexController.routePoints = [];
indexController.routePointLenght.value = 0;
2023-09-04 22:46:53 +05:30
DestinationService.getDestinationLine(destinations, matrix)?.then((value) {
2022-09-22 20:36:56 +05:30
indexController.routePoints = value;
2023-09-04 22:46:53 +05:30
indexController.routePointLenght.value =
indexController.routePoints.length;
2022-09-22 20:36:56 +05:30
});
}
2022-06-14 14:37:59 +05:30
2024-04-07 10:56:51 +09:00
// 指定された緯度と経度に対応する目的地を取得する関数です。
//
2023-09-04 22:46:53 +05:30
Future<Destination?> getDestinationForLatLong(double lat, double long) async {
for (final d in destinations) {
if (lat == d.lat && long == d.lon) {
return d;
}
}
return null;
2022-06-14 14:37:59 +05:30
}
2024-04-07 10:56:51 +09:00
// チェックインの呼び出しを行う関数です。
// 指定された目的地に対してチェックインの処理を行います。
//
2023-10-06 16:25:21 +05:30
Future<void> callforCheckin(Destination d) async {
2023-09-04 22:46:53 +05:30
bool autoCheckin = d.auto_checkin == 0 ? false : true;
2024-04-20 12:34:49 +09:00
print("---- f- checkin ${d.sub_loc_id} ----");
2023-09-04 22:46:53 +05:30
if (autoCheckin) {
2023-10-06 16:25:21 +05:30
if (!checkingIn) {
2023-09-04 22:46:53 +05:30
makeCheckin(d, true, "");
2024-04-24 11:30:38 +09:00
if (d.cp != -1 && d.cp != 0 && d.cp != -2) {
2023-10-06 16:25:21 +05:30
rogainingCounted.value = true;
2023-09-04 22:46:53 +05:30
}
}
} else {
2023-10-06 16:25:21 +05:30
//print("--- hidden loc ${d.hidden_location} ----");
2023-09-04 22:46:53 +05:30
// ask for checkin
2023-10-06 16:25:21 +05:30
//print("is rog ---- ${is_in_rog.value} ----");
2023-09-04 22:46:53 +05:30
if (d.hidden_location != null &&
d.hidden_location == 0 &&
(isInRog.value == true || (d.buy_point != null && d.buy_point! > 0)) &&
2024-04-24 11:30:38 +09:00
d.cp != -1 && d.cp != 0 && d.cp != -2) {
2023-09-04 22:46:53 +05:30
chekcs = 3;
photos.clear();
isInCheckin.value = true;
final result = await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(
manulaCheckin: true,
destination: d,
)));
if (result ?? false) {
debugPrint("==> Checkin complete....");
if (d.buy_point != null && d.buy_point! > 0) {
skipGps = true;
photos.clear();
DatabaseHelper db = DatabaseHelper.instance;
List<Destination> ds =
await db.getDestinationByLatLon(d.lat!, d.lon!);
Destination? dss;
if (ds.isNotEmpty) {
dss = ds.first;
}
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) =>
CameraPage(
buyPointPhoto: true,
destination: d,
dbDest: dss,
))).whenComplete(() {
skipGps = false;
rogainingCounted.value = true;
chekcs = 0;
isInCheckin.value = false;
//Get.back();
});
}
} else {
debugPrint("キャンセルされました");
Get.snackbar(
"キャンセルされました",
"チェックインしていません。必要ならもう一度チェックポイントをタップして下さい。",
backgroundColor: Colors.yellow,
colorText: Colors.black,
icon: const Icon(
Icons.assistant_photo_outlined, size: 40.0, color: Colors.blue),
snackPosition: SnackPosition.TOP,
duration: const Duration(seconds: 3),
);
}
} else {
Get.snackbar(
"ロゲが始まっていません",
"ロゲ開始ボタンをタップして、ロゲイニングを始める必要があります",
backgroundColor: Colors.yellow,
colorText: Colors.black,
icon: const Icon(
Icons.assistant_photo_outlined, size: 40.0, color: Colors.blue),
snackPosition: SnackPosition.TOP,
duration: const Duration(seconds: 3),
);
}
/*
2023-09-14 22:53:51 +05:30
await showModalBottomSheet(
2023-09-12 12:57:45 +05:30
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
2023-09-04 22:46:53 +05:30
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(
2023-10-06 16:25:21 +05:30
manulaCheckin: true,
2023-09-04 22:46:53 +05:30
destination: d,
2023-09-14 22:53:51 +05:30
))).whenComplete(() async {
if (d.buy_point != null && d.buy_point! > 0) {
2023-10-06 16:25:21 +05:30
skipGps = true;
2023-09-14 22:53:51 +05:30
photos.clear();
DatabaseHelper db = DatabaseHelper.instance;
List<Destination> ds =
await db.getDestinationByLatLon(d.lat!, d.lon!);
2023-09-14 22:53:51 +05:30
Destination? dss;
if (ds.isNotEmpty) {
dss = ds.first;
}
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
2023-09-14 22:53:51 +05:30
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(
buyPointPhoto: true,
destination: d,
dbDest: dss,
))).whenComplete(() {
2023-10-06 16:25:21 +05:30
skipGps = false;
rogainingCounted.value = true;
2023-09-14 22:53:51 +05:30
chekcs = 0;
2023-10-06 16:25:21 +05:30
isInCheckin.value = false;
//Get.back();
2023-09-14 22:53:51 +05:30
});
} else {
2023-10-06 16:25:21 +05:30
skipGps = false;
2023-09-14 22:53:51 +05:30
chekcs = 0;
2023-10-06 16:25:21 +05:30
isInCheckin.value = false;
2023-09-14 22:53:51 +05:30
}
2023-09-04 22:46:53 +05:30
});
} else {
2024-04-03 21:39:12 +09:00
Get.snackbar(
"ロゲが始まっていません",
"ロゲ開始ボタンをタップして、ロゲイニングを始める必要があります",
backgroundColor: Colors.yellow,
colorText: Colors.white,
icon: const Icon(
Icons.assistant_photo_outlined, size: 40.0, color: Colors.blue),
snackPosition: SnackPosition.TOP,
duration: const Duration(seconds: 3)
// backgroundColor: Colors.yellow,
);
2023-09-04 22:46:53 +05:30
}
*/
2023-09-04 22:46:53 +05:30
}
}
2022-10-12 21:46:17 +05:30
2024-04-07 10:56:51 +09:00
// GPSデータをデータベースに追加する関数です。
//
2023-11-22 23:06:38 +05:30
Future<void> addGPStoDB(double la, double ln, {isCheckin = 0}) async {
2024-04-20 12:34:49 +09:00
//debugPrint("in addGPStoDB ${indexController.currentUser}");
try {
GpsDatabaseHelper db = GpsDatabaseHelper.instance;
2024-04-20 12:34:49 +09:00
if(indexController.currentUser.length>0){
final team_name = indexController.currentUser[0]["user"]['team_name'];
final event_code = indexController.currentUser[0]["user"]["event_code"];
GpsData gps_data = GpsData(
id: 0,
team_name: team_name,
event_code: event_code,
lat: la,
lon: ln,
is_checkin: isCheckin,
created_at: DateTime.now().millisecondsSinceEpoch);
var res = await db.insertGps(gps_data);
2024-05-26 11:00:06 +09:00
//debugPrint("Saved GPS data into DB...:${gps_data}");
2024-04-20 12:34:49 +09:00
}
} catch (err) {
print("errr ready gps ${err}");
return;
}
2023-11-22 23:06:38 +05:30
}
2024-04-07 10:56:51 +09:00
// チェックインを確認する関数です。
// ゲームが開始されていない場合は、ゲームを開始します。
// 目的地のリストを走査し、現在位置がチェックイン半径内にある場合は、チェックインの処理を行います。
// GPSデータの送信を開始します。
//
// 2024-4-8 Akira : See 2809
// checkForCheckinメソッドの再帰呼び出しをunawaitedで囲んで、非同期処理の結果を待たずに先に進むようにしました。また、再帰呼び出しの前に一定時間待機するようにしました。
//
2023-09-14 00:08:53 +05:30
Future<void> checkForCheckin() async {
2023-11-27 14:57:25 +05:30
//print("--- Start of checkForCheckin function ---");
2024-02-04 19:14:41 +05:30
dbService.updateDatabase();
2023-12-07 10:20:44 +05:30
await Future.delayed(const Duration(milliseconds: 3000));
2023-11-27 14:57:25 +05:30
game_started = true;
2023-09-12 12:57:45 +05:30
try {
2024-04-20 12:34:49 +09:00
// ここで、エラー
if( indexController.locations.length>0 ) {
indexController.locations[0].features.forEach((fs) async {
GeoJSONMultiPoint mp = fs!.geometry as GeoJSONMultiPoint;
LatLng pt = LatLng(mp.coordinates[0][1], mp.coordinates[0][0]);
double latFs = pt.latitude;
double lonFs = pt.longitude;
var distanceFs = const Distance();
double distFs = distanceFs.as(LengthUnit.Meter, LatLng(latFs, lonFs),
LatLng(currentLat, currentLon));
Destination des = festuretoDestination(fs);
2024-04-24 11:30:38 +09:00
if (distFs <= des.checkin_radious!
&& skipGps == false
//&& des.isCheckedIn == false
&& des.cp!=0 && des.cp!=-1 && des.cp!=-2) {
2024-04-20 12:34:49 +09:00
await startTimerLocation(fs, distFs);
// Note: You cannot break out of forEach. If you need to stop processing, you might have to reconsider using forEach.
}
});
2023-12-06 11:16:17 +05:30
2024-04-20 12:34:49 +09:00
if (gps_push_started == false) {
unawaited(pushGPStoServer());
}
2023-11-27 13:22:18 +05:30
}
2023-10-06 16:25:21 +05:30
//print("--- 123 ---- $skip_gps----");
2023-09-12 12:57:45 +05:30
} catch (e) {
print("An error occurred: $e");
// await checkForCheckin();
2023-09-12 12:57:45 +05:30
} finally {
2024-08-01 20:08:12 +09:00
await Future.delayed(const Duration(seconds: 1)); // 一定時間待機してから再帰呼び出し
2023-10-06 16:25:21 +05:30
//print("--- End of checkForCheckin function, calling recursively ---");
unawaited( checkForCheckin() );
2022-06-14 14:37:59 +05:30
}
}
2024-04-07 10:56:51 +09:00
// GPSデータをサーバーにプッシュする関数です。
//
2023-11-24 11:58:17 +05:30
Future<void> pushGPStoServer() async {
2023-11-27 14:57:25 +05:30
// print(
// "^^^^^^^^ ${DateFormat('kk:mm:ss \n EEE d MMM').format(DateTime.now())}");
2023-11-24 11:58:17 +05:30
try {
2023-11-27 13:22:18 +05:30
gps_push_started = true;
2023-11-24 11:58:17 +05:30
ExternalService().pushGPS();
} catch (e) {
//print("An error occurred: $e");
2023-11-27 14:57:25 +05:30
//await pushGPStoServer();
2023-11-24 11:58:17 +05:30
} finally {
//print("--- End of pushGPStoServer function, calling recursively ---");
2023-11-27 14:57:25 +05:30
await Future.delayed(const Duration(seconds: 5 * 60));
2023-11-24 11:58:17 +05:30
await pushGPStoServer();
}
}
2024-04-07 10:56:51 +09:00
// ロゲイニングにデータを追加する関数です。
//
2023-08-16 14:53:32 +05:30
void addToRogaining(double lat, double lon, int destinationId) async {
2022-10-30 21:43:29 +05:30
DatabaseHelper db = DatabaseHelper.instance;
2023-08-16 14:53:32 +05:30
List<Destination> d = await db.getDestinationById(destinationId);
2023-09-04 22:46:53 +05:30
if (d.isEmpty) {
2022-11-01 23:47:35 +05:30
Destination df = festuretoDestination(indexController.currentFeature[0]);
2023-10-06 16:25:21 +05:30
//print("--- made checkin ${df.location_id} ----");
2022-11-05 22:02:21 +05:30
makeCheckin(df, true, "");
2022-10-30 21:43:29 +05:30
}
2023-10-06 16:25:21 +05:30
isInRog.value = true;
2023-09-11 00:45:54 +05:30
saveGameState();
2022-10-12 21:46:17 +05:30
}
2024-04-07 10:56:51 +09:00
// 買い物ポイントをキャンセルする関数です。
//
2023-09-15 17:19:26 +05:30
Future<void> cancelBuyPoint(Destination destination) async {
2023-09-14 00:08:53 +05:30
DatabaseHelper db = DatabaseHelper.instance;
2023-09-15 17:19:26 +05:30
await db.updateCancelBuyPoint(destination);
2023-10-06 16:25:21 +05:30
populateDestinations();
2023-09-15 17:19:26 +05:30
}
2023-09-14 00:08:53 +05:30
2024-04-07 10:56:51 +09:00
// 指定されたパスの画像をギャラリーに保存する関数です。
//
2023-12-06 11:16:17 +05:30
_saveImageFromPath(String imagePath) async {
try {
// Read the image file from the given path
File imageFile = File(imagePath);
Uint8List imageBytes = await imageFile.readAsBytes();
// Save the image to the gallery
final result = await ImageGallerySaver.saveImage(imageBytes);
//print("--- save result --- ${result}");
} catch(e, stackTrace){
print('エラーが発生しました: $e');
print('スタックトレース: $stackTrace');
}
2023-12-06 11:16:17 +05:30
}
Future<void> _saveImageToGallery(String imagePath) async {
2024-05-25 11:05:02 +09:00
final status = await PermissionController.checkStoragePermission();
if(!status){
await PermissionController.requestStoragePermission();
}
/*
final status = await Permission.storage.status;
if (!status.isGranted) {
final result = await Permission.storage.request();
if (!result.isGranted) {
// ユーザーがストレージの権限を拒否した場合の処理
showDialog(
context: Get.context!,
builder: (BuildContext context) {
return AlertDialog(
title: Text('ストレージの権限が必要です'),
content: Text(
'画像をギャラリーに保存するには、ストレージの権限が必要です。アプリの設定画面で権限を許可してください。'),
actions: [
TextButton(
child: Text('キャンセル'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text('設定'),
onPressed: () {
Navigator.of(context).pop();
openAppSettings(); // アプリの設定画面を開く
},
),
],
);
}
);
2024-05-25 11:05:02 +09:00
return;
}
}
2024-05-25 11:05:02 +09:00
*/
try {
final result = await ImageGallerySaver.saveFile(imagePath);
print('Image saved to gallery: $result');
} catch (e) {
print('Failed to save image to gallery: $e');
}
}
2024-04-07 10:56:51 +09:00
// 買い物ポイントを作成する関数です。 指定された目的地に対して買い物ポイントの処理を行います。
//
// 買い物ポイントの作成に失敗した場合のエラーハンドリングを追加することを検討してください。
//
2023-09-15 17:19:26 +05:30
Future<void> makeBuyPoint(Destination destination, String imageurl) async {
DatabaseHelper db = DatabaseHelper.instance;
2023-09-14 00:08:53 +05:30
await db.updateBuyPoint(destination, imageurl);
2023-10-06 16:25:21 +05:30
populateDestinations();
//await _saveImageFromPath(imageurl);
await _saveImageToGallery(imageurl);
2023-09-15 18:11:13 +05:30
2024-08-05 03:08:12 +09:00
2023-09-15 18:11:13 +05:30
if (indexController.currentUser.isNotEmpty) {
double cpNum = destination.cp!;
2024-08-05 03:08:12 +09:00
//int teamId = indexController.teamId.value; // teamIdを使用
2023-09-15 18:11:13 +05:30
int userId = indexController.currentUser[0]["user"]["id"];
//print("--- Pressed -----");
2023-10-06 16:25:21 +05:30
String team = indexController.currentUser[0]["user"]['team_name'];
2023-09-15 18:11:13 +05:30
//print("--- _team : ${_team}-----");
2023-10-06 16:25:21 +05:30
String eventCode = indexController.currentUser[0]["user"]["event_code"];
2023-09-15 18:11:13 +05:30
//print("--- _event_code : ${_event_code}-----");
2023-10-06 16:25:21 +05:30
String token = indexController.currentUser[0]["token"];
2023-09-15 18:11:13 +05:30
//print("--- _token : ${_token}-----");
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(now);
2023-10-06 16:25:21 +05:30
//print("------ checkin event $eventCode ------");
2023-09-15 18:11:13 +05:30
ExternalService()
2023-10-06 16:25:21 +05:30
.makeCheckpoint(userId, token, formattedDate, team, cpNum.round(),
eventCode, imageurl)
2023-09-15 18:11:13 +05:30
.then((value) {
2023-10-06 16:25:21 +05:30
//print("------Ext service check point $value ------");
2023-09-15 18:11:13 +05:30
});
}
2023-09-14 00:08:53 +05:30
}
2024-04-07 10:56:51 +09:00
// チェックインを行う関数です。 指定された目的地に対してチェックインの処理を行います。
//
// 要検討:チェックインのリクエストが失敗した場合のエラーハンドリングを追加することをお勧めします。
//
2023-09-14 00:08:53 +05:30
Future<void> makeCheckin(
2023-09-04 22:46:53 +05:30
Destination destination, bool action, String imageurl) async {
2022-11-05 22:02:21 +05:30
try {
// print("~~~~ calling checkin function ~~~~");
// print(
// "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ressssss ${destination.sub_loc_id}@@@@@@@@@@@");
DatabaseHelper db = DatabaseHelper.instance;
List<Destination> ddd =
await db.getDestinationByLatLon(destination.lat!, destination.lon!);
if (ddd.isEmpty) {
destination.checkedin = true;
destination.checkin_image = imageurl;
await db.insertDestination(destination);
// print("~~~~ inserted into db ~~~~");
2024-04-24 11:30:38 +09:00
}
2023-09-06 21:04:44 +05:30
if (imageurl == null || imageurl.isEmpty) {
if (photos.isNotEmpty) {
// imageurlが空の場合は、destinationのcheckin_imageプロパティを使用する
debugPrint("photos = ${photos}");
imageurl = photos[0].path;
}
debugPrint("imageurl = ${imageurl}");
//await _saveImageFromPath(imageurl!);
}
if (imageurl.isNotEmpty) {
await _saveImageToGallery(imageurl);
}
2023-09-04 22:46:53 +05:30
populateDestinations();
2023-09-04 22:46:53 +05:30
/// post to NATNAT
if (indexController.currentUser.isNotEmpty) {
double cpNum = destination.cp!;
2024-08-05 03:08:12 +09:00
//int teamId = indexController.teamId.value; // teamIdを使用
//Team team0 = teamController.teams[0];
//print("team={team0}");
int userId = indexController.currentUser[0]["user"]["id"];
//print("--- Pressed -----");
String team = indexController.currentUser[0]["user"]['team_name'];
//print("--- _team : ${_team}-----");
String eventCode = indexController.currentUser[0]["user"]["event_code"];
//print("--- _event_code : ${_event_code}-----");
String token = indexController.currentUser[0]["token"];
//print("--- _token : ${_token}-----");
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(now);
await addGPStoDB(currentLat, currentLon, isCheckin: 1);
// print("------ checkin event $eventCode ------");
ExternalService()
.makeCheckpoint(
2024-08-05 03:08:12 +09:00
userId, // teamIdを使用
token,
formattedDate,
team,
cpNum.round(),
eventCode,
imageurl)
.then((value) {
// print("------Ext service check point $value ------");
});
}
// dbService.updateDatabase();
2023-11-22 23:06:38 +05:30
}catch(e, stacktrace){
print("エラー:${e}");
//print("stack : ${stacktrace}");
}finally{
dbService.updateDatabase();
2023-09-04 22:46:53 +05:30
}
2022-07-14 23:10:24 +05:30
}
2024-04-07 10:56:51 +09:00
// チェックインを削除する関数です。
//
2023-11-22 23:06:38 +05:30
Future<void> removeCheckin(int cp) {
2024-02-04 19:14:41 +05:30
dbService.updateDatabase();
2023-11-22 23:06:38 +05:30
return ExternalService().removeCheckin(cp);
}
2024-04-07 10:56:51 +09:00
// ゲームを開始する関数です。
//
2023-09-14 00:08:53 +05:30
Future<void> startGame() async {
debugPrint("------ starting game ------");
2023-11-27 14:57:25 +05:30
if (game_started == false) {
await checkForCheckin();
}
2023-09-12 12:57:45 +05:30
}
2023-09-06 00:22:02 +05:30
Timer? gpsCheckTimer; // 一定間隔でGPSデータの受信状態をチェックするタイマー
void startGPSCheckTimer() {
gpsCheckTimer = Timer.periodic(Duration(seconds: 5), (timer) {
checkGPSDataReceived();
});
}
2024-04-07 10:56:51 +09:00
// コントローラーの初期化時に呼び出されるライフサイクルメソッドです。
//
bool inError=false;
bool isRunningBackgroundGPS=false;
int activeEngineCount = 0;
2023-09-06 00:22:02 +05:30
@override
void onInit() async {
2022-09-22 20:36:56 +05:30
super.onInit();
/*
WidgetsBinding.instance.addPostFrameCallback((_) async {
await PermissionController.checkAndRequestPermissions();
});
*/
startGPSCheckTimer();
// MapControllerの初期化完了を待機するフラグを設定
WidgetsBinding.instance.addPostFrameCallback((_) {
//checkGPSDataReceived(); removed 2024-5-4
isMapControllerReady = true;
});
// 要検討:エラーメッセージを表示するなどの適切な処理を追加することを検討してください。
//
// locationController からデバイスの受け取るGPS情報を取得し、
// handleLocationUpdate を呼び出している。
//
locationController.locationMarkerPositionStream.listen(
(locationMarkerPosition) {
//if (locationMarkerPosition != null) {
handleLocationUpdate(locationMarkerPosition);
//}
}, onError: (err) {
if(inError==false){
inError = true;
debugPrint("Location Error: $err");
// エラーが発生した場合、locationMarkerPositionStreamControllerにエラーを追加します。
locationController.locationMarkerPositionStreamController.addError(err);
// ここにエラー発生時の処理を追加します。
if (err is LocationServiceDisabledException) {
// 位置情報サービスが無効になっている場合の処理
print('Location services are disabled');
Get.snackbar(
'エラー',
'位置情報サービスが無効になっています。設定画面から位置情報サービスを有効にして下さい。不明な場合にはエンジニアスタッフにお問い合わせください。',
backgroundColor: Colors.red,
colorText: Colors.white,
duration: Duration(seconds: 3),
);
inError = false;
} else if (err is PermissionDeniedException) {
// 位置情報の権限がない場合の処理
print('Location permissions are denied');
Get.snackbar(
'エラー',
'位置情報サービスが許可されていません。設定画面から岐阜ナビの位置情報サービスを許可して下さい。不明な場合にはエンジニアスタッフにお問い合わせください。',
backgroundColor: Colors.red,
colorText: Colors.white,
duration: Duration(seconds: 3),
);
inError = false;
} else {
// その他のエラーの場合の処理
print('Location Error: $err');
Get.snackbar(
'エラー',
'位置情報サービスに問題が発生しました。位置情報サービスを再起動していますので少しお待ちください。',
backgroundColor: Colors.red,
colorText: Colors.white,
duration: Duration(seconds: 3),
);
// GPSデータのListenを再開する処理を追加
if( isRunningBackgroundGPS==false && inError ) {
restartGPS();
}
}
}
//print("Location Error: $err");
});
startGame();
//checkGPSDataReceived();
}
void restartGPS(){
// GPSデータのListenを再開する処理を追加
Future.delayed(Duration(seconds: 5), () {
locationController.startPositionStream();
inError=false;
});
}
2024-04-07 10:56:51 +09:00
// コントローラーのクローズ時に呼び出されるライフサイクルメソッドです。
//
2023-12-07 10:20:44 +05:30
@override
void onClose() {
gpsCheckTimer?.cancel();
2023-12-07 10:20:44 +05:30
locationController.stopPositionStream();
super.onClose();
2023-12-07 10:20:44 +05:30
}
2024-04-07 10:56:51 +09:00
// 位置情報の更新を処理する関数です。
// 現在位置とスタート地点との距離を計算します。
// 現在位置と前回の位置情報との距離と時間差を確認し、一定の条件を満たす場合はGPSデータをデータベースに追加します。
//
// 要検討GPSデータの追加に失敗した場合のエラーハンドリングを追加することをお勧めします。
//
double prevLat = 0.0; // 直前の位置
double prevLon = 0.0;
bool gpsDebugMode=false;
void handleLocationUpdate(LocationMarkerPosition? position) async {
//debugPrint("DestinationController.handleLocationUpdate");
try {
//final DestinationController destinationController = Get.find<DestinationController>();
//final signalStrength = locationController.getGpsSignalStrength();
okToUseGPS = false;
2024-04-20 12:34:49 +09:00
if (position != null) {
currentLat = position.latitude;
currentLon = position.longitude;
if( prevLat==0.0 ){
prevLat = currentLat;
prevLon = currentLon;
}
lastValidGPSLocation = LatLng(currentLat, currentLon);
lastValidLat = currentLat;
lastValidLon = currentLon;
okToUseGPS = true;
lastGPSDataReceivedTime = DateTime.now();
hasReceivedGPSData = true;
} else {
debugPrint("....position is null....");
checkGPSDataReceived();
// 信号強度が低い場合、最後に取得した高いまたは中程度の位置情報を使用
// 但し、最初から高精度のものがない場合、どうするか?
//
// GPSデータが受信できない場合、最後に有効なGPSデータを使用
position = LocationMarkerPosition(
latitude: lastValidGPSLocation.latitude,
longitude: lastValidGPSLocation.longitude,
accuracy: 0,
);
currentLat = position.latitude;
currentLon = position.longitude;
okToUseGPS = false;
/*
if (lastValidLat != 0.0 && lastValidLon != 0.0) {
currentLat = lastValidLat;
currentLon = lastValidLon;
okToUseGPS = true;
} else {
// GPSの届く場所に行って、信号を拾ってください。とメッセージを出す。
position = null;
print("GPSの届く場所に行って、信号を拾ってください。");
Get.snackbar(
"GPS信号を正確に拾えていません",
"空が大きく見えるところへ行ってGPS信号を拾ってください。",
icon: const Icon(
Icons.assistant_photo_outlined, size: 40.0, color: Colors.blue),
snackPosition: SnackPosition.TOP,
duration: const Duration(seconds: 3),
backgroundColor: Colors.yellow,
);
}
*/
}
2024-04-20 12:34:49 +09:00
if (okToUseGPS && position != null) {
// スタート位置から150m離れたら、ready_for_goal
2024-03-09 11:59:42 +05:30
if (distanceToStart() >= 150) {
ready_for_goal = true;
}
var distance = const Distance();
double distanceToDest = distance.as(
LengthUnit.Meter,
LatLng(position.latitude, position.longitude),
LatLng(prevLat, prevLon)
);
2024-04-20 12:34:49 +09:00
Duration difference = lastGPSCollectedTime.difference(DateTime.now())
.abs();
// 最後にGPS信号を取得した時刻から10秒以上経過、かつ10m以上経過普通に歩くスピード
//debugPrint("時間差:${difference.inSeconds}, 距離差:${distanceToDest}");
if (difference.inSeconds >= 10 || distanceToDest >= 30) {
// print(
// "^^^^^^^^ GPS data collected ${DateFormat('kk:mm:ss \n EEE d MMM').format(DateTime.now())}, ^^^ ${position.latitude}, ${position.longitude}");
LogManager().addLog(
2024-04-20 12:34:49 +09:00
"GPS : $currentLat, $currentLon - ${DateTime
.now()
.hour}:${DateTime
.now()
.minute}:${DateTime
.now()
.second}:${DateTime
.now()
.microsecond}");
if (isInRog.value) {
await addGPStoDB(position.latitude, position.longitude);
lastGPSCollectedTime = DateTime.now();
prevLat = position.latitude;
prevLon = position.longitude;
gpsDebugMode ? debugPrint("フロントエンドでのGPS保存(時間差:${difference.inSeconds}, 距離差:${distanceToDest}) : Time=${lastGPSCollectedTime}"):null;
}
2023-12-12 16:16:17 +05:30
}
2023-12-07 10:20:44 +05:30
}
2024-04-20 12:34:49 +09:00
} catch(e) {
debugPrint("handleLocationUpdate Error: ${e}");
} finally {
2024-04-07 10:56:51 +09:00
/* Akira , 2024-4-5
if (position != null &&
(position.latitude != 0 && position.longitude != 0)) {
currentLat = position.latitude;
currentLon = position.longitude;
}
2024-04-07 10:56:51 +09:00
*/
if (okToUseGPS) {
2024-04-07 10:56:51 +09:00
// 位置情報が取得できた場合、精度に関わらず最後の位置情報を更新
//currentLat = position.latitude;
//currentLon = position.longitude;
2024-04-07 10:56:51 +09:00
}
2023-12-07 10:20:44 +05:30
}
}
2024-04-07 10:56:51 +09:00
// スタート地点までの距離を計算する関数です。
//
2023-11-20 22:49:54 +05:30
double distanceToStart() {
2024-02-04 19:14:41 +05:30
if (indexController.locations.isEmpty) {
return 1000000000;
}
2023-11-21 15:45:03 +05:30
//print("=== gfs len == ${indexController.locations[0].collection.length}");
2023-12-06 11:16:17 +05:30
double distanceToDest = double.infinity;
if (indexController.locations[0].features.isEmpty) {
return distanceToDest;
}
GeoJSONFeature? gfs = indexController.locations[0].features.firstWhere(
(element) => festuretoDestination(element!).cp == -1,
orElse: () => null, // Provide a null value if no element is found
);
//print("gfs : ${gfs}");
2023-12-06 11:16:17 +05:30
if (gfs == null) {
return distanceToDest;
}
2023-11-21 15:45:03 +05:30
//final currentLocation = getCurrentLocation(); // GPS信号中以上での現在位置
2023-11-21 15:45:03 +05:30
Destination des = festuretoDestination(gfs);
2023-11-27 14:57:25 +05:30
//print("=== gfs == ${des.toMap()}");
2023-11-20 22:49:54 +05:30
2023-11-21 15:45:03 +05:30
var distance = const Distance();
distanceToDest = distance.as(LengthUnit.Meter,
LatLng(currentLat,currentLon), LatLng(des.lat!, des.lon!));
// LatLng(currentLat, currentLon), LatLng(des.lat!, des.lon!));
2023-11-27 14:57:25 +05:30
//print("==== dist==${distanceToDest}");
2023-11-20 22:49:54 +05:30
return distanceToDest;
}
2024-04-07 10:56:51 +09:00
// 強制チェックイン距離を取得する関数です。
//
int getForcedChckinDistance(Destination dest) {
2024-01-17 16:08:41 +05:30
if (dest.checkin_radious == -1) {
return 10000000000000000;
}
int _retValue = 100;
if (dest.cp == -1) {
return 500;
}
Destination? ds;
2023-12-06 11:16:17 +05:30
GeoJSONFeature? gfs = indexController.locations[0].features.firstWhere(
(element) => festuretoDestination(element!).cp == -1,
orElse: () => null, // Provide a null value if no element is found
);
if (gfs == null) {
return _retValue;
}
2023-11-21 15:45:03 +05:30
ds = festuretoDestination(gfs);
var distance = const Distance();
double distanceToDest = distance.as(LengthUnit.Meter,
LatLng(dest.lat!, dest.lon!), LatLng(ds.lat!, ds.lon!));
if (distanceToDest <= 500) {
return 500;
}
2023-11-27 14:57:25 +05:30
//print("==== forced dist ==${distanceToDest}");
return _retValue;
2023-09-04 22:46:53 +05:30
}
2022-06-04 20:16:29 +05:30
2024-04-07 10:56:51 +09:00
// ユーザートークンを読み取る関数です。
//
2023-09-12 12:57:45 +05:30
readUserToken() async {
2023-09-04 22:46:53 +05:30
final SharedPreferences prefs = await SharedPreferences.getInstance();
indexController.userToken = prefs.getString("user_token");
2022-05-12 02:17:08 +05:30
}
2024-04-07 10:56:51 +09:00
// コントローラーの準備完了時に呼び出されるライフサイクルメソッドです。
//
2022-12-27 18:52:37 +05:30
@override
2023-09-04 22:46:53 +05:30
void onReady() async {
await readUserToken();
final token = indexController.userToken;
2023-09-12 12:57:45 +05:30
if (token != null && token.isNotEmpty) {
2023-09-04 22:46:53 +05:30
await indexController.loadUserDetailsForToken(token);
fixMapBound(token);
}else {
Get.toNamed(AppPages.LOGIN)!.then((value) {
if (indexController.currentUser.isNotEmpty) {
final tk = indexController.currentUser[0]["token"];
fixMapBound(tk);
} else {
Get.toNamed(AppPages.TRAVEL);
PerfectureService.getSubExt("9").then((value) {
if (value != null) {
LatLngBounds bnds = LatLngBounds(
LatLng(value[1], value[0]), LatLng(value[3], value[2]));
indexController.mapController
.fitBounds(bnds); //.centerZoomFitBounds(bnds);
}
});
}
});
2023-09-04 22:46:53 +05:30
}
// 地図のイベントリスナーを設定
indexController.mapController.mapEventStream.listen((MapEvent mapEvent) {
if (mapEvent is MapEventMoveEnd) {
2024-07-30 02:15:04 +09:00
indexController.loadLocationsBound(indexController.currentUser[0]["user"]["event_code"]);
2023-07-18 22:10:30 +05:30
}
});
2023-07-18 22:10:30 +05:30
super.onReady();
}
2024-04-07 10:56:51 +09:00
// 地図の境界を修正する関数です。
//
2023-09-04 22:46:53 +05:30
void fixMapBound(String token) {
//String _token = indexController.currentUser[0]["token"];
2023-10-08 19:13:14 +05:30
indexController.switchPage(AppPages.INDEX);
if (isMapControllerReady) {
LocationService.getLocationsExt(token).then((value) {
if (value != null) {
//print("--- loc ext is - $value ----");
LatLngBounds bnds = LatLngBounds(
LatLng(value[1], value[0]), LatLng(value[3], value[2]));
//print("--- bnds is - $bnds ----");
indexController.mapController.fitBounds(
bnds,
);
indexController.currentBound.clear();
indexController.currentBound.add(bnds);
2024-07-30 02:15:04 +09:00
indexController.loadLocationsBound(indexController.currentUser[0]["user"]["event_code"]);
centerMapToCurrentLocation();
}
});
} else {
// MapControllerの初期化が完了していない場合は、遅延して再試行
Future.delayed(Duration(milliseconds: 100), () {
fixMapBound(token);
});
}
}
2024-04-07 10:56:51 +09:00
/*
void fixMapBound(String token) {
indexController.switchPage(AppPages.INDEX);
LocationService.getLocationsExt(token).then((value) {
if (value != null) {
LatLngBounds bnds = LatLngBounds(
LatLng(value[1], value[0]),
LatLng(value[3], value[2]),
);
if (indexController.isMapControllerReady.value) {
indexController.mapController.fitBounds(
bnds,
);
indexController.currentBound.clear();
indexController.currentBound.add(bnds);
indexController.loadLocationsBound();
centerMapToCurrentLocation();
} else {
// MapControllerが初期化されるまで待機し、その後fitBoundsを実行
WidgetsBinding.instance.addPostFrameCallback((_) {
indexController.mapController.fitBounds(
bnds,
);
indexController.currentBound.clear();
indexController.currentBound.add(bnds);
indexController.loadLocationsBound();
centerMapToCurrentLocation();
});
}
}
});
}
*/
// 地図を現在位置に中央揃えする関数です。
//
void centerMapToCurrentLocation() {
//print("center is ${currentLat}, ${currentLon}");
// Akira ... 状況によって呼ぶか呼ばないか
if (currentLat != 0 || currentLon != 0) {
indexController.mapController.move(LatLng(currentLat, currentLon), 17.0);
}
2022-12-27 18:52:37 +05:30
}
2024-04-07 10:56:51 +09:00
// 接続状態が変更されたときに呼び出される関数です。
//
2022-11-14 22:22:41 +05:30
void connectionChanged(String val) {
2023-10-06 16:25:21 +05:30
//print('----- %%%%%%%%%%%%%%%%%%%%% ----- $val');
Map<String, dynamic> res = {};
2023-09-04 22:46:53 +05:30
if (val == "wifi" || val == "mobile") {
2024-08-05 03:08:12 +09:00
//int teamId = indexController.teamId.value; // teamIdを使用
2023-10-06 16:25:21 +05:30
String token = indexController.currentUser[0]["token"];
2022-11-14 22:22:41 +05:30
DatabaseHelper db = DatabaseHelper.instance;
2023-09-04 22:46:53 +05:30
db.allRogianing().then((value) {
2022-11-14 22:27:52 +05:30
value.forEach((e) async {
2023-09-04 22:46:53 +05:30
if (e.rog_action_type == 0) {
2023-10-06 16:25:21 +05:30
res = await ExternalService().startRogaining();
2023-09-04 22:46:53 +05:30
} else if (e.rog_action_type == 1) {
2023-08-16 14:53:32 +05:30
var datetime = DateTime.fromMicrosecondsSinceEpoch(e.checkintime!);
2023-10-06 16:25:21 +05:30
res = await ExternalService().makeCheckpoint(
2024-08-05 03:08:12 +09:00
e.user_id!, // teamId???
2023-10-06 16:25:21 +05:30
token,
2023-09-04 22:46:53 +05:30
getFormatedTime(datetime),
e.team_name!,
e.cp_number!,
e.event_code!,
e.image!);
} else if (e.rog_action_type == 2) {
2023-08-16 14:53:32 +05:30
var datetime = DateTime.fromMicrosecondsSinceEpoch(e.checkintime!);
2023-10-06 16:25:21 +05:30
res = await ExternalService().makeGoal(
2024-08-05 03:08:12 +09:00
e.user_id!, // // teamId???
2023-10-06 16:25:21 +05:30
token,
2023-09-04 22:46:53 +05:30
e.team_name!,
e.image!,
getFormatedTime(datetime),
e.event_code!);
2022-11-14 22:22:41 +05:30
}
2022-11-14 22:27:52 +05:30
2023-10-06 16:25:21 +05:30
if (res.isNotEmpty) {
2022-11-14 22:27:52 +05:30
db.deleteRogaining(e.id!);
}
2022-11-14 22:22:41 +05:30
});
});
}
}
/*
2024-04-07 10:56:51 +09:00
// 位置情報の許可を確認する関数です。
//
2022-07-14 23:10:24 +05:30
void checkPermission() async {
2022-12-25 19:26:07 +05:30
LocationPermission permission = await Geolocator.checkPermission();
2022-07-14 23:10:24 +05:30
if (permission != LocationPermission.whileInUse ||
permission != LocationPermission.always) {
2023-09-04 22:46:53 +05:30
locationPermission.clear();
locationPermission.add(permission.name);
2022-07-14 23:10:24 +05:30
permission = await Geolocator.requestPermission();
}
}
*/
2022-07-14 23:10:24 +05:30
2024-04-07 10:56:51 +09:00
// IDに基づいて目的地を取得する関数です。
//
2023-09-04 22:46:53 +05:30
Destination? destinationById(int id) {
2023-08-16 14:53:32 +05:30
Destination? d;
2023-10-06 16:25:21 +05:30
//print("--- target des - $id ----");
2023-09-04 22:46:53 +05:30
for (Destination ss in destinations) {
2023-10-06 16:25:21 +05:30
//print("--- des - ${ss.location_id} ----");
2023-09-04 22:46:53 +05:30
if (ss.location_id == id) {
2022-10-12 21:46:17 +05:30
d = ss;
break;
}
}
return d;
}
2024-04-07 10:56:51 +09:00
// 目的地を削除する関数です。
//
2023-09-04 22:46:53 +05:30
void deleteDestination(Destination d) {
2022-07-10 23:50:43 +05:30
//int id = destinations[index].location_id!;
2022-07-09 22:51:34 +05:30
//print("---- index ${destinations[index].location_id!}-----");
2023-09-04 22:46:53 +05:30
for (Destination ss in destinations) {
if (ss.location_id == d.location_id) {
2022-10-30 21:43:29 +05:30
destinations.remove(ss);
2022-07-10 23:50:43 +05:30
break;
}
}
2022-07-09 22:51:34 +05:30
DatabaseHelper db = DatabaseHelper.instance;
2023-09-04 22:46:53 +05:30
db.deleteDestination(d.location_id!).then((value) {
2023-10-06 16:25:21 +05:30
populateDestinations();
2022-05-25 21:00:10 +05:30
});
2024-02-04 19:14:41 +05:30
dbService.updateDatabase();
2022-07-09 22:51:34 +05:30
}
2024-04-07 10:56:51 +09:00
// データベースからすべての目的地を削除する関数です。
//
2023-09-12 22:08:03 +05:30
void deleteDBDestinations() {
2022-09-23 18:40:17 +05:30
DatabaseHelper db = DatabaseHelper.instance;
2023-09-04 22:46:53 +05:30
db.deleteAllDestinations().then((value) {
2023-10-06 16:25:21 +05:30
populateDestinations();
2022-09-23 18:40:17 +05:30
});
2024-02-04 19:14:41 +05:30
dbService.updateDatabase();
2022-09-23 18:40:17 +05:30
}
2023-09-04 22:46:53 +05:30
// ---------- database ------------------///
2022-07-09 22:51:34 +05:30
2024-04-07 10:56:51 +09:00
// 目的地を追加する関数です。
//
2023-09-04 22:46:53 +05:30
void addDestinations(Destination dest) {
2022-07-09 22:51:34 +05:30
DatabaseHelper db = DatabaseHelper.instance;
2023-09-04 22:46:53 +05:30
db.getDestinationByLatLon(dest.lat!, dest.lon!).then((value) {
if (value.isNotEmpty) {
db.deleteDestination(value[0].location_id!).then((value) {
db.insertDestination(dest).then((value) {
2023-10-06 16:25:21 +05:30
//print(
// "----- destination controller deleted and inserted destination id $value ---- :::::");
populateDestinations();
2022-07-09 22:51:34 +05:30
});
});
2023-09-04 22:46:53 +05:30
} else {
db.insertDestination(dest).then((value) {
2023-10-06 16:25:21 +05:30
//print("----- destination controller added as new $value--- :::::");
populateDestinations();
2023-09-04 22:46:53 +05:30
});
2022-07-09 22:51:34 +05:30
}
});
2024-02-04 19:14:41 +05:30
dbService.updateDatabase();
2022-05-25 21:00:10 +05:30
}
2024-04-07 10:56:51 +09:00
// 目的地の選択状態を切り替える関数です。
//
void toggleSelection(Destination dest) async {
try {
DatabaseHelper db = DatabaseHelper.instance;
await db.toggleSelecttion(dest);
destinations.clear();
db.getDestinations().then((value) {
destinationCount.value = 0;
currentSelectedDestinations.clear();
for (Destination d in value) {
//print("------ destination controller populating destination-------- ${d.checkedin}-------- :::::");
//print("-----populated----- ${d.toMap()}");
if (d.selected!) {
currentSelectedDestinations.add(d);
}
destinations.add(d);
}
destinationCount.value = destinations.length;
});
} catch( e ){
print('Error in toggleSelection: $e');
Get.snackbar(
"画面切り替えでエラー",
"画面の切り替えができませんでした",
backgroundColor: Colors.red,
colorText: Colors.white,
icon: const Icon(
Icons.assistant_photo_outlined, size: 40.0, color: Colors.blue),
snackPosition: SnackPosition.TOP,
duration: const Duration(seconds: 3),
//backgroundColor: Colors.yellow,
);
}
}
2024-04-07 10:56:51 +09:00
// ダイアログを表示する関数です。
//
2023-02-16 19:36:39 +05:30
buildShowDialog(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
2023-08-16 14:53:32 +05:30
return const Center(
2023-02-16 19:36:39 +05:30
child: CircularProgressIndicator(),
);
});
}
2024-04-07 10:56:51 +09:00
// 現在地点からの目的地の行列を計算する関数です。
//
2023-09-04 22:46:53 +05:30
void destinationMatrixFromCurrentPoint(List<Destination> points) {
2024-03-07 12:27:30 +05:30
//buildShowDialog(Get.context!);
2023-09-04 22:46:53 +05:30
MatrixService.getDestinations(points).then((mat) {
2023-10-06 16:25:21 +05:30
//print(" matrix is ------- $mat");
2023-02-16 19:36:39 +05:30
matrix = mat;
2023-09-04 22:46:53 +05:30
try {
2023-02-16 19:36:39 +05:30
indexController.routePoints = [];
indexController.routePointLenght.value = 0;
2023-09-04 22:46:53 +05:30
DestinationService.getDestinationLine(points, matrix)?.then((value) {
2023-02-16 19:36:39 +05:30
indexController.routePoints = value;
2023-09-04 22:46:53 +05:30
indexController.routePointLenght.value =
indexController.routePoints.length;
2023-06-11 21:03:30 +05:30
//Get.toNamed(AppPages.TRAVEL);
2023-02-16 19:36:39 +05:30
});
destinationCount.value = destinations.length;
2024-05-25 11:05:02 +09:00
2023-09-04 22:46:53 +05:30
} catch (_) {
2023-10-06 16:25:21 +05:30
skipGps = false;
2023-02-16 19:36:39 +05:30
return;
2023-09-04 22:46:53 +05:30
} finally {
2024-03-07 12:27:30 +05:30
//Get.back();
2024-05-25 11:05:02 +09:00
isRouteShowing.value = true;
2023-02-16 19:36:39 +05:30
}
});
}
2024-04-07 10:56:51 +09:00
// 目的地のリストを取得してObservable変数を更新する関数です。
//
2023-10-06 16:25:21 +05:30
void populateDestinations() {
2022-07-09 22:51:34 +05:30
DatabaseHelper db = DatabaseHelper.instance;
2022-09-29 15:32:33 +05:30
destinations.clear();
2023-09-04 22:46:53 +05:30
db.getDestinations().then((value) {
2022-09-22 20:36:56 +05:30
destinationCount.value = 0;
2023-09-04 22:46:53 +05:30
for (Destination d in value) {
2022-07-10 23:50:43 +05:30
destinations.add(d);
}
2023-11-21 22:43:28 +05:30
if (destinations.isEmpty) {
rogainingCounted.value = false;
}
2022-07-09 22:51:34 +05:30
});
2022-05-12 02:17:08 +05:30
}
2024-04-07 10:56:51 +09:00
// 目的地の順序を変更する関数です。
//
2023-09-04 22:46:53 +05:30
void makeOrder(Destination d, int dir) {
2022-09-23 18:40:17 +05:30
DatabaseHelper db = DatabaseHelper.instance;
2023-09-04 22:46:53 +05:30
db.updateOrder(d, dir).then((value) {
2023-10-06 16:25:21 +05:30
populateDestinations();
2022-09-23 18:40:17 +05:30
});
2022-07-09 22:51:34 +05:30
}
2023-09-04 22:46:53 +05:30
}