You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

379 lines
12 KiB

4 years ago
import 'dart:io';
4 years ago
import 'package:dio/dio.dart';
4 years ago
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
7 months ago
import 'package:geolocator/geolocator.dart';
4 years ago
import 'package:huixiang/generated/l10n.dart';
4 years ago
import 'package:huixiang/retrofit/retrofit_api.dart';
7 months ago
import 'package:huixiang/utils/location.dart';
import 'package:huixiang/utils/shared_preference.dart';
4 years ago
import 'package:huixiang/view_widget/request_permission.dart';
7 months ago
import 'package:permission_handler/permission_handler.dart' as PH;
import 'package:shared_preferences/shared_preferences.dart';
import '../data/address.dart';
class AddressMapPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _AddressMapPage();
}
}
class _AddressMapPage extends State<AddressMapPage> {
// //加载自定义地图样式
// void _loadCustomData() async {
// setState(() {
// _mapController?.setCustomMapStyle('assets/map_style/chatian.sty', 0);
// });
// }
// LocationFlutterPlugin? aMapFlutterLocation;
String city = "武汉市";
String keyWord = "";
// @override
// void dispose() {
// super.dispose();
// aMapFlutterLocation?.stopLocation();
// }
ApiService? apiService;
4 years ago
@override
void initState() {
super.initState();
apiService = ApiService(
Dio(),
context: context,
token: SharedInstance.instance.token,
);
LocationInstance.getInstance().startLocation(context, (Position? result) {
print("event: $result");
if (result?.latitude != null && result?.longitude != null) {
latLng = Position(
latitude: result!.latitude,
longitude: result.longitude,
timestamp: DateTime.now(),
accuracy: 0,
altitude: 0,
heading: 0,
speed: 0,
speedAccuracy: 0);
LocationInstance.getInstance().getAddress(result.latitude, result.longitude)
?.then((value) {
7 months ago
if (value != null) {
city = value.city ?? "";
}
});
7 months ago
saveLatLng(result);
searchPoi(latLng);
}
});
// _setLocOption();
//
// getLatLng();
startLocation();
}
// /// 设置android端和ios端定位参数
// void _setLocOption() {
// /// android 端设置定位参数
// BaiduLocationAndroidOption androidOption =
// BaiduLocationAndroidOption(coordType: BMFLocationCoordType.gcj02);
// androidOption.setCoorType("GCJ02"); // 设置返回的位置坐标系类型
// androidOption.setIsNeedAltitude(true); // 设置是否需要返回海拔高度信息
// androidOption.setIsNeedAddress(true); // 设置是否需要返回地址信息
// androidOption.setIsNeedLocationPoiList(true); // 设置是否需要返回周边poi信息
// androidOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
// androidOption.setIsNeedLocationDescribe(true); // 设置是否需要返回位置描述
// androidOption.setOpenGps(true); // 设置是否需要使用gps
// androidOption.setLocationMode(BMFLocationMode.hightAccuracy); // 设置定位模式
// androidOption.setScanspan(0); // 设置发起定位请求时间间隔
// androidOption.setCoordType(BMFLocationCoordType.gcj02);
//
// Map androidMap = androidOption.getMap();
//
// /// ios 端设置定位参数
// BaiduLocationIOSOption iosOption =
// BaiduLocationIOSOption(coordType: BMFLocationCoordType.gcj02);
// iosOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
// iosOption.setBMKLocationCoordinateType(
// "BMKLocationCoordinateTypeGCJ02"); // 设置返回的位置坐标系类型
// iosOption.setActivityType(BMFActivityType.automotiveNavigation); // 设置应用位置类型
// iosOption.setLocationTimeout(10); // 设置位置获取超时时间
// iosOption.setDesiredAccuracy(BMFDesiredAccuracy.best); // 设置预期精度参数
// iosOption.setReGeocodeTimeout(10); // 设置获取地址信息超时时间
// iosOption.setDistanceFilter(1000); // 设置定位最小更新距离
// iosOption.setAllowsBackgroundLocationUpdates(true); // 是否允许后台定位
// iosOption.setPauseLocUpdateAutomatically(true); // 定位是否会被系统自动暂停
// iosOption.coordType = BMFLocationCoordType.gcj02;
//
// Map iosMap = iosOption.getMap();
//
// aMapFlutterLocation?.prepareLoc(androidMap, iosMap);
// }
Position? center;
List<Address>? poiList;
4 years ago
searchPoi(Position? latLng) async {
4 years ago
keyWord = textEditingController.text;
4 years ago
print("keyWord: ${keyWord}");
var addressPoi = await apiService?.searchPoi(
"${latLng?.latitude}", "${latLng?.longitude}", keyWord, 20, 1);
//如果定位列表无法显示,可以考虑数据是否不在当前字段里面;例:原数据放在['pois']里面,后改成了数据放在['entrances']里面
List<dynamic> poi = addressPoi['pois'] ?? addressPoi['entrances'];
4 years ago
poiList = poi
.map((e) => Address.fromJson({
4 years ago
"address": e["address"] is List ? "" : e["address"],
"area": e["adname"],
"city": e["cityname"],
"province": e["pname"],
"latitude": e["location"].toString().split(",")[0],
"longitude": e["location"].toString().split(",")[1],
"cityInfo": e["name"],
"id": "",
"mid": "",
"phone": "",
"tag": "",
"username": "",
"isDefault": true,
}))
4 years ago
.toList();
setState(() {});
// BMFPoiNearbySearch bmfPoiNearbySearch = BMFPoiNearbySearch();
// bmfPoiNearbySearch.onGetPoiNearbySearchResult(
// callback: (BMFPoiSearchResult result, BMFSearchErrorCode errorCode) {
// // if ((DateTime.now().millisecondsSinceEpoch - time) > 2000) {
// result.poiInfoList.map((e) => print("sssssssssss:${e.toMap()}"));
// poiList = result.poiInfoList;
// print("object112221: ${poiList.length}");
// setState(() {
// time = DateTime.now().millisecondsSinceEpoch;
// });
// // }
// });
// bmfPoiNearbySearch.poiNearbySearch(BMFPoiNearbySearchOption(
// keywords: [" "],
// tags: ["小区","住宅","地标","建筑"],
// radius: 100000,
// location: latLng,
// pageSize: 20,
// pageIndex: 0,
// isRadiusLimit: true,
// ));
}
4 years ago
int time = 0;
startLocation() async {
7 months ago
if (!(await PH.Permission.locationWhenInUse.serviceStatus.isEnabled)) {
4 years ago
enableLocation();
return;
}
7 months ago
if (await PH.Permission.location.isPermanentlyDenied) {
4 years ago
requestDialog();
7 months ago
} else if (await PH.Permission.location.isGranted) {
// S.current.zhengzaijiazai.loading;
7 months ago
center = await Geolocator.getCurrentPosition();
4 years ago
Future.delayed(Duration(seconds: 6), () {
SmartDialog.dismiss();
4 years ago
});
}
// else if (await PH.Permission.location.) {
// await PH.Permission.location.request();
// }
else {
4 years ago
if (Platform.isIOS) {
//去设置中心
requestDialog();
} else {
7 months ago
await PH.Permission.location.request();
}
}
}
4 years ago
enableLocation() {
showCupertinoDialog(
context: context,
builder: (context) {
return RequestPermission(
"assets/image/icon_permission_location_bg.webp",
4 years ago
S.of(context).nindingweigongnengweikaiqi,
S.of(context).weilexiangnintuijianfujindemendianxinxi,
S.of(context).dakaidingwei,
4 years ago
(result) async {
4 years ago
if (result) {
7 months ago
// final AndroidIntent intent = AndroidIntent(
// action: 'action_location_source_settings',
// package: "com.zsw.huixiang");
// await intent.launch();
4 years ago
// startLocation();
7 months ago
Geolocator.openLocationSettings();
4 years ago
}
},
heightRatioWithWidth: 0.82,
);
},
);
}
4 years ago
requestDialog() {
showCupertinoDialog(
context: context,
builder: (context) {
return RequestPermission(
"assets/image/icon_permission_location_bg.webp",
4 years ago
S.of(context).nindingweiquanxianweiyunxu,
S.of(context).weilexiangnintuijianfujindemendianxinxi,
S.of(context).kaiqiquanxian,
4 years ago
(result) async {
4 years ago
if (result) {
7 months ago
await PH.openAppSettings();
if (await PH.Permission.location.isGranted) {
4 years ago
startLocation();
}
}
},
heightRatioWithWidth: 0.82,
);
},
);
4 years ago
}
Position? latLng;
4 years ago
saveLatLng(Position? latLng) async {
SharedInstance.instance.saveLatLng(latLng);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
searchWidget(),
Expanded(
4 years ago
child: Container(
child: ListView.separated(
padding: EdgeInsets.symmetric(vertical: 0),
itemCount: poiList?.length ?? 0,
4 years ago
itemBuilder: (context, position) {
return InkWell(
onTap: () {
Navigator.of(context).pop(poiList![position].toJson());
4 years ago
},
child: addressItem(poiList![position]),
4 years ago
);
},
separatorBuilder: (context, position) {
4 years ago
return Container(
height: 1,
4 years ago
margin: EdgeInsets.symmetric(horizontal: 16.w),
4 years ago
color: Color(0xFFF1F1F1),
);
},
),
),
flex: 1,
)
],
),
);
}
4 years ago
Widget addressItem(Address address) {
4 years ago
return Container(
4 years ago
margin: EdgeInsets.symmetric(vertical: 16.h, horizontal: 16.w),
4 years ago
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
4 years ago
address.cityInfo ?? "",
4 years ago
overflow: TextOverflow.ellipsis,
style: TextStyle(
4 years ago
fontSize: 16.sp,
4 years ago
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
SizedBox(
4 years ago
height: 4.h,
4 years ago
),
Text(
"${address.province}${address.city}${address.area}${address.addressStr}",
4 years ago
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Color(0xFF4C4C4C),
4 years ago
fontSize: 14.sp,
4 years ago
),
4 years ago
),
4 years ago
],
),
);
}
4 years ago
TextEditingController textEditingController = TextEditingController();
Widget searchWidget() {
return Container(
4 years ago
height: 36.h,
margin: EdgeInsets.fromLTRB(16, 48, 16, 8),
padding: EdgeInsets.fromLTRB(10, 6, 16, 6),
decoration: BoxDecoration(
4 years ago
color: Colors.white,
borderRadius: BorderRadius.all(
Radius.circular(4),
),
4 years ago
boxShadow: [
BoxShadow(
color: Colors.black.withAlpha(12),
offset: Offset(0, 3),
blurRadius: 14,
spreadRadius: 0,
),
4 years ago
],
),
child: Row(
4 years ago
mainAxisSize: MainAxisSize.max,
children: [
Icon(
Icons.search,
size: 24,
color: Colors.black,
),
Expanded(
child: TextField(
4 years ago
controller: textEditingController,
textInputAction: TextInputAction.search,
onEditingComplete: () {
FocusScope.of(context).requestFocus(FocusNode());
searchPoi(center);
},
decoration: InputDecoration(border: InputBorder.none),
),
),
4 years ago
InkWell(
onTap: () {
textEditingController.clear();
},
child: Icon(
Icons.close,
size: 19,
color: Colors.grey,
),
),
],
),
);
}
}