You need to enable JavaScript to run this app. Flutter中将Geolocator获取的米每秒速度转换为英里每小时存入Firestore
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中将Geolocator获取的米每秒速度转换为英里每小时存入Firestore

代码修改方案

你只需要在获取速度值的环节增加换算逻辑即可,具体修改如下:

核心修改点

  • 先定义米每秒转英里每小时的换算常量2.23694
  • 先拿到Position返回的米每秒速度数值,乘以换算系数得到英里每小时的数值,可根据需求保留小数位数
  • 把换算后的速度值存入对应Map的Speed字段即可

修改后完整代码

import 'dart:async';
import 'dart:developer';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:geolocator/geolocator.dart';
import 'package:intl/intl.dart';

Future<void> backgroundUpdate() async {

  Firebase.initializeApp();
  FirebaseAuth auth = FirebaseAuth.instance;
  Position _fetchedUserLocation = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
  log(_fetchedUserLocation.latitude.toString() +
      _fetchedUserLocation.longitude.toString());

  User firebaseUser = (auth.currentUser)!;
  String uid = firebaseUser.uid;
  String displayNamed = firebaseUser.displayName!;
  DateTime dateTime = DateTime.now();
  String dateString = DateFormat('dd-MM-yyyy - kk:mm').format(dateTime);
  double latitude = _fetchedUserLocation.latitude.toDouble();
  double longitude = _fetchedUserLocation.longitude.toDouble();

  // ---------------新增换算逻辑 开始---------------
  // 定义米每秒转英里每小时的换算系数
  const double mpsToMphFactor = 2.23694;
  // 获取原始米每秒速度值
  double originalSpeedMps = _fetchedUserLocation.speed;
  // 换算为英里每小时,这里保留1位小数,可根据需要调整toStringAsFixed的参数
  double speedMph = originalSpeedMps * mpsToMphFactor;
  String speed = speedMph.toStringAsFixed(1);
  // ---------------新增换算逻辑 结束---------------

  Map<String, dynamic> map = Map();
  map['DateTime'] = dateString;
  map['Uid'] = uid;
  map['Racer'] = displayNamed;
  map['Lat'] = latitude;
  map['Lng'] = longitude;
  map['Speed'] = speed;

  Map<String, dynamic> map2 = Map();
  map2['DateTime'] = dateString;
  map2['Racer'] = displayNamed;
  map2['Lat'] = latitude;
  map2['Lng'] = longitude;
  map2['Speed'] = speed;
  map2['Uid'] = uid;

  FirebaseFirestore firestore = FirebaseFirestore.instance;
  CollectionReference collectionReference =
  firestore.collection('$displayNamed');
  await collectionReference.doc('$dateString').set(map).then((
      value) {
    print('Upload Success Dawg');
  });

  FirebaseFirestore firestore2 = FirebaseFirestore.instance;
  CollectionReference collectionReference2 =
  firestore2.collection('usertest');
  await collectionReference2.doc('$displayNamed').set(map2).then((
      value) {
    print('Upload Success Dawgydeuce');
  });
}

内容的提问来源于stack exchange,提问作者giroprotagonist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 04:45:02