Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

How to get location of a point marked in the google maps flutter plugin?

How to get the location of a point marked in the google maps flutter plugin? I need to pinpoint a single location and get the exact address of that location to print. This is my code. any suggestions on how to do that? i only need a single marker at a time. It would be nice if the location is shown in a small pop up box when a place is marked on the map. Thanks in advance.

    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;
      });
    }
  }
question from:https://stackoverflow.com/questions/65885214/how-to-get-location-of-a-point-marked-in-the-google-maps-flutter-plugin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suppose this article would be helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...