谷歌Map上的当前位置(Flutter)

rn0zuynd  于 2023-01-27  发布在  Flutter
关注(0)|答案(2)|浏览(173)

我尝试获取设备当前位置并在initialCameraPosition中使用,
执行函数,获取坐标并将其设置在**_currentPosition**中
启动屏幕后,我有一个错误:

  • 最新错误(最新初始化错误:字段"currentPosition"尚未初始化。)*

我认为,Map创建速度比数据写入变量的速度快,但我不知道它是如何修复的。
感谢帮助或建议如何使代码是正确的

import 'package:flutter/material.dart';

import 'package:google_maps_flutter/google_maps_flutter.dart';

import 'package:geolocator/geolocator.dart';

class UserMapInfo extends StatefulWidget {
  const UserMapInfo({Key? key}) : super(key: key);

  @override
  State<UserMapInfo> createState() => _UserMapInfoState();
}

class _UserMapInfoState extends State<UserMapInfo> {
  late GoogleMapController mapController;

  late LatLng _currentPosition;

  @override
  void initState() {
    super.initState();
    getLocation();
  }

  getLocation() async {
    LocationPermission permission;
    permission = await Geolocator.requestPermission();

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    double lat = position.latitude;
    double long = position.longitude;

    LatLng location = LatLng(lat, long);

    setState(() {
      _currentPosition = location;
    });
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Map'),
      ),
      body: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _currentPosition,
          zoom: 16.0,
        ),
      ),
    );
  }
}
    • 更新**

我试着用

    • LatLng?_当前位置;**

并添加测试坐标

    • 横向长度基准位置=横向长度(56.324293441187315,38.13961947281509);**

并添加"空值检查"
我的代码

class _UserMapInfoState extends State<UserMapInfo> {
  
  late GoogleMapController mapController;

  // late LatLng currentPosition;

  LatLng? _currentPosition;

  LatLng basePosition = LatLng(56.324293441187315, 38.13961947281509);

  @override
  void initState() {
    super.initState();
    getLocation();
  }

  getLocation() async {
    LocationPermission permission;
    permission = await Geolocator.requestPermission();

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    double lat = position.latitude;
    double long = position.longitude;

    LatLng location = LatLng(lat, long);

    setState(() {
      _currentPosition = location;
    });
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Map'),
      ),
      body: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _currentPosition ?? basePosition,
          zoom: 16.0,
        ),
      ),
    );
  }
}

当我的Map打开时,使用LatLng basePosition((这不是我需要的
我尝试其他空检查

initialCameraPosition: CameraPosition(
          target: _currentPosition!,
          zoom: 16.0,
        ),

再次出错

  • _CastError(用于空值的空检查运算符)*

谢谢!好办法!
我在这里加上"null check"
终码

import 'package:flutter/material.dart';

import 'package:google_maps_flutter/google_maps_flutter.dart';

import 'package:geolocator/geolocator.dart';

class UserMapInfo extends StatefulWidget {
  const UserMapInfo({Key? key}) : super(key: key);

  @override
  State<UserMapInfo> createState() => _UserMapInfoState();
}

class _UserMapInfoState extends State<UserMapInfo> {
  late GoogleMapController mapController;

  LatLng? _currentPosition;

  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    getLocation();
  }

  getLocation() async {
    LocationPermission permission;
    permission = await Geolocator.requestPermission();

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    double lat = position.latitude;
    double long = position.longitude;

    LatLng location = LatLng(lat, long);

    setState(() {
      _currentPosition = location;
      _isLoading = false;
    });
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Map'),
      ),
      body: _isLoading
          ? const Center(
              child: CircularProgressIndicator(),
            )
          : GoogleMap(
              onMapCreated: _onMapCreated,
              initialCameraPosition: CameraPosition(
                target: _currentPosition!,
                zoom: 16.0,
              ),
            ),
    );
  }
}
htrmnn0y

htrmnn0y1#

试试这个:

class _UserMapInfoState extends State<UserMapInfo> {
  
  late GoogleMapController mapController;

  LatLng? _currentPosition;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    getLocation();
  }

  getLocation() async {
    LocationPermission permission;
    permission = await Geolocator.requestPermission();

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    double lat = position.latitude;
    double long = position.longitude;

    LatLng location = LatLng(lat, long);

    setState(() {
      _currentPosition = location;
      _isLoading = false;
    });
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Map'),
      ),
      body: _isLoading ? 
      Center(child:CircularProgressIndicator()) : 
      GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _currentPosition,
          zoom: 16.0,
        ),
      ),
    );
  }
}
3pmvbmvn

3pmvbmvn2#

发生这种情况的原因是getLocation()async方法,您必须等待该方法完成,然后才能使用_currentPosition创建Map微件
下面的代码是一个快速解决方案:

class MapPage extends StatefulWidget {
  const MapPage({Key? key}) : super(key: key);

  @override
  State<MapPage> createState() => _MapPageState();
}

class _MapPageState extends State<MapPage> {
  late GoogleMapController mapController;
  late Future _getCurrentLocationFuture;
  LatLng? _currentPosition;

  @override
  void initState() {
    _getCurrentLocationFuture = _getCurrentLocation();
    super.initState();
  }

  _getCurrentLocation() async {
    Position position;
    try {
      position = await Geolocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.high,
          forceAndroidLocationManager: true,
          timeLimit: Duration(seconds: 15));
    } catch (e) {
      position = null;
      debugPrint(e);
    }

    if (position != null) {
      LatLng location = LatLng(position.latitude, position.longitude);
      _currentPosition = location;
    }

    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: _getCurrentLocationFuture,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return GoogleMap(
              onMapCreated: _onMapCreated,
              initialCameraPosition: CameraPosition(
                target: _currentPosition ??
                    LatLng(56.324293441187315, 38.13961947281509),
                zoom: 16.0,
              ),
            );
          } else {
            return CircularProgressIndicator();
          }
        },
      ),
    );
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }
}

另外,最好在打开MapPage之前检查位置权限和服务。或者您可以在MapPage中检查,然后使用animateCamera将Map移动到当前位置

相关问题