【问题标题】:Flutter map_view center to user location颤动 map_view 中心到用户位置
【发布时间】:2019-01-16 06:09:38
【问题描述】:

我正在使用 map_view 插件在我的 Fluter 应用程序中构建地图。我正在按照示例进行操作,但我想将地图初始化为用户当前位置,而不对坐标进行硬编码。

我一直在研究文档和 Github 问题,发现 this,但我不明白如何应用它。

地图是这样初始化的:

mapView.show(
    new MapOptions(
        mapViewType: MapViewType.normal,
        showUserLocation: true,
        initialCameraPosition: new CameraPosition(
            new Location(45.5235258, -122.6732493), 14.0),
        title: "Recently Visited"),
    toolbarActions: [new ToolbarAction("Close", 1)]);

地图准备就绪时收到通知

如何使用此代码设置地图的位置?

mapView.onLocationUpdated.listen((location) => myUserLocation = location);

这是我的全部代码:

Location myUserLocation = null;

class NuMapView extends StatefulWidget {
  @override
_NuMapViewState createState() => new _NuMapViewState();
}




class _NuMapViewState extends State<NuMapView> {
  static String apiKey = "mykey";

  MapView mapView;
  CameraPosition cameraPosition;
  var compositeSubscription = new CompositeSubscription();
  var staticMapProvider = new StaticMapProvider(apiKey);
  Uri staticMapUri;




  @override
  void initState(){
      print("dentro init state\n");

  mapView = new MapView();
  mapView.onLocationUpdated.listen((location) {
    print("cacchissime\n");
    if (myUserLocation == null){
      print("user location non null\n");
      myUserLocation = location;
      showMap();
    }
    else {
      print("user location è nullo!!\n");
    }


  } );

  super.initState();
    }



    bool ready = false;

  List<Marker> _markers = new List<Marker>();


    });
  }





  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: new Text("ciao")
      ),

    );
  }

  showMap() {
    mapView.show(
        new MapOptions(
            mapViewType: MapViewType.normal,
            showUserLocation: true,
            showMyLocationButton: true,
            showCompassButton: true,
            initialCameraPosition: new CameraPosition(
                new Location(myUserLocation.latitude, myUserLocation.longitude), 35.0),
            hideToolbar: false,
            title: "Cerca sulla mappa"),

        );
    StreamSubscription sub = mapView.onMapReady.listen((_) {
      mapView.setMarkers(_markers);

    });
    compositeSubscription.add(sub);
    sub = mapView.onLocationUpdated.listen((location) {
      print("Location updated $location");
    });
    compositeSubscription.add(sub);
    sub = mapView.onTouchAnnotation
        .listen((annotation) => print("annotation ${annotation.id} tapped"));
    compositeSubscription.add(sub);

    sub = mapView.onCameraChanged.listen((cameraPosition) =>
        this.setState(() => this.cameraPosition = cameraPosition));
    compositeSubscription.add(sub);


  }

【问题讨论】:

  • 初始化mapview的时候能不能放代码?
  • 是同一个文档,但我会更新我的问题

标签: google-maps dart flutter


【解决方案1】:

好的,根据您发布的信息,您可以执行以下操作:

  //state class variable    
  Location myUserLocation;


      @override
      void initState() {
         mapView.onLocationUpdated.listen((location) {
            if (myUserLocation == null){
                myUserLocation = location;
                _loadMap();
            }

         } );
        super.initState();
      }


      _loadMap(){
          mapView.show(
           new MapOptions(
              mapViewType: MapViewType.normal,
              showUserLocation: true,
              initialCameraPosition: new CameraPosition(
                  new Location(myUserLocation.latitude, myUserLocation.longitude), 14.0),
              title: "Recently Visited"),
          toolbarActions: [new ToolbarAction("Close", 1)]);
      }

首先,在initState 之后,您可以获取您当前的位置并使用您的位置调用 showMap。

【讨论】:

  • 我试过这段代码,但它没有进入 onLocationUpdated 并且地图没有被加载..
  • 你能给我们更多的信息吗?该应用程序是否要求有关位置的权限?您可以更新问题中的代码吗?是否启用了 GPS?
  • 请求许可,gps 已启用。我在 ClassViewState 方法中编写了变量和 initState 方法覆盖。我在 initState 方法中写了一个调试打印:它进入了方法,但只是没有进入 .listen 部分......
  • 刚刚更新了代码,我删掉了一些其他没用的方法
  • 你听了两次: sub = mapView.onLocationUpdated.listen((location) { print("Location updated $location"); });删除它
【解决方案2】:

这段代码你需要什么(我已经展示了完整的代码,你可以直接尝试):

注意,在运行此代码之前,您需要将google_maps_flutterlocationpermission 包安装到项目中。

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:permission/permission.dart';

void main() => runApp(TestMap());

class TestMap extends StatefulWidget {
  @override
  _TestMapState createState() => _TestMapState();
}

class _TestMapState extends State<TestMap> {
  @override
  Widget build(BuildContext context) {
    //To Require Permission
    Permission.openSettings;

    return MaterialApp(
      title: 'Flutter Google Maps Demo',
      home: MapSample(),
    );
  }
}

class MapSample extends StatefulWidget {
  @override
  State<MapSample> createState() => MapSampleState();
}

class MapSampleState extends State<MapSample> {
  Map<PolylineId, Polyline> _mapPolylines = {};
  int _polylineIdCounter = 1;

  static double latitude_current = 31.9414246;
  static double longitude_current = 35.8880857;

  void _GetDeviceLocation() async {
    var location = new Location();
    location.changeSettings(
      accuracy: LocationAccuracy.HIGH,
      distanceFilter: 0,
      interval: 100,
    );
    location.onLocationChanged().listen((LocationData currentLocation) {
      latitude_current = currentLocation.latitude;
      longitude_current = currentLocation.longitude;
      _goToTheLake();
    });
  }



  Completer<GoogleMapController> _controller = Completer();

  static final CameraPosition _kLake = CameraPosition(
      bearing: 60.8334901395799,
      target: LatLng(latitude_current, longitude_current),
      tilt: 80.440717697143555,
      zoom: 18.151926040649414);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("Maps"),
        actions: <Widget>[IconButton(icon: Icon(Icons.add), onPressed: _GetDeviceLocation)],
      ),
      body: GoogleMap(
        mapType: MapType.normal,
        initialCameraPosition: CameraPosition(
          target: LatLng(latitude_current, longitude_current),
          zoom: 14.4746,
        ),
        onMapCreated: (GoogleMapController controller) async {
          _GetDeviceLocation();
          _controller.complete(controller);
        },
        myLocationEnabled: true,
        polylines: Set<Polyline>.of(_mapPolylines.values),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _goToTheLake,
        label: Text('Drive Mode'),
        icon: Icon(Icons.directions_boat),
      ),
    );
  }

  Future<void> _goToTheLake() async {
    _GetDeviceLocation();
    final GoogleMapController controller = await _controller.future;
    controller.animateCamera(CameraUpdate.newCameraPosition(_kLake));

  }
}

【讨论】:

  • 我正在使用您的答案在地图中加载位置,地图动画很慢并且需要永远加载。我的连接速度很快
  • 修复了它。如果你为 latitude_current 和 longitude_current 设置默认值,它的行为会不正常
【解决方案3】:

我找到了使用 GeoLocator 插件的解决方案... 试试这个代码..

  _animateToUser() async {
    Geolocator().getCurrentPosition().then((currloc) {
      setState(() {
        currentLocation = currloc;
      });
    });

    mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
      target: LatLng(currentLocation.latitude, currentLocation.longitude),
      zoom: 17.0,
    )));
  }

在谷歌地图部分...

Stack(
  children: <Widget>[
    GoogleMap(
      initialCameraPosition: CameraPosition(target: LatLng(currentLocation.latitude, currentLocation.longitude), zoom: 17),
      onMapCreated: _onMapCreated,
      myLocationEnabled: true,
      mapType: _currentMapType,
      markers: Set<Marker>.of(markers.values),
    ),
  ],
);

希望大于帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-10
    • 2018-09-30
    • 2022-12-06
    • 1970-01-01
    • 2021-12-08
    • 2021-10-08
    • 1970-01-01
    • 2019-04-29
    相关资源
    最近更新 更多