location_picker.dart 22 KB

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