我是Flutter的新手,正在做tutorial to add a google map,我的代码如下:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Completer<GoogleMapController> _controller = Completer();
static const LatLng _center = const LatLng(45.521563, -122.677433);
MapType _currentMapType= MapType.normal;
void _onMapTypeButtonPressed(){
setState(() {
_currentMapType = _currentMapType == MapType.normal
? MapType.satellite
: MapType.normal;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Maps Sample App'),
backgroundColor: Colors.green[700],
),
body: Stack(
children: <Widget>[
GoogleMap(
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
mapType: _currentMapType,
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Align(
alignment: Alignment.topRight,
child: FloatingActionButton(
onPressed: _onMapTypeButtonPressed,
materialTapTargetSize: MaterialTapTargetSize.padded,
backgroundColor: Colors.green,
child: const Icon(Icons.map, size: 36.0),
),
)
)
],
)
),
);
}
}
此后,该教程显示了如何通过按钮添加一些标记,但是我想通过在用户长按地图时添加标记来改善这一点,但是我并没有真正理解如何实现此功能...我发现一些文档向我证明了该功能的存在,但并不是真正的用法。 (发现我必须在GoogleMap()小部件中添加onTap:[我的方法],但这无法识别为功能)
答案 0 :(得分:1)
第一
Set<Marker> _markers = Set();
将其添加到地图 然后在GoogleMap小部件中添加onTap :(您的方法将默认设置LatLng)和Marker:(_ markers)
GoogleMap(
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
mapType: _currentMapType,
onTap: (LatLng latLng) {
_markers.add(Marker(markerId: MarkerId('mark'), position: latLng));
setState(() {});
} ,
markers: Set<Marker>.of(_markers),
)
不要忘记更改markerId,它必须是唯一的。