Current location - Flutter

Asked

Viewed 3,057 times

4

Guys, I need to get the current latitude and longitude of the cell phone coom flutter, but it’s not working and I’m not finding anything on the internet, someone can help me?

code:

import 'dart:async';
import 'package:location/location.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Completer<GoogleMapController> _controller = Completer();

  static const LatLng _center = const LatLng(0, 0);
  static var location = new Location();
  var x = location.getLocation();
  var lg = x.longitude;
  var lt = x.latitude;


  final Set<Marker> _makers2 = {};

  LatLng _lastMapPosition = _center;

  static var latitudes = [-23.5629, -19.9324, -22.0154];
  static var longitudes = [-46.6544, -43.9388, -47.8911];
  static var i = 0;

  LatLng posicaoVetor = LatLng(latitudes[i], longitudes[i]);

  MapType _currentMapType = MapType.normal;

  void _onMapTypeButtonPressed() {
    setState(() {
      _currentMapType = _currentMapType == MapType.normal
          ? MapType.satellite
          : MapType.normal;
    });
  }

  void _onAddMarkerButtonPressed() {
    setState(() {
      _makers2.add(Marker(
        markerId: MarkerId(LatLng(latitudes[i], longitudes[i]).toString()),
        position: LatLng(latitudes[i], longitudes[i]),
        icon: BitmapDescriptor.defaultMarker,
      ));
    });
    i++;
  }

  void _onCameraMove(CameraPosition position) {
    _lastMapPosition = position.target;
  }

  void _onMapCreated(GoogleMapController controller) {
    _controller.complete(controller);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(''),
          backgroundColor: Colors.green[700],
        ),
        body: Stack(
          children: <Widget>[
            GoogleMap(
              onMapCreated: _onMapCreated,
              initialCameraPosition: CameraPosition(
                target: LatLng(0, 0), /*AQUI SERIA A LOCALIZAÇAO ATUAL DA PESSOA*/
                zoom: 11.0,
              ),
              mapType: _currentMapType,
              markers: _makers2,
              onCameraMove: _onCameraMove,
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Align(
                alignment: Alignment.topRight,
                child: Column(
                  children: <Widget> [
                    FloatingActionButton(
                      onPressed: _onMapTypeButtonPressed,
                      materialTapTargetSize: MaterialTapTargetSize.padded,
                      backgroundColor: Colors.green,
                      child: const Icon(Icons.map, size: 36.0),
                    ),
                    SizedBox(height: 16.0),
                    FloatingActionButton(
                      onPressed: _onAddMarkerButtonPressed,
                      materialTapTargetSize: MaterialTapTargetSize.padded,
                      backgroundColor: Colors.green,
                      child: const Icon(Icons.add_location, size: 36.0),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
  • tried to use that package and follow the steps on the? https://pub.dartlang.org/packages/location

3 answers

3

Using the plugin Geolocator, you could do it this way:

void _getCurrentLocation() {
final Geolocator _geolocator = Geolocator()..forceAndroidLocationManager = true;
_geolocator.checkGeolocationPermissionStatus().then((GeolocationStatus _locationStatus) {
  if (_locationStatus == GeolocationStatus.granted) {
    _geolocator
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
        .then((Position position) {
      setState(() {
        _stringPosition = 'Altitude: ${position.altitude} Longitude: ${position.longitude}';
      });
    }).catchError((e) {
      _stringPosition = e.toString();
    });
  }
});

Where permission is first requested to use the device location, with the permission accepted you will have access to altitude, longitude and among other data.

To facilitate reading and observe how I implemented I am leaving the project link Flutter-Geolocator.

2

I saw that you use the getLocation() but it doesn’t use its value, so try something like this:

import 'dart:async';
import 'package:location/location.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Completer<GoogleMapController> _controller = Completer();

  static const LatLng _center = const LatLng(0, 0);
  static var location = new Location();
  /*var x = location.getLocation();
  var lg = x.longitude;
  var lt = x.latitude;*/

  var minhaLocalizacao;

  void pegarLocalizacao() async {
    setState((){
      minhaLocalizacao = await location.getLocation();
    })
  }

  @override
  void initState() {
    super.initState();
    pegarLocalizacao();
  }

  final Set<Marker> _makers2 = {};

  LatLng _lastMapPosition = _center;

  static var latitudes = [-23.5629, -19.9324, -22.0154];
  static var longitudes = [-46.6544, -43.9388, -47.8911];
  static var i = 0;

  LatLng posicaoVetor = LatLng(latitudes[i], longitudes[i]);

  MapType _currentMapType = MapType.normal;

  void _onMapTypeButtonPressed() {
    setState(() {
      _currentMapType = _currentMapType == MapType.normal
          ? MapType.satellite
          : MapType.normal;
    });
  }

  void _onAddMarkerButtonPressed() {
    setState(() {
      _makers2.add(Marker(
        markerId: MarkerId(LatLng(latitudes[i], longitudes[i]).toString()),
        position: LatLng(latitudes[i], longitudes[i]),
        icon: BitmapDescriptor.defaultMarker,
      ));
    });
    i++;
  }

  void _onCameraMove(CameraPosition position) {
    _lastMapPosition = position.target;
  }

  void _onMapCreated(GoogleMapController controller) {
    _controller.complete(controller);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(''),
          backgroundColor: Colors.green[700],
        ),
        body: Stack(
          children: <Widget>[
            GoogleMap(
              onMapCreated: _onMapCreated,
              initialCameraPosition: CameraPosition(
                target: LatLng(minhaLocalizacao.latitude, minhaLocalizacao.longitude),
                zoom: 11.0,
              ),
              mapType: _currentMapType,
              markers: _makers2,
              onCameraMove: _onCameraMove,
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Align(
                alignment: Alignment.topRight,
                child: Column(
                  children: <Widget> [
                    FloatingActionButton(
                      onPressed: _onMapTypeButtonPressed,
                      materialTapTargetSize: MaterialTapTargetSize.padded,
                      backgroundColor: Colors.green,
                      child: const Icon(Icons.map, size: 36.0),
                    ),
                    SizedBox(height: 16.0),
                    FloatingActionButton(
                      onPressed: _onAddMarkerButtonPressed,
                      materialTapTargetSize: MaterialTapTargetSize.padded,
                      backgroundColor: Colors.green,
                      child: const Icon(Icons.add_location, size: 36.0),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Don’t forget to follow the step by step available on the package that you are using, as it is necessary to ask for permission to use the fine access to the location!

Note: I am without Flutter in the computer where I am, so I did not test anything!

0

I used this way using the package Location Serves to pick up the current location of the GPS, checks if it is given the GPS permission for the application, if it does not ask to authorize and then picks up the current location of the device.

try {
  Location location = new Location();
  bool permission = await checkPermission();

  if(permission) {

    await location.getLocation().then((onValue) {
      //print(onValue["latitude"].toString() + "," + onValue["longitude"].toString());
    });

    //print("Com permissões!");
    posicao = await location.getLocation().catchError((e){
      //print("ERRO DE LOCALIZAÇÃO: "+e.toString());
    });

    posicao = await location.onLocationChanged().first;
    //print("POSICAO TO STRING: " + posicao.toString());

    print("latitude: ${posicao["latitude"]} | longitude: ${posicao["longitude"]} | altitude: ${posicao["altitude"]}");
  } else {
    print("Sem permissões!");
  }
  return true;
} catch (e) {
  print("CATCH ERROR: ${e.toString()}");
}

Future<bool> checkPermission() async {
    bool hasPermission =
    await SimplePermissions.checkPermission(Permission.WhenInUseLocation);

    //debugPrint("*location_state_handler* permission for location: $hasPermission");

    if (hasPermission) {
      return true;
    }

    PermissionStatus permissionStatus =
    await SimplePermissions.requestPermission(Permission.WhenInUseLocation);

    debugPrint("permission request result is $permissionStatus");

    if (permissionStatus == PermissionStatus.authorized ||
        permissionStatus == PermissionStatus.restricted) {
      return true;
    }

    print('permission denied');
    return false;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.