android GoogleMap标记未在google_maps_flutter中更新

noj0wjuj  于 2022-11-03  发布在  Android
关注(0)|答案(1)|浏览(147)

我尝试使用GetX Obx小工具在我的谷歌Map中显示位置列表。我可以显示所有标记的列表,但当我清除列表并调用update时,即使这样,以前添加的标记也不会从Map中删除。我也尝试过手动调用setState(){},但它不能反映最新的标记列表。以下是我的控制器代码:

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,
)));

()}}
这是我的主页代码

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;
}

在我的主页中,我正在观察Obx小部件中的标记集,但仍然可以看到以前添加的标记以及新添加的标记。如果有人有任何建议,请让我知道,提前感谢

ql3eal8s

ql3eal8s1#

您应该使用setState重新构建Map,如下所示

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)));
  });

相关问题