Flutter Google Maps无法确定设备的当前位置 [英] Flutter Google Maps not determining current location of device

查看:114
本文介绍了Flutter Google Maps无法确定设备的当前位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Flutter's Geolocator and Google Maps packages to determine a device's location. I utilize the Circular Progress Bar to wait for the current location to be determined. Once determined, Google Maps loads with the device's location identified.

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

When the application loads, the circular progress bar is displayed but the map is not loaded despite the notification being displayed and accepted to use location services; the app hangs on the circular progress bar. I don't believe this to be an API issue as I have had success loading the map with coordinates specified in InitialCameraPosition.

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

Is the device's location not being determined which is the cause for the map to not load with the location indicated?

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

I've tried running the app on both Android emulator and a physical device without success.

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将在地图上显示设备的位置.

I expect the notification to use location services to appear while the circular progress bar is displayed. Once the location is determined, the InitialCameraPosition displays the device's location on the map.

推荐答案

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

Try the following code as a solution. You can modify the map widget to your use case:

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

这篇关于Flutter Google Maps无法确定设备的当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆