所以,我有一个Flutter应用程序,主要使用这些包:flutter_map,get,LatLng2.我使用GetX作为状态管理,我的目标是从REST API获取数据,并将此数据显示到屏幕上。这是我的设置。
首先我有这个MapController:
class MapAppController extends GetxController {
LatLng center = LatLng(28.0339, 1.6596);
Marker? userLocationMarker;
bool isLoading = false;
List<Marker> markers = [];
Future<void> getLocation() async {
isLoading = true;
update();
LocationPermission permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// TODO: handle the scenario when the user denies location permission
} else if (permission == LocationPermission.deniedForever) {
// TODO: handle the scenario when the user denies location permission permanently
} else {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
LatLng userLocation = LatLng(position.latitude, position.longitude);
center = userLocation;
userLocationMarker = Marker(
width: 40.0,
height: 40.0,
point: userLocation,
builder: (ctx) => const Icon(
Icons.location_on,
size: 45,
color: Colors.red,
),
);
isLoading = false;
update();
}
}
Future<void> populateMarkers() async {
isLoading = true;
update();
final Map<String, LatLng> clustersCentroid =
await DjangoHelper.getClusterCentroid();
markers.clear();
for (var cluster in clustersCentroid.entries) {
markers.add(
Marker(
width: 80.0,
height: 80.0,
point: cluster.value,
builder: (ctx) => const Icon(
Icons.circle,
size: 70,
color: Colors.green,
),
),
);
}
isLoading = false;
update();
}
}
该控制器主要有两种方法:getLocation()获取用户的位置,从flutter_map包中创建一个标记,并使用Flutter库中的图标显示他的位置,这个方法工作得很好,我成功地显示了用户的位置。
第二种方法获取质心位置(使用k-means算法生成的聚类质心),它清除标记(如果之前有标记),然后为每个聚类创建一个标记并将其添加到标记列表中,最后重建侦听MapController控制器的GetBuilder(),我猜这是必须做的事情,但它不显示这些聚类。用户位置显示得很好,但我在clustesr质心标记上遇到了问题。
下面是我调用这些方法的Map页面:
final mapController = Get.find<MapAppController>();
final userInfoController = Get.find<InscriptionController>();
class MapPage extends StatelessWidget {
const MapPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: GetBuilder<MapAppController>(
builder: (controller) => Stack(
children: [
FlutterMap(
options: MapOptions(
center: controller.center,
zoom: 5.0,
),
children: [
TileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
subdomains: const ['a', 'b', 'c'],
),
MarkerLayer(
markers: [
if (mapController.userLocationMarker != null)
mapController.userLocationMarker!,
if (mapController.markers.isNotEmpty)
...mapController.markers,
],
),
],
),
Visibility(
visible: mapController.isLoading,
child: const CustomLoadingIndicator(),
),
FloatingActionButton(
onPressed: () async {
await mapController.populateMarkers();
},
child: const Icon(Icons.info),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
await mapController.getLocation();
},
child: const Icon(Icons.gps_fixed),
),
);
}
}
1条答案
按热度按时间sauutmhj1#
将标记列表作为obs列表,如下所示:
在视图中这样使用它: