中心多边形线Google Maps插件抖动适合屏幕Google Map

时间:2019-09-18 07:03:46

标签: google-maps flutter dart

想要找到2个点的中心并拟合地图。 在地图上查看时,我想适合所有屏幕。 我已准备好路线,但仅适合1点。请帮我。 此类用于颤振的地图视图。 我试图再过一天找到插件和解决方案,但仍然找不到。

 GoogleMap(
              mapType: MapType.normal,
              markers: _markers,
//              cameraTargetBounds: CameraTargetBounds(new LatLngBounds(
//                  northeast: LatLng(latFrom, logFrom),
//                  southwest: LatLng(latTo, logTo),
//              )),
//              minMaxZoomPreference: MinMaxZoomPreference(1, 15),
              mapToolbarEnabled: true,
              scrollGesturesEnabled: true,
              zoomGesturesEnabled: true,
              trafficEnabled: true,
              compassEnabled: true,
              indoorViewEnabled: true,
              rotateGesturesEnabled: true,
              tiltGesturesEnabled: true,
              myLocationButtonEnabled: true,
              myLocationEnabled: true,
              polylines: _polyline,
//              padding: EdgeInsets.all(20),
              initialCameraPosition:
                  CameraPosition(
                      target: LatLng(latFrom, logFrom),
                      zoom: 10,
                  ),
              onMapCreated: (GoogleMapController controller) {
                _controller.complete(controller);
              })

4 个答案:

答案 0 :(得分:7)

void _setMapFitToTour(Set<Polyline> p) {
    double minLat = p.first.points.first.latitude;
    double minLong = p.first.points.first.longitude;
    double maxLat = p.first.points.first.latitude;
    double maxLong = p.first.points.first.longitude;
    p.forEach((poly) {
      poly.points.forEach((point) {
        if(point.latitude < minLat) minLat = point.latitude;
        if(point.latitude > maxLat) maxLat = point.latitude;
        if(point.longitude < minLong) minLong = point.longitude;
        if(point.longitude > maxLong) maxLong = point.longitude;
      });
    });
    mapController.moveCamera(CameraUpdate.newLatLngBounds(LatLngBounds(
      southwest: LatLng(minLat, minLong),
      northeast: LatLng(maxLat,maxLong)
    ), 20));
  }

答案 1 :(得分:0)

今天我遇到了同样的问题,偶然发现了你的问题。我发现了两个可以提供帮助的链接。

https://medium.com/flutter-community/drawing-route-lines-on-google-maps-between-two-locations-in-flutter-4d351733ccbe

https://stackoverflow.com/a/55990256/1537413

结合这两个链接后,我得到了完美的解决方案。

你在这里。

import 'dart:async';

import 'package:app/env.dart';
import 'package:flutter/material.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class RoutePage extends StatefulWidget {
  @override
  _RoutePageState createState() => _RoutePageState();
}

class _RoutePageState extends State<RoutePage> {
  Completer<GoogleMapController> _controller = Completer();
  GoogleMapController mapController;

  final Set<Marker> _markers = {};

  Set<Polyline> _polylines = {};
  List<LatLng> polylineCoordinates = [];
  PolylinePoints polylinePoints = PolylinePoints();
  String googleAPIKey = GOOGLE_MAPS_API_KEY;

  static LatLng sourceLocation = LatLng(42.7477863, -71.1699932);
  static LatLng destLocation = LatLng(42.6871386, -71.2143403);

  void _onMapCreated(GoogleMapController controller) async {
    mapController = controller;
    _controller.complete(controller);

    LatLng temp;

    if (sourceLocation.latitude > destLocation.latitude) {
      temp = sourceLocation;
      sourceLocation = destLocation;
      destLocation = temp;
    }

    LatLngBounds bound =
        LatLngBounds(southwest: sourceLocation, northeast: destLocation);

    BitmapDescriptor sourceIcon = await BitmapDescriptor.fromAssetImage(
        ImageConfiguration(devicePixelRatio: 2.5), 'assets/driving_pin.png');
    BitmapDescriptor destinationIcon = await BitmapDescriptor.fromAssetImage(
        ImageConfiguration(devicePixelRatio: 2.5),
        'assets/destination_map_marker.png');

    setState(() {
      _markers.clear();
      addMarker(sourceLocation, "Madrid", "5 Star Rating", icon: sourceIcon);
      addMarker(destLocation, "Barcelona", "7 Star Rating",
          icon: destinationIcon);
    });

    CameraUpdate u2 = CameraUpdate.newLatLngBounds(bound, 50);
    this.mapController.animateCamera(u2).then((void v) {
      check(u2, this.mapController);
    });
  }

  void addMarker(LatLng mLatLng, String mTitle, String mDescription,
      {BitmapDescriptor icon}) {
    _markers.add(Marker(
      markerId: MarkerId(
          (mTitle + "_" + _markers.length.toString()).toString()), //must unique
      position: mLatLng,
      infoWindow: InfoWindow(
        title: mTitle,
        snippet: mDescription,
      ),
      icon: icon,
    ));
  }

  void check(CameraUpdate u, GoogleMapController c) async {
    c.animateCamera(u);
    mapController.animateCamera(u);
    LatLngBounds l1 = await c.getVisibleRegion();
    LatLngBounds l2 = await c.getVisibleRegion();
    print(l1.toString());
    print(l2.toString());

    if (l1.southwest.latitude == -90 || l2.southwest.latitude == -90)
      check(u, c);
    else {
      await setPolylines();
    }
  }

  void _onCameraMove(CameraPosition position) {}

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Maps Sample App'),
          backgroundColor: Colors.green[700],
        ),
        body: GoogleMap(
          myLocationEnabled: true,
          compassEnabled: true,
          tiltGesturesEnabled: false,
          markers: _markers,
          polylines: _polylines,
          mapType: MapType.normal,
          onMapCreated: _onMapCreated,
          initialCameraPosition: CameraPosition(
            target: sourceLocation,
            zoom: 13.0,
          ),
          onCameraMove: _onCameraMove,
        ),
      ),
    );
  }

  setPolylines() async {
    List<PointLatLng> result = await polylinePoints?.getRouteBetweenCoordinates(
        googleAPIKey,
        sourceLocation.latitude,
        sourceLocation.longitude,
        destLocation.latitude,
        destLocation.longitude);
    if (result.isNotEmpty) {
      result.forEach((PointLatLng point) {
        polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      });
    }

    setState(() {
      Polyline polyline = Polyline(
          polylineId: PolylineId("poly"),
          color: Color.fromARGB(255, 40, 122, 198),
          points: polylineCoordinates);

      _polylines.add(polyline);
    });
  }
}

答案 2 :(得分:0)

google_maps_flutter: ^0.5.30
flutter_polyline_points: ^0.2.2

请确保已使用.then()函数,因为setPolyline()是异步函数且具有await关键字。 使用这些依赖项

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

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

class _ShowMapState extends State<ShowMap> {
  GoogleMapController _googleMapController;
  Set<Polyline> _polylines = {};
  List<LatLng> polylineCoordinates = [];
  PolylinePoints polylinePoints = PolylinePoints();
  String googleAPIKey = "YOUR_API_KEY_HERE";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorUtils.bluePrimary,
      appBar: AppBar(
        // automaticallyImplyLeading: false,
        backgroundColor: ColorUtils.greenPrimary,
        title: Center(
          child: Column(
            children: [
              Text(
                'Delivery Accepted! ',
                style: TextStyle(fontSize: 18.0, letterSpacing: -0.3333),
              ),
             
            ],
          ),
        ),
      ),
      body: Column(
        children: [
          Expanded(
            flex: 5,
            child: Center(
              child: Container(
                margin: EdgeInsets.only(top: 10),
                decoration: BoxDecoration(
                    // color: Colors.white,
                    ),
                width: MediaQuery.of(context).size.width - 10,
                height: MediaQuery.of(context).size.height * 0.5,
                child: GoogleMap(
                    cameraTargetBounds: CameraTargetBounds.unbounded,
                    initialCameraPosition: _initialPosition,
                    onMapCreated: _onMapCreated,
                    tiltGesturesEnabled: true,
                    scrollGesturesEnabled: true,
                    zoomGesturesEnabled: true,
                    // trafficEnabled: true,
                    polylines: _polylines),
              ),
            ),
          ),
          ),
        ],
      ),
    );
  }

  static final CameraPosition _initialPosition = CameraPosition(
      // bearing: 192.8334901395799,
      target: LatLng(31.5204, 74.3587),
      zoom: 12);

  void _onMapCreated(GoogleMapController controller) async {
    setState(() {
      _googleMapController = controller;
      setPolylines().then((_) => _setMapFitToTour(_polylines));
    });
  }

  void _setMapFitToTour(Set<Polyline> p) {
    double minLat = p.first.points.first.latitude;
    double minLong = p.first.points.first.longitude;
    double maxLat = p.first.points.first.latitude;
    double maxLong = p.first.points.first.longitude;

    p.forEach((poly) {
      poly.points.forEach((point) {
        if (point.latitude < minLat) minLat = point.latitude;
        if (point.latitude > maxLat) maxLat = point.latitude;
        if (point.longitude < minLong) minLong = point.longitude;
        if (point.longitude > maxLong) maxLong = point.longitude;
      });
    });
    _googleMapController.animateCamera(CameraUpdate.newLatLngBounds(
        LatLngBounds(
            southwest: LatLng(minLat, minLong),
            northeast: LatLng(maxLat, maxLong)),
        20));
  }

  setPolylines() async {
    PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
      googleAPIKey,
      PointLatLng(31.5204, 74.3587),
      PointLatLng(31.4504, 74.1350),
    );
    if (result.points.isNotEmpty) {
      result.points.forEach((PointLatLng point) {
        polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      });
    } else {
      print("--address not found ---");
    }
    setState(() {
      Polyline polyline = Polyline(
          polylineId: PolylineId("poly"),
          color: Color.fromARGB(255, 40, 122, 198),
          width: 5,
          points: polylineCoordinates);
      _polylines.add(polyline);
    });
  }
}

答案 3 :(得分:0)

今天我遇到了同样的问题,我偶然发现了你的问题。在实施时查看答案,我发现了一种更简单的方法。

LatLangBounds 类中有一个名为 .fromPoint(List<LatLng> points) 的方法,该方法获取点列表并返回边界。

我将它与 MapController 类一起使用,它完美地显示了地图上的边界。根据我对 GoogleMapController 的理解,它应该可以工作。

mapController.fitBounds(LatLngBounds.fromPoints(list_of_points));

理想情况下,这应该是谷歌地图等效的内容

googleMapController.moveCamera(
  CameraUpdate.newLatLngBounds(
    LatLngBounds.fromPoints(list_of_points)
  ),zoomIndex)
);

.fromPoints(List<LatLng> points) 方法执行每个人都已实际实现的功能。希望这可以帮助任何需要它的人。