如何使Flutter GoogleMap initialCameraPosition显示用户的当前位置?

时间:2019-10-17 16:32:06

标签: flutter dart

好,所以我有一个地图屏幕,用户可以在其中选择位置并放置标记,但是问题是我无法弄清楚如何将GoogleMap initialCameraPosition设置为用户的当前位置。

我真不明白如何执行Flutter Location软件包(https://pub.dev/packages/location)中的指令。

我觉得很愚蠢,我希望我能弄清楚:'(

import 'package:location/location.dart';

class MapScreen extends StatefulWidget {

@override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  LatLng _pickedLocation;

  void _selectLocation(LatLng position) {
    setState(
      () {
        _pickedLocation = position;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
body: GoogleMap(
        compassEnabled: true,
        myLocationButtonEnabled: true,
        myLocationEnabled: true,
        initialCameraPosition: CameraPosition(
          target: LatLng(0, 0),
          zoom: 16,
        ),
        onTap: widget.isSelecting ? _selectLocation : null,
        markers: (_pickedLocation == null && widget.isSelecting)
            ? null
            : {
                Marker(
                  markerId: MarkerId('m1'),
                  position: _pickedLocation ??
                      LatLng(widget.initialLocation.latitude,
                          widget.initialLocation.longitude),
                ),
              },
      ),
      floatingActionButton: widget.isSelecting
          ? FloatingActionButton(
              disabledElevation: 0,
              child: Icon(Icons.check),
              onPressed: _pickedLocation == null
                  ? null
                  : () {
                      Navigator.of(context).pop(_pickedLocation);
                    },
            )
          : null,
    );
  }
}

我试图自己弄清楚这一点,但我不知道如何正确地做到这一点,需要有人来解释我需要做什么和为什么。

1 个答案:

答案 0 :(得分:0)

添加位置库

import 'package:location/location.dart';

var location = new Location();

并添加 OnMapCreated

GoogleMap(
        compassEnabled: true,
        myLocationButtonEnabled: true,
        myLocationEnabled: true,
        initialCameraPosition: CameraPosition(
          target: LatLng(0, 0),
          zoom: 16,
        ),
        onTap: widget.isSelecting ? _selectLocation : null,
        markers: (_pickedLocation == null && widget.isSelecting)
            ? null
            : {
                Marker(
                  markerId: MarkerId('m1'),
                  position: _pickedLocation ??
                      LatLng(widget.initialLocation.latitude,
                          widget.initialLocation.longitude),
                ),
              },

    onMapCreated: (GoogleMapController controller) {
     var here = await location.getLocation();
    controller.animateCamera(
              CameraUpdate.newCameraPosition(
                CameraPosition(
                    target: LatLng(here.latitude, here.longitude)),
              ),
            );
    }),