Created
June 3, 2020 09:36
-
-
Save wwwdata/afbc3cd75fcd938771c97c444e5ce53b to your computer and use it in GitHub Desktop.
Google Maps Marker with Flutter Widgets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:typed_data'; | |
import 'dart:ui' as ui; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter/rendering.dart'; | |
import 'package:google_maps_flutter/google_maps_flutter.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
visualDensity: VisualDensity.adaptivePlatformDensity, | |
), | |
home: MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
MyHomePage({Key key, this.title}) : super(key: key); | |
final String title; | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
final markerKey = GlobalKey(); | |
final markers = Set<Marker>(); | |
@override | |
void initState() { | |
WidgetsBinding.instance.addPostFrameCallback((_) async { | |
final markerUint = await getUint8List(markerKey); | |
markers.add(Marker( | |
markerId: MarkerId('one'), | |
position: LatLng(48.1548895, 11.4717969), | |
icon: BitmapDescriptor.fromBytes(markerUint))); | |
setState(() {}); | |
}); | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Stack( | |
children: <Widget>[ | |
Positioned( | |
left: 10000, | |
top: 10000, | |
child: RepaintBoundary( | |
key: markerKey, | |
child: CustomMarkerWidget(), | |
), | |
), | |
GoogleMap( | |
initialCameraPosition: CameraPosition( | |
target: LatLng(48.1548895, 11.4717969), zoom: 10.0), | |
markers: markers, | |
), | |
], | |
), | |
); | |
} | |
} | |
class CustomMarkerWidget extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Container( | |
width: 50.0, | |
height: 50.0, | |
color: Colors.red, | |
child: Center(child: Text('Market')), | |
); | |
} | |
} | |
Future<Uint8List> getUint8List(GlobalKey markerKey) async { | |
RenderRepaintBoundary boundary = markerKey.currentContext.findRenderObject(); | |
var image = await boundary.toImage(pixelRatio: 2.0); | |
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png); | |
return byteData.buffer.asUint8List(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment