I am trying to show the list of locations in my google map, using GetX Obx widget.I am able to show the list of all markers but when I clear the list and call update even then the previously added markers are not removed from the map. I have tried the same by calling setState(){} manually but it is not reflecting the latest list of markers. Here is my code of controller:
import 'dart:async';
import 'package:custom_info_window/custom_info_window.dart';
import 'package:ev_charger/data/models/stations_list_response.dart';
import 'package:ev_charger/data/repositories/api_repository.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class HomeController extends GetxController {
final ApiRepository _repo;
var isLoading = false.obs;
var stationsList = <StationsData>[].obs;
var currentLocation = const LatLng(20.5937, 78.9629).obs;
var mapMarkers = <Marker>{}.obs;
CustomInfoWindowController customInfoWindowController =
CustomInfoWindowController();
final Completer<GoogleMapController> myMapController = Completer();
late TextEditingController searchBoxController;
HomeController(this._repo);
@override
void onInit() {
getStationLists("19.5353552", "72.876104", "50000");
super.onInit();
}
@override
void dispose() {
customInfoWindowController.dispose();
super.dispose();
}
void getStationLists(double latitude, double longitude, String radius) async {
isLoading(true);
currentLocation(LatLng(latitude, longitude));
mapMarkers.clear();
mapMarkers.refresh();
final marker = Marker(
markerId: const MarkerId("Current Location"),
position: LatLng(latitude, longitude),
icon: BitmapDescriptor.defaultMarker,
);
mapMarkers.add(marker);
try {
var requestBody = {
"latitude1": "$latitude",
"longitude1": "$longitude",
"meter": radius,
"assetTypeName": "Car"
};
var data = await _repo.getStationsList(requestBody);
if (data.data!.isNotEmpty) {
stationsList.addAll(data.data!);
for (var element in stationsList) {
double latitude = double.parse(element.latitude!);
double longitude = double.parse(element.longitude!);
Uint8List markerIcon = await getBytesFromAsset(
'assets/images/lnt_charger_marker.png', 100);
final marker = Marker(
markerId: MarkerId(element.groupName!),
position: LatLng(latitude, longitude),
icon: BitmapDescriptor.fromBytes(markerIcon),
onTap: () {
customInfoWindowController.addInfoWindow!(
element.groupSeq == null
? Wrap(
children: [
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16.0)),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
element.groupName!,
style: TextStyle(
fontSize: 10.sp,
fontWeight: FontWeight.bold,
color: AppColors.textColor),
),
),
Padding(
padding: const EdgeInsets.only(
left: 8.0, bottom: 8.0),
child: Text(
element.location!,
style: TextStyle(fontSize: 10.sp),
),
)
],
),
)
],
)
: Wrap(children: [
Container(
width: 50.w,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16.0)),
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(
left: 8.0, right: 8.0, top: 8.0),
child: Text(
element.groupName!,
style: TextStyle(fontSize: 10.sp),
),
),
MaterialButton(
onPressed: () {
},
child: Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(8.0),
color: AppColors.primaryColor),
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Details",
style: TextStyle(color: Colors.white),
),
),
),
)
],
),
)
]),
LatLng(latitude, longitude));
},
);
mapMarkers.add(marker);
}
moveCamera(latitude, longitude);
isLoading(false);
debugPrint("The no of markers is ${mapMarkers.length}");
} else {
isLoading(false);
AppValidations.showToast("No charging stations found for the location");
}
} catch (e) {
isLoading(false);
AppValidations.showToast(e.toString());
}
}
Future<void> moveCamera(double latitude, double longitude) async {
final marker = Marker(
markerId: const MarkerId("Current address"),
position: LatLng(latitude, longitude),
);
mapMarkers.add(marker);
final GoogleMapController controller = await myMapController.future;
controller.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: LatLng(latitude, longitude),
zoom: 7.4736,
tilt: 59.440717697143555,
bearing: 5.55,
)));
} }
Here is my Home Page Code
import 'dart:async';
import 'package:custom_info_window/custom_info_window.dart';
import 'package:ev_charger/data/repositories/api_repository.dart';
import 'package:ev_charger/network/api_base_helper.dart';
import 'package:ev_charger/presentation/common_widgets/app_loader.dart';
import 'package:ev_charger/presentation/screens/home/home_controller.dart';
import 'package:ev_charger/utils/constants.dart';
import 'package:ev_charger/utils/validations.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_google_places/flutter_google_places.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_vector_icons/flutter_vector_icons.dart';
import 'package:get/get.dart';
import 'package:google_api_headers/google_api_headers.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_webservice/places.dart';
import 'package:sizer/sizer.dart';
import '../../../utils/colors.dart';
import '../../../utils/styles.dart';
import '../../../utils/ui_helpers.dart';
const apiId = "";
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context);
var controller = Get.put(HomeController(ApiRepository(ApiBaseHelper())));
return Scaffold(
appBar: AppBar(),
body: SafeArea(
child: Stack(
children: [
Obx(
() => controller.isLoading.value
? const AppLoader()
: GoogleMap(
onTap: (position) {
controller.customInfoWindowController.hideInfoWindow!();
},
mapToolbarEnabled: true,
initialCameraPosition: CameraPosition(
target: controller.mapMarkers.isEmpty
? const LatLng(20.5937, 78.9629)
: LatLng(
controller.mapMarkers.last.position.latitude,
controller
.mapMarkers.last.position.longitude),
zoom: 15.4736,
tilt: 59.440717697143555,
bearing: 5.55),
mapType: MapType.normal,
markers: controller.mapMarkers,
circles: {
Circle(
circleId: const CircleId("id"),
center: controller.currentLocation.value,
radius: controller.selectedRadius == "Select radius"
? 50000.00
: double.parse(controller.selectedRadius) *
1000,
fillColor: Colors.blue.shade200.withOpacity(0.5),
strokeColor: Colors.blue.shade100.withOpacity(0.1))
},
onMapCreated: (GoogleMapController mapController) async {
if (!controller.myMapController.isCompleted) {
controller.myMapController.complete(mapController);
controller.customInfoWindowController
.googleMapController =
await controller.myMapController.future;
} else {
controller.customInfoWindowController
.googleMapController = mapController;
}
},
),
),
CustomInfoWindow(
width: 50.w,
controller: controller.customInfoWindowController,
),
],
),
),
);
}
@override
bool get wantKeepAlive => true;
}
In my Home page I am observing the set of markers inside the Obx widget but still able to see the previously added markers as well as the new ones .If anyone has any suggestions please let me know Thanks in advance
CodePudding user response:
you should use setState to rebuild your map something like this
setState(() {
lat = widget.lat;
lng = widget.lng;
final Marker marker = Marker(
markerId: markerId,
position: LatLng(widget.lat, widget.lng),
//infoWindow: const InfoWindow(title: "company", snippet: '*'),
onTap: () {
_onMarkerTapped(markerId);
},
);
markers[markerId] = marker;
mapController?.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(widget.lat, widget.lng), zoom: 11)));
});