Flutter : how to use google maps

Dr_Skele·2023년 3월 28일
0

Flutter

목록 보기
18/19

Guide to google maps on flutter
https://codelabs.developers.google.com/codelabs/google-maps-in-flutter?hl=en#0

How to get current location
https://pub.dev/packages/geolocator

With latitude and longitude, a marker can be set on the google map.


class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Google Office Locations'),
          backgroundColor: Colors.green[700],
        ),
        body: FutureBuilder(
            future: Geolocator.getCurrentPosition(),
            builder: (context, snapshot) {
              var location = snapshot.data;
              if (snapshot.hasData && location is Position) {
                print(
                    '${snapshot.data!.latitude}, ${snapshot.data!.longitude}');

                return GoogleMap(
                    initialCameraPosition: CameraPosition(
                      target: LatLng(location.latitude, location.longitude),
                      zoom: 11,
                    ),
                    markers: {
                      Marker(
                        markerId: MarkerId(
                            (location.timestamp ?? DateTime.now()).toString()),
                        position: LatLng(location.latitude, location.longitude),
                        infoWindow: InfoWindow(
                          title: 'location',
                          snippet: 'snippet',
                        ),
                      ),
                    } 
                    );
              }
              return Center(
                child: CircularProgressIndicator(),
              );
            }),
      ),
    );
  }
}

GoogleMap widget also provides 'onMapCreated' parameter which is called when map is generated, so instead of using FutureBuilder, location can be obtained after map generation and set the marker afterward using setState().

profile
Tireless And Restless Debugging In Source : TARDIS

0개의 댓글