location_picker.dart 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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';
  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 Geolocator.getCurrentPosition(
  193. desiredAccuracy: LocationAccuracy.high,
  194. forceAndroidLocationManager: true,
  195. timeLimit: const Duration(seconds: 10),
  196. );
  197. final p = LatLng(pos.latitude, pos.longitude);
  198. _mapCtrl.move(p, 16);
  199. _reverse(p);
  200. } on LocationServiceDisabledException catch (e) {
  201. // 系统位置服务(GPS)总开关关闭
  202. if (mounted) {
  203. _showLocateError(
  204. context,
  205. messageKey: 'locateServiceOff',
  206. detail: e.toString(),
  207. );
  208. }
  209. } on TimeoutException catch (e) {
  210. // 定位超时(GPS 冷启动/室内等场景)
  211. if (mounted) {
  212. _showLocateError(
  213. context,
  214. messageKey: 'locateTimeout',
  215. detail: e.toString(),
  216. );
  217. }
  218. } catch (e) {
  219. if (mounted) _showLocateError(context, detail: e.toString());
  220. }
  221. if (mounted) setState(() => _locating = false);
  222. }
  223. void _showLocateError(
  224. BuildContext context, {
  225. String? messageKey,
  226. String? detail,
  227. }) {
  228. final l10n = AppLocalizations.of(context);
  229. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  230. final content = detail == null
  231. ? l10n.get(messageKey ?? 'locateFailed')
  232. : '${l10n.get(messageKey ?? 'locateFailed')}\n\n$detail';
  233. showDialog(
  234. context: context,
  235. useRootNavigator: true,
  236. builder: (ctx) => TDAlertDialog(
  237. content: content,
  238. // 带异常详情时限制高度,由 TDAlertDialog 自带的滚动处理长内容
  239. contentMaxHeight: detail == null ? 0 : 240,
  240. buttonStyle: TDDialogButtonStyle.text,
  241. rightBtn: TDDialogButtonOptions(
  242. title: l10n.get('confirm'),
  243. titleColor: colors.primary,
  244. action: () => Navigator.pop(ctx),
  245. ),
  246. ),
  247. );
  248. }
  249. void _confirm() {
  250. if (_address.isEmpty) return;
  251. Navigator.pop(
  252. context,
  253. LocationResult(
  254. address: _address,
  255. latitude: _center.latitude,
  256. longitude: _center.longitude,
  257. ),
  258. );
  259. }
  260. @override
  261. Widget build(BuildContext context) {
  262. final l10n = AppLocalizations.of(context);
  263. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  264. return AnimatedPadding(
  265. padding: EdgeInsets.only(
  266. bottom: MediaQuery.of(context).viewInsets.bottom,
  267. ),
  268. duration: const Duration(milliseconds: 200),
  269. child: SafeArea(
  270. child: ConstrainedBox(
  271. constraints: BoxConstraints(
  272. maxHeight: MediaQuery.of(context).size.height * 0.9,
  273. ),
  274. child: Container(
  275. decoration: BoxDecoration(
  276. color: colors.bgPage,
  277. borderRadius: const BorderRadius.vertical(
  278. top: Radius.circular(16),
  279. ),
  280. ),
  281. child: Column(
  282. mainAxisSize: MainAxisSize.min,
  283. children: [
  284. // ── 拖拽指示条 ──
  285. Center(
  286. child: Container(
  287. margin: const EdgeInsets.only(top: 8, bottom: 4),
  288. width: 36,
  289. height: 4,
  290. decoration: BoxDecoration(
  291. color: colors.border,
  292. borderRadius: BorderRadius.circular(2),
  293. ),
  294. ),
  295. ),
  296. // ── 标题栏 ──
  297. Padding(
  298. padding: const EdgeInsets.fromLTRB(20, 8, 20, 16),
  299. child: SizedBox(
  300. height: 32,
  301. child: Stack(
  302. children: [
  303. Positioned(
  304. left: 0,
  305. top: 0,
  306. bottom: 0,
  307. child: Center(
  308. child: GestureDetector(
  309. onTap: () => Navigator.pop(context),
  310. child: Icon(
  311. Icons.close,
  312. size: 24,
  313. color: colors.textSecondary,
  314. ),
  315. ),
  316. ),
  317. ),
  318. Positioned(
  319. right: 0,
  320. top: 0,
  321. bottom: 0,
  322. child: Center(
  323. child: GestureDetector(
  324. onTap: _address.isNotEmpty ? _confirm : null,
  325. child: Text(
  326. l10n.get('confirm'),
  327. style: TextStyle(
  328. color: _address.isNotEmpty
  329. ? colors.primary
  330. : colors.textPlaceholder,
  331. fontWeight: FontWeight.w600,
  332. fontSize: 16,
  333. ),
  334. ),
  335. ),
  336. ),
  337. ),
  338. Center(
  339. child: Text(
  340. l10n.get('selectLocation'),
  341. maxLines: 1,
  342. overflow: TextOverflow.ellipsis,
  343. style: TextStyle(
  344. fontSize: 18,
  345. fontWeight: FontWeight.w600,
  346. color: colors.textPrimary,
  347. ),
  348. ),
  349. ),
  350. ],
  351. ),
  352. ),
  353. ),
  354. // ── 地图 ──
  355. Expanded(
  356. child: Stack(
  357. children: [
  358. FlutterMap(
  359. mapController: _mapCtrl,
  360. options: MapOptions(
  361. initialCenter: _center,
  362. initialZoom: 15,
  363. maxZoom: 18,
  364. onMapEvent: (e) {
  365. if (e is MapEventTap) {
  366. FocusScope.of(context).unfocus();
  367. _center = e.tapPosition;
  368. _reverse(_center);
  369. }
  370. if (e is MapEventMoveEnd) {
  371. _center = _mapCtrl.camera.center;
  372. _reverse(_center);
  373. }
  374. },
  375. ),
  376. children: [
  377. TileLayer(
  378. urlTemplate:
  379. 'https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
  380. subdomains: const ['1', '2', '3', '4'],
  381. userAgentPackageName: 'com.amtxts.tboss_oa_module',
  382. ),
  383. ],
  384. ),
  385. Center(
  386. child: IgnorePointer(
  387. child: Column(
  388. mainAxisSize: MainAxisSize.min,
  389. children: [
  390. if (_address.isNotEmpty)
  391. Container(
  392. constraints: const BoxConstraints(
  393. maxWidth: 280,
  394. ),
  395. margin: const EdgeInsets.only(bottom: 2),
  396. padding: const EdgeInsets.symmetric(
  397. horizontal: 10,
  398. vertical: 6,
  399. ),
  400. decoration: BoxDecoration(
  401. color: Colors.white,
  402. borderRadius: BorderRadius.circular(6),
  403. boxShadow: [
  404. BoxShadow(
  405. color: Colors.black.withValues(
  406. alpha: 0.15,
  407. ),
  408. blurRadius: 6,
  409. ),
  410. ],
  411. ),
  412. child: Text(
  413. _address,
  414. maxLines: 2,
  415. overflow: TextOverflow.ellipsis,
  416. textAlign: TextAlign.center,
  417. style: TextStyle(
  418. fontSize: 13,
  419. color: colors.textPrimary,
  420. fontWeight: FontWeight.w500,
  421. ),
  422. ),
  423. ),
  424. const Icon(
  425. Icons.location_on,
  426. size: 40,
  427. color: Colors.red,
  428. ),
  429. ],
  430. ),
  431. ),
  432. ),
  433. SafeArea(
  434. child: Padding(
  435. padding: const EdgeInsets.fromLTRB(12, 12, 12, 0),
  436. child: Container(
  437. decoration: BoxDecoration(
  438. color: Colors.white,
  439. borderRadius: BorderRadius.circular(8),
  440. boxShadow: [
  441. BoxShadow(color: Colors.black12, blurRadius: 4),
  442. ],
  443. ),
  444. child: Column(
  445. mainAxisSize: MainAxisSize.min,
  446. children: [
  447. Padding(
  448. padding: const EdgeInsets.symmetric(
  449. horizontal: 12,
  450. ),
  451. child: TextField(
  452. controller: _searchCtrl,
  453. style: const TextStyle(fontSize: 16),
  454. decoration: InputDecoration(
  455. hintText: l10n.get('searchAddress'),
  456. hintStyle: TextStyle(
  457. color: colors.textPlaceholder,
  458. fontSize: 16,
  459. ),
  460. prefixIcon: const Icon(
  461. Icons.search,
  462. size: 22,
  463. color: Colors.grey,
  464. ),
  465. suffixIcon: _searching
  466. ? const Padding(
  467. padding: EdgeInsets.all(12),
  468. child: SizedBox(
  469. width: 18,
  470. height: 18,
  471. child:
  472. CircularProgressIndicator(
  473. strokeWidth: 2,
  474. ),
  475. ),
  476. )
  477. : _searchCtrl.text.isNotEmpty
  478. ? IconButton(
  479. icon: const Icon(
  480. Icons.close,
  481. size: 20,
  482. color: Colors.grey,
  483. ),
  484. onPressed: () {
  485. _searchCtrl.clear();
  486. setState(() {
  487. _results = [];
  488. _address = '';
  489. });
  490. },
  491. )
  492. : null,
  493. border: InputBorder.none,
  494. contentPadding:
  495. const EdgeInsets.symmetric(
  496. vertical: 14,
  497. ),
  498. ),
  499. onChanged: (_) => _search(),
  500. ),
  501. ),
  502. if (_results.isNotEmpty)
  503. Container(
  504. constraints: const BoxConstraints(
  505. maxHeight: 200,
  506. ),
  507. child: ListView.separated(
  508. shrinkWrap: true,
  509. itemCount: _results.length,
  510. separatorBuilder: (_, _) =>
  511. const Divider(height: 1, indent: 0),
  512. itemBuilder: (_, i) => ListTile(
  513. dense: true,
  514. leading: const Icon(
  515. Icons.location_on,
  516. size: 20,
  517. color: Colors.redAccent,
  518. ),
  519. title: Text(
  520. _results[i].name,
  521. maxLines: 2,
  522. overflow: TextOverflow.ellipsis,
  523. style: const TextStyle(fontSize: 14),
  524. ),
  525. onTap: () => _pick(_results[i]),
  526. ),
  527. ),
  528. ),
  529. ],
  530. ),
  531. ),
  532. ),
  533. ),
  534. Positioned(
  535. right: 12,
  536. bottom: _address.isNotEmpty ? 70 : 32,
  537. child: FloatingActionButton.small(
  538. heroTag: 'loc',
  539. backgroundColor: Colors.white,
  540. onPressed: _locating ? null : _locate,
  541. child: _locating
  542. ? const SizedBox(
  543. width: 20,
  544. height: 20,
  545. child: CircularProgressIndicator(
  546. strokeWidth: 2,
  547. ),
  548. )
  549. : const Icon(
  550. Icons.my_location,
  551. color: Colors.blue,
  552. ),
  553. ),
  554. ),
  555. if (_address.isNotEmpty)
  556. Positioned(
  557. left: 0,
  558. right: 0,
  559. bottom: 0,
  560. child: Container(
  561. padding: EdgeInsets.fromLTRB(
  562. 16,
  563. 12,
  564. 16,
  565. 12 + MediaQuery.of(context).padding.bottom,
  566. ),
  567. color: Colors.white,
  568. child: Row(
  569. children: [
  570. const Icon(
  571. Icons.location_on,
  572. color: Colors.red,
  573. size: 20,
  574. ),
  575. const SizedBox(width: 8),
  576. Expanded(
  577. child: Text(
  578. _address,
  579. maxLines: 2,
  580. overflow: TextOverflow.ellipsis,
  581. ),
  582. ),
  583. ],
  584. ),
  585. ),
  586. ),
  587. ],
  588. ),
  589. ),
  590. ],
  591. ),
  592. ),
  593. ),
  594. ),
  595. );
  596. }
  597. }
  598. class _SItem {
  599. final String name;
  600. final double lat;
  601. final double lon;
  602. const _SItem(this.name, this.lat, this.lon);
  603. }