'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?
Solution 1:[1]
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;
});
},
),
);
}
}
Solution 2:[2]
Create a MapType variable:
MapType _currentMapType = MapType.normal;
Reference this variable when calling your Google Map widget:
googleMap = new GoogleMap( mapType: _currentMapType, //etc
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, ),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wali Khan |
Solution 2 |