Fix google map marker in center

后端 未结 5 1671
情歌与酒
情歌与酒 2020-12-28 09:41

In my flutter app. I am using google_maps_plugin . The link is https://github.com/flutter/plugins/tree/master/packages/google_maps_flutter . I want to fix the m

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 10:23

    Actually with new update of google_maps_flutter: ^0.4.0 we can achieve above requirement easily.

    This is the demo link.

    Map _markers = {};
    int _markerIdCounter = 0;
    Completer _mapController = Completer();
    
    Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: GoogleMap(
          markers: Set.of(_markers.values),
          onMapCreated: _onMapCreated,
          initialCameraPosition: CameraPosition(
            target: Constants.LOCATION_SRI_LANKA,
            zoom: 12.0,
          ),
          myLocationEnabled: true,
          onCameraMove: (CameraPosition position) {
            if(_markers.length > 0) {
              MarkerId markerId = MarkerId(_markerIdVal());
              Marker marker = _markers[markerId];
              Marker updatedMarker = marker.copyWith(
                positionParam: position.target,
              );
    
              setState(() {
                _markers[markerId] = updatedMarker;
              });
            }
          },
        ),
      )
    
    void _onMapCreated(GoogleMapController controller) async {
      _mapController.complete(controller);
      if ([INITIAL_LOCATION] != null) {
        MarkerId markerId = MarkerId(_markerIdVal());
        LatLng position = [INITIAL_LOCATION];
        Marker marker = Marker(
          markerId: markerId,
          position: position,
          draggable: false,
        );
        setState(() {
          _markers[markerId] = marker;
        });
    
        Future.delayed(Duration(seconds: 1), () async {
          GoogleMapController controller = await _mapController.future;
          controller.animateCamera(
            CameraUpdate.newCameraPosition(
              CameraPosition(
                target: position,
                zoom: 17.0,
              ),
            ),
          );
        });
      }
    }
    
    String _markerIdVal({bool increment = false}) {
      String val = 'marker_id_$_markerIdCounter';
      if (increment) _markerIdCounter++;
      return val;
    }
    

提交回复
热议问题