在Flutter中实现地理定位和地图功能,你可以使用location
插件来获取当前位置,以及google_maps_flutter
插件来在应用中展示Google Maps。
首先,在pubspec.yaml
中添加依赖:
dependencies:
flutter:
sdk: flutter
location: ^4.3.0
google_maps_flutter: ^2.0.1
然后,获取地理定位权限并使用location
插件获取当前位置:
import 'package:location/location.dart';
Location location = Location();
var locationData = await location.getLocation();
double latitude = locationData.latitude;
double longitude = locationData.longitude;
接下来,在地图上显示当前位置,可以使用google_maps_flutter
插件:
import 'package:google_maps_flutter/google_maps_flutter.dart';
GoogleMapController mapController;
final GoogleMap googleMap = GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(latitude, longitude),
zoom: 15.0,
),
onMapCreated: (controller) {
mapController = controller;
},
);
完整的示例代码:
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MapsSample(),
);
}
}
class MapsSample extends StatefulWidget {
@override
State<MapsSample> createState() => MapsSampleState();
}
class MapsSampleState extends State<MapsSample> {
Location location = Location();
GoogleMapController mapController;
var locationData;
double latitude;
double longitude;
@override
void initState() {
super.initState();
getLocationData();
}
getLocationData() async {
locationData = await location.getLocation();
latitude = locationData.latitude;
longitude = locationData.longitude;
setState(() {});
}
@override
Widget build(BuildContext context) {
if (latitude == null || longitude == null) {
return Scaffold(
body: Center(
child: Text('Loading...'),
),
);
}
return Scaffold(
body: GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(latitude, longitude),
zoom: 15.0,
),
onMapCreated: (controller) {
mapController = controller;
},
),
);
}
}
确保你有正确的Google Maps API密钥,并在AndroidManifest.xml
和Info.plist
中配置好。在实际应用中,你可能还需要处理权限请求和其他错误情况。