英文:
How to access current location and set that as initial location?
问题
我有一个使用位置服务的Flutter应用程序。我已经实现了获取用户的当前位置和权限等等。
我的应用程序在首次打开时需要在地图上放置一个标记,位置应该基于用户的当前位置。这是我需要帮助的部分。
用户随后可以在地图上的任何其他位置点击以在该位置放置标记。这部分我已经完成了。
我已经成功创建了一个可以获取用户当前位置的函数,如下所示(请注意,这个函数是异步的):
Future<LatLng> get currentLocation async {
Position pos = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
);
return LatLng(pos.latitude, pos.longitude);
}
目前,我在我的HomePage中有一个初始标记点,如下所示:
class _HomePageState extends State<HomePage> {
// Initial marker location
LatLng markerPoint = LatLng(12.9716, 77.5946);
...
但我想要使用我的函数返回的当前位置来替换这里给定的值。我无法像这样做:LatLng markerPoint = await _locationService.currentLocation;
,因为我无法将该部分设为类的一部分async
。
所以,这基本上就是我的问题。我想通过异步函数初始化我的变量,但由于我所在的区域不允许异步函数,我尚未找到实现的方法。
帮助将不胜感激。
附:以下是设置标记点的剩余构建函数,每当触摸时都会设置标记点:
@override
Widget build(BuildContext context) {
return Stack(
children: [
FlutterMap(
options: MapOptions(
onTap: (tapPosition, point) async {
setState(() {
markerPoint = point;
});
},
center: markerPoint,
zoom: 10.0,
interactiveFlags: InteractiveFlag.all & ~InteractiveFlag.rotate,
),
nonRotatedChildren: [
TileLayer(
urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: const ['a', 'b', 'c'],
),
MarkerLayer(
markers: [
Marker(
width: 100.0,
height: 100.0,
point: markerPoint,
builder: (ctx) => const Icon(
Icons.location_on,
color: Colors.red,
size: 40,
),
),
],
),
],
),
SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Card(
child: TextField(
decoration: const InputDecoration(
prefixIcon: Icon(Icons.location_on_outlined),
hintText: "Search for a location",
contentPadding: EdgeInsets.all(16.0),
),
onTap: () async {
await requestPermission();
},
),
),
],
),
),
),
],
);
}
英文:
I have a Flutter app which requires location services. I have already implemented getting a users current location, permissions, etc...
My app has to position a marker on a map when first open based on the current location of the user. (This is what I need help with)
The user can later touch the map at any other point to place the marker at that point. (This I have already done)
I have successfully created a function which can retrieve the current location of a user like this, (Do note that that function is async)
Future<LatLng> get currentLocation async {
Position pos = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
);
return LatLng(pos.latitude, pos.longitude);
}
I currently have LatLng markerPoint = LatLng(12.9716, 77.5946);
as my initial marker point inside of my HomePage like this,
class _HomePageState extends State<HomePage> {
// Initial marker location
LatLng markerPoint = LatLng(12.9716, 77.5946);
...
But I want the current location returned by my function to replace the values given here. I am unable to do something like LatLng markerPoint = await _locationService.currentLocation;
because I cannot make that part of the class async.
So, that's basically my problem. I want to initialise my variable through an asynchronous function, but I haven't found a way to do that since the area I am in, does not allow for async functions.
Help will be appreciated.
PS:
My remaining build function which sets the marker point whenever touched is over here for your reference.
@override
Widget build(BuildContext context) {
return Stack(
children: [
FlutterMap(
options: MapOptions(
onTap: (tapPosition, point) async {
setState(() {
markerPoint = point;
});
},
//
center: markerPoint,
zoom: 10.0,
// this is required to disable rotation of the map
// the map will behave wierd when you rotate it if it's deleted
// the map will not scroll properly and not place markers at the exact locations.
// if the below line in removed
interactiveFlags: InteractiveFlag.all & ~InteractiveFlag.rotate,
),
nonRotatedChildren: [
TileLayer(
urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: const ['a', 'b', 'c'],
),
MarkerLayer(
markers: [
Marker(
width: 100.0,
height: 100.0,
point: markerPoint,
builder: (ctx) => const Icon(
Icons.location_on,
color: Colors.red,
size: 40,
),
),
],
),
],
),
SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Card(
child: TextField(
decoration: const InputDecoration(
prefixIcon: Icon(Icons.location_on_outlined),
hintText: "Search for a location",
contentPadding: EdgeInsets.all(16.0),
),
onTap: () async {
// This is here for debugging only, kindly ignore
await requestPermission();
},
),
),
],
),
),
),
],
);
}
答案1
得分: 1
希望您在initState()
方法中调用获取当前位置的API。
例如:
@override
void initState() {
super.initState();
fetchCurrentLocation();
}
void fetchCurrentLocation() async {
// 调用API
var currentLocation = await _locationService.currentLocation;
// setState将实时更新数值
setState(() {
markerPoint = currentLocation;
});
}
英文:
hope you are calling the get current location api in the initState() method
eg :
@override
void initState() {
super.initState();
fetchCurrentLocation();
}
void fetchCurrentLocation() async{
//calling the api
var currentLocation = await _locationService.currentLocation;
//setState will update the values in real time
setState(() {
markerPoint = currentLocation
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论