How to get location in flutter code example
Example 1: currunt location in flutter
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main() => runApp(MapScreen());
class MapScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Map",
home: MapActivity(),
);
}
}
class MapActivity extends StatefulWidget {
@override
_MapActivityState createState() => _MapActivityState();
}
class _MapActivityState extends State {
LatLng _center ;
Position currentLocation;
@override
void initState() {
// TODO: implement initState
super.initState();
getUserLocation();
}
Future locateUser() async {
return Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
}
getUserLocation() async {
currentLocation = await locateUser();
setState(() {
_center = LatLng(currentLocation.latitude, currentLocation.longitude);
});
print('center $_center');
}
}
Example 2: get location name in flutter
import 'package:geocoder/geocoder.dart';
// From a query
final query = "1600 Amphiteatre Parkway, Mountain View";
var addresses = await Geocoder.local.findAddressesFromQuery(query);
var first = addresses.first;
print("${first.featureName} : ${first.coordinates}");
// From coordinates
final coordinates = new Coordinates(1.10, 45.50);
addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
first = addresses.first;
print("${first.featureName} : ${first.addressLine}");