Flutter Google Maps无法确定设备的当前位置

时间:2019-06-02 15:41:25

标签: google-maps flutter

我正在使用Flutter的Geolocator和Google Maps软件包来确定设备的位置。我利用圆形进度条等待当前位置确定。确定后,Google Maps会加载确定的设备位置。

在加载应用程序时,尽管显示了通知并已接受使用位置服务,但会显示圆形进度条,但不会加载地图;该应用程序挂在圆形进度栏上。我不认为这是API的问题,因为我已经成功地使用InitialCameraPosition中指定的坐标加载了地图。

是否未确定设备的位置,这是导致地图未加载所指示位置的原因?

我尝试在Android模拟器和物理设备上运行该应用程序,但均未成功。

Android Manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="smartkart.app.com.coffee">

<!-- io.flutter.app.FlutterApplication is an android.app.Application 
 that
     calls FlutterMain.startInitialization(this); in its onCreate 
  method.
     In most cases you can leave this as-is, but you if you want to   
      provide
     additional functionality it is fine to subclass or reimplement
     FlutterApplication and put your custom class here. -->

 <uses-permission  
 android:name="android.permission.ACCESS_FINE_LOCATION" />



<application
    android:name="io.flutter.app.FlutterApplication"
    android:label="coffee"
    android:icon="@mipmap/ic_launcher">
    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="API KEY HERE"/>
    <activity../>



Maps Screen

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';

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

  @override
  State<FirstScreen> createState() => _FirstScreen();
}

class _FirstScreen extends State<FirstScreen> {
  GoogleMapController mapController;

 var currentLocation;


@override
void initState(){
  super.initState();
  Geolocator().getCurrentPosition().then((currloc){
    currentLocation = currloc;
  });
}


  @override
  Widget build(BuildContext context) {
    return currentLocation == null ? Container(
      alignment: Alignment.center,
      child: Center(
        child: CircularProgressIndicator(),
      ),
    ):
      Stack(
      children: <Widget>[
        GoogleMap(
          initialCameraPosition:
           CameraPosition(target: LatLng(currentLocation.latitude,      
              currentLocation.longitude), zoom: 10),
          onMapCreated: _onMapCreated,
          myLocationEnabled: true,
          mapType: MapType.normal,
        ),
      ],
    );
  }



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


}

我希望在显示圆形进度栏时出现使用位置服务的通知。确定位置后,InitialCameraPosition将在地图上显示设备的位置。

2 个答案:

答案 0 :(得分:0)

您似乎在initState中缺少setState。 它应该看起来像这样:

(.)\1

答案 1 :(得分:0)

尝试以下代码作为解决方案。您可以将地图小部件修改为您的用例:

import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class Map extends StatefulWidget {
  @override
  _MapState createState() => _MapState();
}

class _MapState extends State<Map> {
  Completer<GoogleMapController> controller1;

  //static LatLng _center = LatLng(-15.4630239974464, 28.363397732282127);
  static LatLng _initialPosition;
  final Set<Marker> _markers = {};
  static  LatLng _lastMapPosition = _initialPosition;

  @override
  void initState() {
    super.initState();
    _getUserLocation();
  }
  void _getUserLocation() async {
    Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    List<Placemark> placemark = await Geolocator().placemarkFromCoordinates(position.latitude, position.longitude);
    setState(() {
      _initialPosition = LatLng(position.latitude, position.longitude);
      print('${placemark[0].name}');
    });
  }


  _onMapCreated(GoogleMapController controller) {
    setState(() {
      controller1.complete(controller);
    });
  }

  MapType _currentMapType = MapType.normal;

  void _onMapTypeButtonPressed() {
    setState(() {
      _currentMapType = _currentMapType == MapType.normal
          ? MapType.satellite
          : MapType.normal;
    });
  }

  _onCameraMove(CameraPosition position) {
    _lastMapPosition = position.target;
  }

  _onAddMarkerButtonPressed() {
    setState(() {
      _markers.add(
          Marker(
              markerId: MarkerId(_lastMapPosition.toString()),
              position: _lastMapPosition,
              infoWindow: InfoWindow(
                  title: "Pizza Parlour",
                  snippet: "This is a snippet",
                  onTap: (){
                  }
              ),
              onTap: (){
              },

              icon: BitmapDescriptor.defaultMarker));
    });
  }
  Widget mapButton(Function function, Icon icon, Color color) {
    return RawMaterialButton(
      onPressed: function,
      child: icon,
      shape: new CircleBorder(),
      elevation: 2.0,
      fillColor: color,
      padding: const EdgeInsets.all(7.0),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _initialPosition == null ? Container(child: Center(child:Text('loading map..', style: TextStyle(fontFamily: 'Avenir-Medium', color: Colors.grey[400]),),),) : Container(
        child: Stack(children: <Widget>[
          GoogleMap(
            markers: _markers,

            mapType: _currentMapType,
            initialCameraPosition: CameraPosition(
              target: _initialPosition,
              zoom: 14.4746,
            ),
            onMapCreated: _onMapCreated,
            zoomGesturesEnabled: true,
            onCameraMove: _onCameraMove,
            myLocationEnabled: true,
            compassEnabled: true,
            myLocationButtonEnabled: false,

          ),
          Align(
            alignment: Alignment.topRight,
            child: Container(
                margin: EdgeInsets.fromLTRB(0.0, 50.0, 0.0, 0.0),
                child: Column(
                  children: <Widget>[
                    mapButton(_onAddMarkerButtonPressed,
                        Icon(
                            Icons.add_location
                        ), Colors.blue),
                    mapButton(
                        _onMapTypeButtonPressed,
                        Icon(
                          IconData(0xf473,
                              fontFamily: CupertinoIcons.iconFont,
                              fontPackage: CupertinoIcons.iconFontPackage),
                        ),
                        Colors.green),
                  ],
                )),
          )
        ]),
      ),
    );
  }
}