location_picker.dart 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:math';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter_map/flutter_map.dart';
  6. import 'package:latlong2/latlong.dart';
  7. import 'package:geolocator/geolocator.dart';
  8. import 'package:http/http.dart' as http;
  9. import 'package:tdesign_flutter/tdesign_flutter.dart' hide Position;
  10. import '../../core/theme/app_colors_extension.dart';
  11. import '../../core/i18n/app_localizations.dart';
  12. class LocationResult {
  13. final String address;
  14. final double latitude;
  15. final double longitude;
  16. const LocationResult({
  17. required this.address,
  18. required this.latitude,
  19. required this.longitude,
  20. });
  21. }
  22. class LocationPicker extends StatefulWidget {
  23. final String? initialAddress;
  24. const LocationPicker({super.key, this.initialAddress});
  25. static Future<LocationResult?> show(
  26. BuildContext context, {
  27. String? initialAddress,
  28. }) {
  29. return Navigator.push(
  30. context,
  31. TDSlidePopupRoute<LocationResult>(
  32. slideTransitionFrom: SlideTransitionFrom.bottom,
  33. isDismissible: true,
  34. builder: (_) => LocationPicker(initialAddress: initialAddress),
  35. ),
  36. );
  37. }
  38. @override
  39. State<LocationPicker> createState() => _LocationPickerState();
  40. }
  41. class _LocationPickerState extends State<LocationPicker> {
  42. final _mapCtrl = MapController();
  43. final _searchCtrl = TextEditingController();
  44. LatLng _center = const LatLng(22.277, 113.565); // 珠海市区
  45. String _address = '';
  46. bool _locating = false;
  47. bool _searching = false;
  48. Timer? _debounce;
  49. List<_SItem> _results = [];
  50. static const _ak = 'rXpqWuD8jNrEzczIYzzc9Jwjqi6MVtXD';
  51. static const _base = 'https://api.map.baidu.com';
  52. static const _xPi = pi * 3000.0 / 180.0;
  53. /// BD-09 → GCJ-02 (高德坐标系)
  54. LatLng _bd2gcj(double lat, double lng) {
  55. final x = lng - 0.0065;
  56. final y = lat - 0.006;
  57. final z = sqrt(x * x + y * y) - 0.00002 * sin(y * _xPi);
  58. final theta = atan2(y, x) - 0.000003 * cos(x * _xPi);
  59. return LatLng(z * sin(theta), z * cos(theta));
  60. }
  61. @override
  62. void initState() {
  63. super.initState();
  64. if (widget.initialAddress != null && widget.initialAddress!.isNotEmpty) {
  65. _address = widget.initialAddress!;
  66. _geocode(_address);
  67. } else {
  68. _reverse(_center);
  69. }
  70. }
  71. @override
  72. void dispose() {
  73. _searchCtrl.dispose();
  74. super.dispose();
  75. }
  76. Future<void> _geocode(String q) async {
  77. try {
  78. final u =
  79. '$_base/geocoding/v3/?address=${Uri.encodeComponent(q)}&output=json&ak=$_ak';
  80. final r = await http.get(Uri.parse(u));
  81. if (r.statusCode != 200) return;
  82. final d = json.decode(r.body);
  83. if (d['status'] != 0 || d['result'] == null) return;
  84. final loc = d['result']['location'];
  85. final p = _bd2gcj(loc['lat'] as double, loc['lng'] as double);
  86. _mapCtrl.move(p, 15);
  87. setState(() {
  88. _center = p;
  89. _address = q;
  90. });
  91. } catch (_) {}
  92. }
  93. Future<void> _reverse(LatLng p) async {
  94. try {
  95. final u =
  96. '$_base/reverse_geocoding/v3/?location=${p.latitude},${p.longitude}&coordtype=gcj02ll&output=json&ak=$_ak';
  97. final r = await http.get(Uri.parse(u));
  98. if (r.statusCode != 200) return;
  99. final d = json.decode(r.body);
  100. if (d['status'] != 0 || d['result'] == null) return;
  101. if (!mounted) return;
  102. final addr = d['result']['formatted_address'] as String?;
  103. if (addr != null && addr.isNotEmpty) {
  104. setState(() => _address = addr);
  105. } else {
  106. setState(
  107. () => _address =
  108. '${p.latitude.toStringAsFixed(6)}, ${p.longitude.toStringAsFixed(6)}',
  109. );
  110. }
  111. } catch (_) {}
  112. }
  113. void _search() {
  114. _debounce?.cancel();
  115. final q = _searchCtrl.text.trim();
  116. if (q.isEmpty) {
  117. setState(() {
  118. _results = [];
  119. _address = '';
  120. _searching = false;
  121. });
  122. return;
  123. }
  124. _address = q;
  125. // 中文最少 2 个字再触发搜索
  126. if (q.length < 2) {
  127. setState(() => _results = []);
  128. return;
  129. }
  130. _debounce = Timer(const Duration(milliseconds: 400), () {
  131. _doSearch(q);
  132. });
  133. }
  134. Future<void> _doSearch(String q) async {
  135. // 守卫:防止旧 Timer 带着已删除的文本触发搜索
  136. if (_searchCtrl.text.trim() != q) return;
  137. setState(() => _searching = true);
  138. try {
  139. final u =
  140. '$_base/place/v2/search?query=${Uri.encodeComponent(q)}&region=全国&output=json&scope=2&ak=$_ak';
  141. final r = await http.get(Uri.parse(u));
  142. if (r.statusCode != 200) return;
  143. final d = json.decode(r.body);
  144. if (d['status'] != 0 || d['results'] == null) return;
  145. final list = d['results'] as List;
  146. if (!mounted) return;
  147. setState(() {
  148. _results = list.map((e) {
  149. final loc = e['location'];
  150. final p = _bd2gcj(
  151. (loc['lat'] as num).toDouble(),
  152. (loc['lng'] as num).toDouble(),
  153. );
  154. final addr = e['address'] as String?;
  155. return _SItem(
  156. '${e['name'] ?? ''}${addr != null ? ',$addr' : ''}',
  157. p.latitude,
  158. p.longitude,
  159. );
  160. }).toList();
  161. });
  162. } catch (_) {
  163. } finally {
  164. if (mounted) setState(() => _searching = false);
  165. }
  166. }
  167. void _pick(_SItem item) {
  168. final p = LatLng(item.lat, item.lon);
  169. _mapCtrl.move(p, 15);
  170. setState(() {
  171. _center = p;
  172. _address = item.name;
  173. _results = [];
  174. });
  175. _searchCtrl.clear();
  176. FocusScope.of(context).unfocus();
  177. }
  178. Future<void> _locate() async {
  179. setState(() => _locating = true);
  180. try {
  181. final ok = await Geolocator.requestPermission();
  182. if (ok == LocationPermission.denied ||
  183. ok == LocationPermission.deniedForever) {
  184. if (mounted) {
  185. if (ok == LocationPermission.deniedForever) {
  186. _showLocateError(context);
  187. }
  188. setState(() => _locating = false);
  189. }
  190. return;
  191. }
  192. final pos = await _getPositionWithRetry();
  193. final p = LatLng(pos.latitude, pos.longitude);
  194. _mapCtrl.move(p, 16);
  195. _reverse(p);
  196. } on LocationServiceDisabledException catch (e) {
  197. // 系统位置服务(GPS)总开关关闭
  198. if (mounted) {
  199. _showLocateError(
  200. context,
  201. messageKey: 'locateServiceOff',
  202. detail: e.toString(),
  203. );
  204. }
  205. } on TimeoutException catch (e) {
  206. // 定位超时(GPS 冷启动/室内等场景)
  207. if (mounted) {
  208. _showLocateError(
  209. context,
  210. messageKey: 'locateTimeout',
  211. detail: e.toString(),
  212. );
  213. }
  214. } catch (e) {
  215. if (mounted) _showLocateError(context, detail: e.toString());
  216. }
  217. if (mounted) setState(() => _locating = false);
  218. }
  219. /// 获取当前位置:20 秒超时,超时自动重试一次(GPS 冷启动后第二次定位成功率更高)。
  220. /// 重试仍超时则抛 [TimeoutException],由 _locate 弹超时提示。
  221. Future<Position> _getPositionWithRetry() async {
  222. const timeout = Duration(seconds: 20);
  223. try {
  224. return await Geolocator.getCurrentPosition(
  225. desiredAccuracy: LocationAccuracy.high,
  226. forceAndroidLocationManager: true,
  227. timeLimit: timeout,
  228. );
  229. } on TimeoutException {
  230. return Geolocator.getCurrentPosition(
  231. desiredAccuracy: LocationAccuracy.high,
  232. forceAndroidLocationManager: true,
  233. timeLimit: timeout,
  234. );
  235. }
  236. }
  237. void _showLocateError(
  238. BuildContext context, {
  239. String? messageKey,
  240. String? detail,
  241. }) {
  242. final l10n = AppLocalizations.of(context);
  243. final content = detail == null
  244. ? l10n.get(messageKey ?? 'locateFailed')
  245. : '${l10n.get(messageKey ?? 'locateFailed')}\n\n$detail';
  246. showDialog(
  247. context: context,
  248. useRootNavigator: true,
  249. // 单按钮确认框:TDConfirmDialog 天然只有一个按钮(TDAlertDialog 会自动补默认"取消")
  250. builder: (ctx) => TDConfirmDialog(
  251. content: content,
  252. // 带异常详情时限制高度,由组件自带的滚动处理长内容
  253. contentMaxHeight: detail == null ? 0 : 240,
  254. buttonText: l10n.get('confirm'),
  255. buttonStyle: TDDialogButtonStyle.text,
  256. action: () => Navigator.pop(ctx),
  257. ),
  258. );
  259. }
  260. void _confirm() {
  261. if (_address.isEmpty) return;
  262. Navigator.pop(
  263. context,
  264. LocationResult(
  265. address: _address,
  266. latitude: _center.latitude,
  267. longitude: _center.longitude,
  268. ),
  269. );
  270. }
  271. @override
  272. Widget build(BuildContext context) {
  273. final l10n = AppLocalizations.of(context);
  274. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  275. return AnimatedPadding(
  276. padding: EdgeInsets.only(
  277. bottom: MediaQuery.of(context).viewInsets.bottom,
  278. ),
  279. duration: const Duration(milliseconds: 200),
  280. child: SafeArea(
  281. child: ConstrainedBox(
  282. constraints: BoxConstraints(
  283. maxHeight: MediaQuery.of(context).size.height * 0.9,
  284. ),
  285. child: Container(
  286. decoration: BoxDecoration(
  287. color: colors.bgPage,
  288. borderRadius: const BorderRadius.vertical(
  289. top: Radius.circular(16),
  290. ),
  291. ),
  292. child: Column(
  293. mainAxisSize: MainAxisSize.min,
  294. children: [
  295. // ── 拖拽指示条 ──
  296. Center(
  297. child: Container(
  298. margin: const EdgeInsets.only(top: 8, bottom: 4),
  299. width: 36,
  300. height: 4,
  301. decoration: BoxDecoration(
  302. color: colors.border,
  303. borderRadius: BorderRadius.circular(2),
  304. ),
  305. ),
  306. ),
  307. // ── 标题栏 ──
  308. Padding(
  309. padding: const EdgeInsets.fromLTRB(20, 8, 20, 16),
  310. child: SizedBox(
  311. height: 32,
  312. child: Stack(
  313. children: [
  314. Positioned(
  315. left: 0,
  316. top: 0,
  317. bottom: 0,
  318. child: Center(
  319. child: GestureDetector(
  320. onTap: () => Navigator.pop(context),
  321. child: Icon(
  322. Icons.close,
  323. size: 24,
  324. color: colors.textSecondary,
  325. ),
  326. ),
  327. ),
  328. ),
  329. Positioned(
  330. right: 0,
  331. top: 0,
  332. bottom: 0,
  333. child: Center(
  334. child: GestureDetector(
  335. onTap: _address.isNotEmpty ? _confirm : null,
  336. child: Text(
  337. l10n.get('confirm'),
  338. style: TextStyle(
  339. color: _address.isNotEmpty
  340. ? colors.primary
  341. : colors.textPlaceholder,
  342. fontWeight: FontWeight.w600,
  343. fontSize: 16,
  344. ),
  345. ),
  346. ),
  347. ),
  348. ),
  349. Center(
  350. child: Text(
  351. l10n.get('selectLocation'),
  352. maxLines: 1,
  353. overflow: TextOverflow.ellipsis,
  354. style: TextStyle(
  355. fontSize: 18,
  356. fontWeight: FontWeight.w600,
  357. color: colors.textPrimary,
  358. ),
  359. ),
  360. ),
  361. ],
  362. ),
  363. ),
  364. ),
  365. // ── 地图 ──
  366. Expanded(
  367. child: Stack(
  368. children: [
  369. FlutterMap(
  370. mapController: _mapCtrl,
  371. options: MapOptions(
  372. initialCenter: _center,
  373. initialZoom: 15,
  374. maxZoom: 18,
  375. onMapEvent: (e) {
  376. if (e is MapEventTap) {
  377. FocusScope.of(context).unfocus();
  378. _center = e.tapPosition;
  379. _reverse(_center);
  380. }
  381. if (e is MapEventMoveEnd) {
  382. _center = _mapCtrl.camera.center;
  383. _reverse(_center);
  384. }
  385. },
  386. ),
  387. children: [
  388. TileLayer(
  389. urlTemplate:
  390. 'https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
  391. subdomains: const ['1', '2', '3', '4'],
  392. userAgentPackageName: 'com.amtxts.tboss_oa_module',
  393. ),
  394. ],
  395. ),
  396. Center(
  397. child: IgnorePointer(
  398. child: Column(
  399. mainAxisSize: MainAxisSize.min,
  400. children: [
  401. if (_address.isNotEmpty)
  402. Container(
  403. constraints: const BoxConstraints(
  404. maxWidth: 280,
  405. ),
  406. margin: const EdgeInsets.only(bottom: 2),
  407. padding: const EdgeInsets.symmetric(
  408. horizontal: 10,
  409. vertical: 6,
  410. ),
  411. decoration: BoxDecoration(
  412. color: Colors.white,
  413. borderRadius: BorderRadius.circular(6),
  414. boxShadow: [
  415. BoxShadow(
  416. color: Colors.black.withValues(
  417. alpha: 0.15,
  418. ),
  419. blurRadius: 6,
  420. ),
  421. ],
  422. ),
  423. child: Text(
  424. _address,
  425. maxLines: 2,
  426. overflow: TextOverflow.ellipsis,
  427. textAlign: TextAlign.center,
  428. style: TextStyle(
  429. fontSize: 13,
  430. color: colors.textPrimary,
  431. fontWeight: FontWeight.w500,
  432. ),
  433. ),
  434. ),
  435. const Icon(
  436. Icons.location_on,
  437. size: 40,
  438. color: Colors.red,
  439. ),
  440. ],
  441. ),
  442. ),
  443. ),
  444. SafeArea(
  445. child: Padding(
  446. padding: const EdgeInsets.fromLTRB(12, 12, 12, 0),
  447. child: Container(
  448. decoration: BoxDecoration(
  449. color: Colors.white,
  450. borderRadius: BorderRadius.circular(8),
  451. boxShadow: [
  452. BoxShadow(color: Colors.black12, blurRadius: 4),
  453. ],
  454. ),
  455. child: Column(
  456. mainAxisSize: MainAxisSize.min,
  457. children: [
  458. Padding(
  459. padding: const EdgeInsets.symmetric(
  460. horizontal: 12,
  461. ),
  462. child: TextField(
  463. controller: _searchCtrl,
  464. style: const TextStyle(fontSize: 16),
  465. decoration: InputDecoration(
  466. hintText: l10n.get('searchAddress'),
  467. hintStyle: TextStyle(
  468. color: colors.textPlaceholder,
  469. fontSize: 16,
  470. ),
  471. prefixIcon: const Icon(
  472. Icons.search,
  473. size: 22,
  474. color: Colors.grey,
  475. ),
  476. suffixIcon: _searching
  477. ? const Padding(
  478. padding: EdgeInsets.all(12),
  479. child: SizedBox(
  480. width: 18,
  481. height: 18,
  482. child:
  483. CircularProgressIndicator(
  484. strokeWidth: 2,
  485. ),
  486. ),
  487. )
  488. : _searchCtrl.text.isNotEmpty
  489. ? IconButton(
  490. icon: const Icon(
  491. Icons.close,
  492. size: 20,
  493. color: Colors.grey,
  494. ),
  495. onPressed: () {
  496. _searchCtrl.clear();
  497. setState(() {
  498. _results = [];
  499. _address = '';
  500. });
  501. },
  502. )
  503. : null,
  504. border: InputBorder.none,
  505. contentPadding:
  506. const EdgeInsets.symmetric(
  507. vertical: 14,
  508. ),
  509. ),
  510. onChanged: (_) => _search(),
  511. ),
  512. ),
  513. if (_results.isNotEmpty)
  514. Container(
  515. constraints: const BoxConstraints(
  516. maxHeight: 200,
  517. ),
  518. child: ListView.separated(
  519. shrinkWrap: true,
  520. itemCount: _results.length,
  521. separatorBuilder: (_, _) =>
  522. const Divider(height: 1, indent: 0),
  523. itemBuilder: (_, i) => ListTile(
  524. dense: true,
  525. leading: const Icon(
  526. Icons.location_on,
  527. size: 20,
  528. color: Colors.redAccent,
  529. ),
  530. title: Text(
  531. _results[i].name,
  532. maxLines: 2,
  533. overflow: TextOverflow.ellipsis,
  534. style: const TextStyle(fontSize: 14),
  535. ),
  536. onTap: () => _pick(_results[i]),
  537. ),
  538. ),
  539. ),
  540. ],
  541. ),
  542. ),
  543. ),
  544. ),
  545. Positioned(
  546. right: 12,
  547. bottom: _address.isNotEmpty ? 70 : 32,
  548. child: FloatingActionButton.small(
  549. heroTag: 'loc',
  550. backgroundColor: Colors.white,
  551. onPressed: _locating ? null : _locate,
  552. child: _locating
  553. ? const SizedBox(
  554. width: 20,
  555. height: 20,
  556. child: CircularProgressIndicator(
  557. strokeWidth: 2,
  558. ),
  559. )
  560. : const Icon(
  561. Icons.my_location,
  562. color: Colors.blue,
  563. ),
  564. ),
  565. ),
  566. if (_address.isNotEmpty)
  567. Positioned(
  568. left: 0,
  569. right: 0,
  570. bottom: 0,
  571. child: Container(
  572. padding: EdgeInsets.fromLTRB(
  573. 16,
  574. 12,
  575. 16,
  576. 12 + MediaQuery.of(context).padding.bottom,
  577. ),
  578. color: Colors.white,
  579. child: Row(
  580. children: [
  581. const Icon(
  582. Icons.location_on,
  583. color: Colors.red,
  584. size: 20,
  585. ),
  586. const SizedBox(width: 8),
  587. Expanded(
  588. child: Text(
  589. _address,
  590. maxLines: 2,
  591. overflow: TextOverflow.ellipsis,
  592. ),
  593. ),
  594. ],
  595. ),
  596. ),
  597. ),
  598. ],
  599. ),
  600. ),
  601. ],
  602. ),
  603. ),
  604. ),
  605. ),
  606. );
  607. }
  608. }
  609. class _SItem {
  610. final String name;
  611. final double lat;
  612. final double lon;
  613. const _SItem(this.name, this.lat, this.lon);
  614. }