map_choice_point.dart
20.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
import 'dart:async';
// import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:contacts_service/contacts_service.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
// import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_maps_webservice/places.dart' as Places;
import 'package:one_key/constant/constant.dart';
import 'package:one_key/utils/dialog_util.dart';
import 'package:one_key/utils/misc.dart';
import 'package:one_key/route/navigator_util.dart';
import 'package:one_key/utils/utils.dart';
import 'package:one_key/widgets/system_app_bar.dart';
import 'package:permission_handler/permission_handler.dart';
// import 'package:demo/resources/custom_text_style.dart';
// import 'package:demo/utils/misc.dart';
// import 'package:demo/widgets/network_state/page_loading.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
// import 'package:google_maps_webservice/places.dart';
// import 'package:one_key/library/google_maps_webservice/places.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geocoding/geocoding.dart';
class MapChoicePointPage extends StatefulWidget {
final String long;
final String lat;
MapChoicePointPage({Key key, this.long, this.lat}) : super(key: key);
@override
_MapChoicePointPageState createState() => _MapChoicePointPageState();
}
class _MapChoicePointPageState extends State<MapChoicePointPage> {
final Completer<GoogleMapController> _controller =
Completer<GoogleMapController>();
// List<Poi> poiList;
static List<PoiModel> list = new List();
// static List<PoiModel> searchlist = new List();
PoiModel poiModel;
String keyword = "";
String address = "";
bool isloading = true;
double latitude = 39.684670899;
double longitude = 118.17630045;
CameraPosition _kGooglePlex = CameraPosition(
target: LatLng(39.684670899, 118.17630045),
zoom: 14.4746,
);
final Places.GoogleMapsPlaces _places =
Places.GoogleMapsPlaces(apiKey: Constant.googleKey);
Places.PlacesSearchResponse _placesSearch;
// final _controllerKeywords = TextEditingController();
@override
void initState() {
super.initState();
if (widget.long != null && widget.long != '' && widget.long != 'null') {
longitude = double.parse(widget.long);
}
if (widget.lat != null && widget.lat != '' && widget.lat != 'null') {
latitude = double.parse(widget.lat);
}
_kGooglePlex = CameraPosition(
target: LatLng(latitude, longitude),
zoom: 14.4746,
);
WidgetsBinding.instance.addPostFrameCallback((_) async {
_requestLocationPermission();
});
}
Future<bool> checkLocationPermission() async {
PermissionStatus permissionStatus = await Permission.location.status;
if (permissionStatus == PermissionStatus.granted) {
return true;
} else {
return false;
}
}
/// 检查权限并定
// _getLocationPermission() async {
// if (!(await checkPermission(Permission.location))) {
// //没有定位权限
// //申请定位权限
// _requestLocationPermission();
// } else {
// //去定位
// _requestLocationPermission();
// }
// }
/// 获取定位权限
_requestLocationPermission() async {
// await AmapLocation.instance.updatePrivacyShow(true);
// await AmapLocation.instance.updatePrivacyAgree(true);
bool serviceEnabled;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
Utils.showToast('位置服务被禁用');
return;
// return Future.error('位置服务被禁用');
}
bool canLocation = false;
if (!(await checkPermission(Permission.location))) {
//没有定位权限
//申请定位权限
canLocation = await requestPermission(Permission.location);
} else {
canLocation = true;
}
// bool canLocation = await requestPermission(Permission.location);
// 单次定位
if (canLocation) {
Future.delayed(Duration(milliseconds: 200), () async {
Position location = await Geolocator.getCurrentPosition();
// final location = await AmapLocation.instance.fetchLocation(
// // needAddress: true,
// // mode: LocationAccuracy.High,
// // timeout: Duration(seconds: 10)
// );
if (location == null) //网络不好,定位失败
{
// App.sp.setString("lat", "39.684670899");
// App.sp.setString("lng", "118.17630045");
} else {
if (widget.long == null ||
widget.long == '' ||
widget.long == 'null') {
latitude = location.latitude;
longitude = location.longitude;
if (_controller != null) {
//设置地图扎针为获取到的当前位置
final GoogleMapController controller = await _controller.future;
CameraPosition _kLake = CameraPosition(
// bearing: 192.8334901395799, //地图的方位旋转角度
target: LatLng(latitude, longitude),
// tilt: 59.440717697143555,
zoom: 14.4746);
controller.animateCamera(CameraUpdate.newCameraPosition(_kLake));
_loadData(LatLng(latitude, longitude));
// _controller.setCenterCoordinate(
// LatLng(location.latLng.latitude, location.latLng.longitude));
}
setState(() {});
}
}
});
} else {
//无权限
}
}
// Future<Position> _determinePosition() async {
// bool serviceEnabled;
// LocationPermission permission;
// // Test if location services are enabled.
// serviceEnabled = await Geolocator.isLocationServiceEnabled();
// if (!serviceEnabled) {
// // Location services are not enabled don't continue
// // accessing the position and request users of the
// // App to enable the location services.
// return Future.error('Location services are disabled.');
// }
// permission = await Geolocator.checkPermission();
// if (permission == LocationPermission.denied) {
// permission = await Geolocator.requestPermission();
// if (permission == LocationPermission.denied) {
// // Permissions are denied, next time you could try
// // requesting permissions again (this is also where
// // Android's shouldShowRequestPermissionRationale
// // returned true. According to Android guidelines
// // your App should show an explanatory UI now.
// return Future.error('Location permissions are denied');
// }
// }
// if (permission == LocationPermission.deniedForever) {
// // Permissions are denied forever, handle appropriately.
// return Future.error(
// 'Location permissions are permanently denied, we cannot request permissions.');
// }
// // When we reach here, permissions are granted and we can
// // continue accessing the position of the device.
// return await Geolocator.getCurrentPosition();
// }
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false, //防止底部布局被顶起
appBar: SystemAppBar(
'选择位置信息',
onTap: () {
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
},
),
body: Column(
children: <Widget>[
Theme(
data: new ThemeData(
primaryColor: Color(0xFFFFCA28), hintColor: Color(0xFFFFCA28)),
child: Container(
color: Color(0xFFFFCA28),
padding: EdgeInsets.all(5),
child: Container(
height: 36,
margin: EdgeInsets.only(left: 5, right: 5, bottom: 5),
child: TextField(
style: TextStyle(fontSize: 16, letterSpacing: 1.0),
controller: TextEditingController.fromValue(TextEditingValue(
// 设置内容
text: keyword,
selection: TextSelection.fromPosition(TextPosition(
affinity: TextAffinity.downstream,
offset: keyword?.length ?? 0)),
// 保持光标在最后
)),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(40)),
),
hintText: '输入关键字',
hintStyle:
TextStyle(color: Color(0xFFBEBEBE), fontSize: 14),
contentPadding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 1),
prefixIcon: Icon(
Icons.search,
color: Colors.grey,
size: 20,
),
suffixIcon: IconButton(
icon: Icon(
Icons.clear,
color: Colors.grey,
size: 20,
),
onPressed: () {
keyword = "";
setState(() {});
},
),
fillColor: Colors.white,
filled: true,
),
inputFormatters: [],
//内容改变的回调
onChanged: (text) {
print('change $text');
keyword = text;
},
//内容提交(按回车)的回调
onSubmitted: (text) {
print('submit $text');
// 触发关闭弹出来的键盘。
keyword = text;
setState(() {
isloading = true;
FocusScope.of(context).requestFocus(FocusNode());
});
searchAroundAddress(text.toString());
},
//按回车时调用
onEditingComplete: () {
print('onEditingComplete');
},
),
),
),
),
//地图展示UI
Container(
height: 300,
child: Stack(
children: <Widget>[
GoogleMap(
// markers: ,
mapType: MapType.normal,
initialCameraPosition: _kGooglePlex,
onTap: (position){
_loadData(LatLng(
position.latitude, position.longitude));
}
,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
// markers: Set<Marker>.of(list.map((place) => Marker(
// markerId: MarkerId(place.title??''),
// position: place.latLng,
// ))),
onCameraMove: (position) {
// _loadData(LatLng(
// position.target.latitude, position.target.longitude));
},
),
// showZoomControl: false,
// centerCoordinate: LatLng(latitude, longitude),
// maskDelay: Duration(milliseconds: 500),
// zoomLevel: 16,
// onMapCreated: (controller) async {
// _controller = controller;
// _controller
// .setCenterCoordinate(LatLng(latitude, longitude));
// // if (await requestPermission(PermissionGroup.location)) {
// // await controller.showMyLocation(true);
// // await controller?.showLocateControl(true);
// // final latLng = await _controller?.getLocation(
// // delay: Duration(seconds: 2));
// // await enableFluttifyLog(false); // 关闭log
// // _loadData(latLng);
// // } else {
// // //无权限
// // _showLocPemWidget();
// // }
// },
// onMapMoveEnd: (MapMove move) async {
// _loadData(move.coordinate);
// },
// ),
Center(
child: Icon(
Icons.place,
size: 36.0,
color: Color(0xFFFF0000),
),
),
],
),
),
Expanded(
flex: 1,
child: Visibility(
visible: !isloading,
maintainSize: false,
maintainSemantics: false,
maintainInteractivity: false,
replacement: Center(
child: CupertinoActivityIndicator(),
),
child: ListView.builder(
itemCount: list.length,
itemBuilder: (BuildContext context, int position) {
print("itemBuilder" + list.length.toString());
PoiModel item = list[position];
return InkWell(
child: Column(
children: <Widget>[
Container(
margin:
EdgeInsets.only(top: 8, bottom: 5, left: 10),
child: Row(
children: <Widget>[
Icon(
Icons.place,
size: 20.0,
color: position == 0
? Colors.green
: Colors.grey,
),
Expanded(
child: Text(item.title??'',
style: TextStyle(
fontSize: 16,
color: position == 0
? Colors.green
: Color(0xFF787878))))
],
),
),
Container(
margin:
EdgeInsets.only(top: 5, bottom: 5, left: 18),
alignment: Alignment.centerLeft,
child: Text(
item.address,
style: TextStyle(
fontSize: 14,
color: Color(0xFF646464),
),
),
),
Divider(
height: 1,
)
],
),
onTap: () async {
// await _controller.setCenterCoordinate(
// LatLng(item.latLng.latitude, item.latLng.longitude),
// zoomLevel: 16);
if (Navigator.canPop(context)) {
Navigator.pop(context, {
'address': item.address,
'lat': item.latLng.latitude.toString(),
'lng': item.latLng.longitude.toString()
});
}
},
);
}),
),
),
],
),
);
}
// void _searchPlace(LatLng latLng) async {
// setState(() {
// isloading = true;
// });
// /// 逆地理编码(坐标转地址)
// ///
// ///
// _placesSearch = await _places.searchByText(_controller.text,
// sessionToken: SessionToken(uuid: Uuid().v4()));
// setState(() {
// // Update the UI with the new places search result
// });
// }
// void _reverseGeocode(double lat, double lon) async {
// List<Placemark> placemarks =
// await placemarkFromCoordinates(lat, lon);
// Placemark place = placemarks[0];
// print('Address: ${place.name}, ${place.locality}, ${place.country}');
// }
void _loadData(LatLng latLng) async {
setState(() {
isloading = true;
});
/// 逆地理编码(坐标转地址)
List<Placemark> placemarks =
await placemarkFromCoordinates(latLng.latitude, latLng.longitude);
Placemark place = placemarks[0];
// print('Address: ${place.name}, ${place.locality}, ${place.country}');
// address = '${place.administrativeArea}, ${place.locality}, ${place.subLocality},${place.thoroughfare},${place.subThoroughfare}';
// await AmapLocation.instance.updatePrivacyShow(true);
// await AmapLocation.instance.updatePrivacyAgree(true);
// ReGeocode reGeocodeList = await AmapSearch.instance.searchReGeocode(
// latLng,
// );
address = place.street;
// // print(await reGeocodeList.toFutureString());
// address = reGeocodeList.formatAddress;
// await AmapLocation.instance.updatePrivacyShow(true);
// await AmapLocation.instance.updatePrivacyAgree(true);
//通过经纬度搜索周边信息
// PlacesSearchResponse response = await _places.searchNearbyWithRadius(Location(lat: 31.0424, lng: 42.421), 500);
Places.PlacesSearchResponse response = await _places.searchNearbyWithRadius(
Places.Location(lat: latLng.latitude, lng: latLng.longitude), 1500);
// Places.PlacesSearchResponse response = await _places.searchByText(
// address,
// radius: 500,
// );
// Places.PlacesSearchResponse response = await _places.searchNearbyWithRankBy(
// Places.Location(lat: latLng.latitude, lng: latLng.longitude), "district");
// Places.PlacesSearchResult fff = response.results[0];
// List<Place> places = response.getPlaces();
// final poiList = await AmapSearch.instance.searchAround(
// latLng,
// city: "",
// );
poiModel = new PoiModel("当前位置", address, latLng);
// /通过经纬度,获取当前位置的地理位置
list.clear();
list.add(poiModel);
for (var poi in response.results) {
String title = await poi.name;
// String cityName = await poi.cityName;
// String provinceName = await poi.provinceName;
// String address = await poi.formattedAddress;
// LatLng latLng = await poi.;
// String bussniss = poi.businessArea;
LatLng latLng =
LatLng(poi.geometry.location.lat, poi.geometry.location.lng);
List<Placemark> placemarks =
await placemarkFromCoordinates(latLng.latitude, latLng.longitude);
Placemark place = placemarks[0];
// print('Address: ${place.name}, ${place.locality}, ${place.country}');
// address = '${place.administrativeArea}, ${place.locality}, ${place.subLocality},${place.thoroughfare},${place.subThoroughfare}';
// await AmapLocation.instance.updatePrivacyShow(true);
// await AmapLocation.instance.updatePrivacyAgree(true);
// ReGeocode reGeocodeList = await AmapSearch.instance.searchReGeocode(
// latLng,
// );
String address = place.street;
list.add(new PoiModel(title.toString(), address.toString(), latLng));
}
setState(() {
isloading = false;
});
}
void searchAroundAddress(String text) async {
// await AmapLocation.instance.updatePrivacyShow(true);
// await AmapLocation.instance.updatePrivacyAgree(true);
// final poiList = await AmapSearch.instance.searchKeyword(
// text,
// city: "",
// );
Places.PlacesSearchResponse response = await _places.searchByText(
text,
radius: 1500,
);
list.clear();
list.add(poiModel);
for (var poi in response.results) {
String title = await poi.name;
// LatLng latLng = await poi.latLng;
// String cityName = await poi.cityName;
// String provinceName = await poi.provinceName;
String address = await poi.formattedAddress??'';
LatLng latLng = LatLng(poi.geometry.location.lat,poi.geometry.location.lng);
list.add(new PoiModel(title.toString(), address.toString(), latLng));
}
setState(() {
isloading = false;
FocusScope.of(context).requestFocus(FocusNode());
});
}
}
class PoiModel {
LatLng latLng;
String title;
String address;
PoiModel(this.title, this.address, this.latLng);
}