【问题标题】:Center poly line google maps plugin flutter fit to screen google map中心折线谷歌地图插件颤振适合屏幕谷歌地图
【发布时间】:2023-03-06 20:37:01
【问题描述】:

想要找到 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);
              })

【问题讨论】:

    标签: google-maps flutter dart


    【解决方案1】:
    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));
      }
    

    【讨论】:

    • 虽然这可能是正确的答案,但如果你能添加一些解释会很有帮助 - from review
    • 你今天真的救了我。非常感谢。
    • 这是正确的答案。除非您必须交换 southwest 和 northeast 值,因为当 south.latitue 为 时,谷歌地图会抛出错误
    【解决方案2】:
    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】:

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

      LatLangBounds 类中有一个名为 .fromPoint(List&lt;LatLng&gt; points) 的方法,它接受点列表并返回边界。

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

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

      理想情况下,这应该是 google 地图等价物应该是的

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

      .fromPoints(List&lt;LatLng&gt; points) 方法完成了每个人实际上已经实现的事情。希望这可以帮助任何需要它的人。

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 2019-11-05
          • 2020-07-19
          • 2019-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多