在 flutter 中单击按钮时获取当前位置并向 openstreetmaps 添加标记

问题描述 投票:0回答:1

我想在我的按钮中添加功能,当我单击该按钮时,openstreetmaps 会用红色标记显示我当前的位置。这是我的代码:

我的页面.dart

import 'package:geocoding/geocoding.dart'; // Package maps
import 'package:geolocator/geolocator.dart'; // Package maps
import 'package:flutter_map/flutter_map.dart'; // Package maps
import 'package:latlong2/latlong.dart'; // Package maps

class _AbsenPageState extends State<AbsenPage> {
  Position? _currentLocation;
  bool servicePermission = false;
  LocationPermission permission = LocationPermission.denied;
  String _currentAddress = "";
  bool showSyncText = true; // Variabel untuk mengontrol apakah teks "Klik icon untuk sinkronisasi" ditampilkan

  Future<Position> _getCurrentLocation() async {
    servicePermission = await Geolocator.isLocationServiceEnabled();
    if (!servicePermission) {
      print("Service Disabled");
    }
    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
    }
    return await Geolocator.getCurrentPosition();
  }

  _getAddressFromCoordinates() async {
    try {
      List<Placemark> placemarks = await placemarkFromCoordinates(
        _currentLocation!.latitude,
        _currentLocation!.longitude,
      );

      Placemark place = placemarks[0];

      setState(() {
        _currentAddress = "${place.street}";
        showSyncText = false; // Setel showSyncText menjadi false setelah alamat tersedia
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        fit: StackFit.expand,
        children: [
          FlutterMap(
            options: const MapOptions(
              center: LatLng(-7.238141, 112.734710),
              zoom: 18.0,
            ),
            children: [
              TileLayer(
                urlTemplate:
                'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
                subdomains: const ['a', 'b', 'c'],
              ),

            ],
          ),

这是我的按钮:

ElevatedButton(
                onPressed: () async {
                  _currentLocation = await _getCurrentLocation();
                  await _getAddressFromCoordinates();
                  print("$_currentAddress");
                },

我应该添加什么代码来获取当前位置并在单击按钮时向 openstreetmaps 添加标记

flutter gps location openstreetmap
1个回答
0
投票

flutter_map 
官方网站本身中,他们提到这超出了他们的范围,我们需要添加 flutter_map_location_marker 来实现标记。

© www.soinside.com 2019 - 2024. All rights reserved.