Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue while getting location of android device using Google Maps #3192

Open
nijatmursali opened this issue Aug 24, 2024 · 0 comments
Open

Issue while getting location of android device using Google Maps #3192

nijatmursali opened this issue Aug 24, 2024 · 0 comments
Assignees

Comments

@nijatmursali
Copy link

I'm having an issue while getting the location of the user, having API call to get the stations and lastly placing markers on the map.

I'm using Getx as controller, so my variables are:

  LatLng _initialPosition = const LatLng(40.42, 49.82);
  var activeGps = true.obs;
  late GoogleMapController _mapController;
  List<NearbyStation>? _stations;
  final Set<Marker> _markers = Set();

  BitmapDescriptor _availableIcon = BitmapDescriptor.defaultMarker;
  BitmapDescriptor _unavailabeIcon = BitmapDescriptor.defaultMarker;

and using getter to get them:

  LatLng get gpsPosition => _actualLocation;
  LatLng get initialPos => _initialPosition;
  List<NearbyStation>? get stations => _stations;

  Set<Marker> get markers => _markers;
  GoogleMapController get mapController => _mapController;

I have getUserLocation function which uses geolocator package and gets the accurate location:

void getUserLocation() async {
    if (!(await Geolocator.isLocationServiceEnabled())) {
      activeGps.value = false;
    } else {
      activeGps.value = true;
      LocationPermission permission;
      permission = await Geolocator.checkPermission();
      if (permission == LocationPermission.denied) {
        permission = await Geolocator.requestPermission();
        if (permission == LocationPermission.denied) {
          return Future.error('Location permissions are denied');
        }
      }
      if (permission == LocationPermission.deniedForever) {
        return Future.error(
            'Location permissions are permanently denied, we cannot request permissions.');
      }

      const LocationSettings locationSettings = LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
      );
      Position position = await Geolocator.getCurrentPosition(
          locationSettings: locationSettings);
      _initialPosition = LatLng(position.latitude, position.longitude);
      await _getStations(position.latitude, position.longitude); // used to get stations

      _mapController.moveCamera(CameraUpdate.newLatLng(_initialPosition));
      _buildMarkers(); // used to build markers
    }
  }

Of course, I also have the onInit function to initialize:

  @override
  void onInit() {
    super.onInit();
    addCustomIcon();
    getUserLocation();
  }

and _buildMarkers() function is used to add the markers to the set.

Set<Marker> _buildMarkers() {
    for (var station in _stations!) {
      _markers.add(
        Marker(
          markerId: MarkerId(station.id.toString()),
          position:
              LatLng(double.parse(station.lat), double.parse(station.long)),
          icon: station.availableConnectors > 0
              ? _availableIcon
              : _unavailabeIcon,
          onTap: () async {
            Get.toNamed('/connectors', arguments: {
              'id': station.id,
              'location': LatLng(
                double.parse(station.lat),
                double.parse(station.long),
              ),
            });
            //}
          },
        ),
      );
    }

    return markers;
  }

and lastly, _getStations() function is used to get the stations, call itself works fine, but issue happens when I try to get the locations inside getUserLocation.

  Future<List<NearbyStation>?> _getStations(
      double latitude, double longitude) async {
    final String? accessToken = box.read('access_token');
    try {
      var url = Uri.parse(
          '${ApiConstants.baseUrl}${ApiConstants.getNearbyStationEndpoint}?long=$longitude&lat=$latitude&rad=-1');
      var response =
          await http.get(url, headers: ApiConstants.headers(accessToken));
      if (response.statusCode == 200) {
        List<dynamic> jsonResponse = json.decode(response.body);
        List<NearbyStation> station = jsonResponse
            .map((regionJson) => NearbyStation.fromJson(regionJson))
            .toList();
        _stations = station;
        return station;
      }
    } catch (e) {
      print('Error: $e');
      return null;
    }
    return null;
  }

The issue happens only in android devices, in IOS device it worked just fine. I'm not sure which part is wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants