如何获取谷歌地图颤振插件中标记的点的位置?

时间:2021-01-25 12:56:24

标签: flutter

如何获取谷歌地图flutter插件中标记的点的位置?我需要确定一个位置并获取要打印的该位置的确切地址。这是我的代码。关于如何做到这一点的任何建议?我一次只需要一个标记。如果在地图上标记了某个地点时,该位置会显示在一个小的弹出框中,那就太好了。提前致谢。

    class Map extends StatefulWidget {
  @override
  _MapState createState() => _MapState();
}

class _MapState extends State<Map> {
  final houseController = TextEditingController();
  final buildingController = TextEditingController();
  final zipController = TextEditingController();
  final cityController = TextEditingController();
  final stateController = TextEditingController();
  final locationController = TextEditingController();
  final combineAddressController = TextEditingController();
  final buildingNameController = TextEditingController();
  final subLocalityController = TextEditingController();
  final localityController = TextEditingController();
  var checkedValue = false;
  var locPg = false;
  var pg = true;

  Completer<GoogleMapController> controller1;

  static LatLng _initialPosition;
  final Set<Marker> _markers = {};
  static LatLng _lastMapPosition = _initialPosition;

  @override
  void initState() {
    super.initState();
    _getUserLocation();
  }

  void _getUserLocation() async {
    Position position = await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    List<Placemark> placemark = await Geolocator()
        .placemarkFromCoordinates(position.latitude, position.longitude);
    setState(() {
      _initialPosition = LatLng(position.latitude, position.longitude);
      print('${placemark[0].name}');
    });
  }

  _onMapCreated(GoogleMapController controller) {
    setState(() {
      controller1.complete(controller);
    });
  }

  MapType _currentMapType = MapType.hybrid;

  void _onMapTypeButtonPressed() {
    setState(() {
      _currentMapType =
          _currentMapType == MapType.hybrid ? MapType.normal : MapType.hybrid;
    });
  }

  _onCameraMove(CameraPosition position) {
    _lastMapPosition = position.target;
  }

  Widget mapButton(Function function, Icon icon, Color color) {
    return RawMaterialButton(
      onPressed: function,
      child: icon,
      shape: new CircleBorder(),
      elevation: 2.0,
      fillColor: color,
      padding: const EdgeInsets.all(7.0),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        centerTitle: true,
        title: Text(
          'Choose your location',
          style: TextStyle(color: Colors.white),
        ),
        leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: Icon(
            Icons.arrow_back_ios_rounded,
            color: Colors.white,
          ),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.check),
            color: Colors.white,
            onPressed: () async {
              HapticFeedback.heavyImpact();
              print("location tapped");
              Fluttertoast.showToast(
                  msg: "Location Updated!",
                  toastLength: Toast.LENGTH_SHORT,
                  gravity: ToastGravity.BOTTOM,
                  timeInSecForIosWeb: 1,
                  backgroundColor: Colors.blue,
                  textColor: Colors.white,
                  fontSize: 13.0);
              _getLocation();
              SharedPreferences prfs = await SharedPreferences.getInstance();
            },
          )
        ],
      ),
      body: _initialPosition == null
          ? Container(
              child: Center(
                child: Text(
                  'Loading map...',
                ),
              ),
            )
          : Container(
              child: Stack(children: <Widget>[
                GoogleMap(
                  markers: _markers,
                  // markers: Set<Marker>.of(markers.values),
                  mapType: _currentMapType,
                  // onTap: _getUserLocation(),
                  initialCameraPosition: CameraPosition(
                    target: _initialPosition,
                    zoom: 14.4746,
                  ),
                  onMapCreated: _onMapCreated,
                  // onTap: ,
                  zoomGesturesEnabled: true,
                  onCameraMove: _onCameraMove,
                  myLocationEnabled: true,
                  compassEnabled: true,
                  zoomControlsEnabled: true,
                  myLocationButtonEnabled: true,
                  padding: EdgeInsets.only(top: 100, bottom: 20, right: 15),
                ),
                Align(
                  alignment: Alignment.topRight,
                  child: Container(
                      margin: EdgeInsets.fromLTRB(0.0, 50.0, 0.0, 0.0),
                      child: Column(
                        children: <Widget>[
                          mapButton(
                            _onMapTypeButtonPressed,
                            Icon(
                              Icons.layers_outlined,
                              color: Colors.black87,
                              size: 25,
                            ),
                            Colors.white,
                          ),
                        ],
                      )),
                )
              ]),
            ),
    );
  }

  _getLocation() async {
    setState(() {
      locPg = true;
      pg = false;
    });
    try {
      Geolocator geoLocator = Geolocator()..forceAndroidLocationManager = true;
      Position currentLocation = await geoLocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.best);
      List<Placemark> placemark = await Geolocator().placemarkFromCoordinates(
          currentLocation.latitude, currentLocation.longitude);

      print("currentLocation");
      SharedPreferences prfs = await SharedPreferences.getInstance();
      prfs.setString("Lat", currentLocation.latitude.toString());
      prfs.setString("Long", currentLocation.longitude.toString());
      print(currentLocation.latitude);
      print(currentLocation.longitude);

      if (currentLocation != null) {
        print("position : ${placemark[0].position}");
        print("locality : ${placemark[0].locality}");
        print("administrativeArea : ${placemark[0].administrativeArea}");
        print("postalCode : ${placemark[0].postalCode}");
        print("name : ${placemark[0].name}");
        print("subAdministrativeArea : ${placemark[0].subAdministrativeArea}");
        print("isoCountryCode : ${placemark[0].isoCountryCode}");
        print("subLocality : ${placemark[0].subLocality}");
        print("subThoroughfare : ${placemark[0].subThoroughfare}");
        print("thoroughfare : ${placemark[0].thoroughfare}");

        if (placemark[0] != null) {
          if (placemark[0].administrativeArea.isNotEmpty) {
            stateController.text = placemark[0].administrativeArea;
          }
          if (placemark[0].postalCode.isNotEmpty) {
            zipController.text = placemark[0].postalCode;
          }
          if (placemark[0].subAdministrativeArea.isNotEmpty) {
            cityController.text = placemark[0].subAdministrativeArea;
          }
          if (placemark[0].name.isNotEmpty) {
            buildingController.text = placemark[0].name;
          }
          if (placemark[0].subLocality.isNotEmpty) {
            subLocalityController.text = placemark[0].subLocality;
          }
          if (placemark[0].locality.isNotEmpty) {
            localityController.text = placemark[0].locality;
          }
          if (placemark[0].name.isNotEmpty) {
            buildingNameController.text = placemark[0].name;
          }

          combineAddressController.text = buildingNameController.text +
              ", " +
              subLocalityController.text +
              ", " +
              localityController.text;

          setState(() {
            locPg = false;
            pg = true;
          });
        }
      }
    } on PlatformException catch (error) {
      print(error.message);
      setState(() {
        locPg = false;
        pg = true;
      });
    } catch (error) {
      print("Error: $error");
      setState(() {
        locPg = false;
        pg = true;
      });
    }
  }

1 个答案:

答案 0 :(得分:0)

我想 this article 会有所帮助。

相关问题