在Google Maps上长按时如何使图钉掉落?

时间:2019-07-23 08:01:09

标签: google-maps flutter dart

我是新手。 我正试图在地图上乱扔图钉,

在这里,我使用geolocator软件包获取了当前位置并设置了一个标记


 GoogleMap(
            onMapCreated: (controller){
              mapController=controller ;
            },
            mapType: _currentMapType,
            myLocationEnabled: true,
            initialCameraPosition: CameraPosition(
              target:_center,
              zoom: 11.0,
            ),
            markers: {
              //Marker for current Location
              Marker(
                markerId: MarkerId("marker"),
                position: LatLng(currentPosition.latitude, currentPosition.longitude),
                infoWindow: InfoWindow(title: 'Current Location'),
                icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed)
              )  
            },
          ),

1 个答案:

答案 0 :(得分:1)

我最近正在编写此代码,可能会对您有所帮助。

1.-首先以这种方式定义标记(将其作为全局变量):

Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

2.-创建Google Maps小部件:

@override
Widget build(BuildContext context) {
    return new Scaffold(
        body: Stack(
            children: [Container(
                height: MediaQuery.of(context).size.height,
                width: MediaQuery.of(context).size.width,
                child: GoogleMap(
                    mapType: _defaultMapType,
                    myLocationEnabled: true,
                    myLocationButtonEnabled: true,
                    initialCameraPosition: _currentposition,
                    onMapCreated: (GoogleMapController controller) {
                      _controller.complete(controller);
                    },
                    compassEnabled: true,
                    tiltGesturesEnabled: false,
                    onLongPress: (latlang) {
                        _addMarkerLongPressed(latlang); //we will call this function when pressed on the map
                    },
                    markers: Set<Marker>.of(markers.values), //all markers are here
                )
            )]
        ),
    );
}

3.-创建函数(方法)“ _ addMarkerLongPressed”:

Future _addMarkerLongPressed(LatLng latlang) async {
    setState(() {
        final MarkerId markerId = MarkerId("RANDOM_ID");
        Marker marker = Marker(
            markerId: markerId,
            draggable: true,
            position: latlang, //With this parameter you automatically obtain latitude and longitude
            infoWindow: InfoWindow(
                title: "Marker here",
                snippet: 'This looks good',
            ),
            icon: BitmapDescriptor.defaultMarker,
        );

        markers[markerId] = marker;
    });

    //This is optional, it will zoom when the marker has been created
    GoogleMapController controller = await _controller.future;
    controller.animateCamera(CameraUpdate.newLatLngZoom(latlang, 17.0));
}

我希望我有所帮助:)