如果手动设置坐标
target: LatLng(48.5244722, 39.2643343),
,显示地图。如果坐标是动态确定的,则不会使用package:geolocator显示地图。为什么?下面是完整的代码示例和屏幕截图。
主要.dart
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Name App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Name Page'),
),
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _str = ''; //для проверки
double _latitude = 0.0; //широта
double _longitude = 0.0; //долгота
@override
void initState() {
super.initState();
_getPosition().then((value) {
_latitude = value.latitude;
_longitude = value.longitude;
_str = '$_latitude\n$_longitude';
});
}
@override
void dispose() {
super.dispose();
}
void _f1() {
setState(() {
});
}
Future<Position> _getPosition() async {
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
return position;
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
GoogleMap(
initialCameraPosition: CameraPosition(
//target: LatLng(48.5244722, 39.2643343),
target: LatLng(_latitude, _longitude),
zoom: 19.151926040649414,
bearing: 222.8334901395799,
),
mapType: MapType.hybrid,
),
Align(
alignment: Alignment(0.0, 0.95),
child: Text(
_str,
style: TextStyle(
fontSize: 20.0,
),
),
),
],
);
}
}
将答案从评论移至关闭问题。
该小部件
GoogleMap
有一个方法,该方法onMapCreated
具有GoogleMapController
. 应该通过GoogleMapController
地图进行管理。例子: