location_picker.dart 22 KB

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