简体   繁体   中英

Flutter Google Maps: How can you change maptype after runtime?

I am trying to change from normal to satellite when pressing a button as shown below, but i get an error that setMapType does not exist.

mapController.setMapType(MapType.satellite);

Anyone knows what I am doing wrong?

  1. Create a MapType variable:

     MapType _currentMapType = MapType.normal;
  2. Reference this variable when calling your Google Map widget:

     googleMap = new GoogleMap( mapType: _currentMapType, //etc
  3. Create a floating button widget to toggle map types:

     floatingActionButton: FloatingActionButton( child: Icon(Icons.layers), onPressed: ()=> { setState(() { _currentMapType = (_currentMapType == MapType.normal)? MapType.satellite: MapType.normal; }); }, heroTag: null, ),
     import 'dart:async';

   import 'package:flutter/material.dart';

     import 'package:search_map_place/search_map_place.dart';
   import 'package:google_maps_flutter/google_maps_flutter.dart';

   String apiKEY;

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

 class MyApp extends StatelessWidget {
   @override
     Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Search Map Place Demo',
        home: MapSample(),
         );
         }
      }

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

      class MapSampleState extends State<MapSample> {
      Completer<GoogleMapController> _mapController = Completer();

      final CameraPosition _initialCamera = CameraPosition(
      target: LatLng(-20.3000, -40.2990),
      zoom: 14.0000,
      );
      var maptype = MapType.normal;
       @override
       Widget build(BuildContext context) {
       return Scaffold(
       resizeToAvoidBottomPadding: false,
      body: Stack(
       children: <Widget>[
        GoogleMap(
        mapType: maptype,
        initialCameraPosition: _initialCamera,
        onMapCreated: (GoogleMapController controller) {
          _mapController.complete(controller);
        },
      ),
          
          ],
          ),

     floatingActionButton: FloatingActionButton(
    backgroundColor: Colors.white,
    foregroundColor: Colors.black,
    child: const Icon(Icons.my_location),
    onPressed: () {
    setState(() {
      
      this.maptype=MapType.satellite;
    });
    },
  ),


            );
          }
          }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM