https://pub.dev/packages/geolocator
# pubspec.yaml
dependencies:
geolocator: ^8.0.1
# android/app/build.gradle
android {
compileSdkVersion 31
안드로이드
# android/app/src/debug/AndroidManifest.xml<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
ios
# ios/Runner/Info.plist<key>NSLocationWhenInUseUsageDescription</key> <string>This app needs access to location when open.</string> <key>NSLocationAlwaysUsageDescription</key> <string>This app needs access to location when in the background.</string>
# lib/screens/map_screen.dart
import 'package:givewang/services/location.dart';
class _MapScreenState extends State<MapScreen> {
void initState() {
super.initState();
getLocationData();
}
void getLocationData() async {
Location location = Location();
await location.getCurrentLocation();
print(location.latitude);
print(location.longitude);
}
# lib/services/location.dart
import 'package:geolocator/geolocator.dart';
class Location {
double latitude = 0;
double longitude = 0;
Future<void> getCurrentLocation() async {
LocationPermission permission = await Geolocator.checkPermission();
// print(permission);
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
latitude = position.latitude;
longitude = position.longitude;
} catch (e) {
print(e);
}
}
}