简体   繁体   English

谷歌地图上的当前位置(Flutter)

[英]Current location on the google maps (Flutter)

I try to get current location my device and use it in initialCameraPosition,我尝试获取我的设备的当前位置并在 initialCameraPosition 中使用它,

The function is executed and I get the coordinates and set it in _currentPosition function 被执行,我得到坐标并将其设置在_currentPosition

After starting the screen i have an error:启动屏幕后出现错误:

LateError (LateInitializationError: Field 'currentPosition' has not been initialized.) LateError(LateInitializationError:字段“currentPosition”尚未初始化。)

I think, map is created faster than the data is written to the variable, but i dont know how it fix.我认为,创建 map 的速度比将数据写入变量的速度快,但我不知道它是如何修复的。

Thanks fo help or advice how make code is correct感谢您的帮助或建议如何使代码正确


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,
        ),
      ),
    );
  }
}

Update更新

I try to use我尝试使用

LatLng?经纬度? _currentPosition; _当前位置;

and add test coordinates并添加测试坐标

LatLng basePosition = LatLng(56.324293441187315, 38.13961947281509); LatLng basePosition = LatLng(56.324293441187315, 38.13961947281509);

and add "null check"并添加“空检查”

my code我的代码


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,
        ),
      ),
    );
  }
}

And when my map is open, use LatLng basePosition ((( this is not what i need当我的 map 打开时,使用LatLng basePosition ((( 这不是我需要的

I try other null check我试试别的 null check


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

ERROR again再次出错

_CastError (Null check operator used on a null value) _CastError(用于 null 值的空检查运算符)

Thanks!谢谢! Good solution!好的解决方案!

And i`m add "null check" there我在那里添加“空检查”

final code最终代码


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,
              ),
            ),
    );
  }
}


Try this:尝试这个:

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,
        ),
      ),
    );
  }
}

This is happening because getLocation() is a async method and you have to wait for it to finish before creating your map widget with _currentPosition发生这种情况是因为getLocation()是一种async方法,您必须等待它完成才能使用_currentPosition创建 map 小部件

Below code is a quick solution:下面的代码是一个快速的解决方案:

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;
  }
}

Also its best to check location permission and service before opening MapPage .最好在打开MapPage之前检查位置权限和服务。 or you can check it inside MapPage and then use animateCamera to move the map to current location或者您可以在MapPage中检查它,然后使用animateCamera将 map 移动到当前位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM