Search code examples
fluttergpslocationopenstreetmap

Get current location and add marker to openstreetmaps when button clicked in flutter


I want to add feature in my button, when i clicked the button, openstreetmaps will show my current location with red marker. this is my code :

My Page.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'],
              ),

            ],
          ),

This is my button :

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

What the code that i should add to get current location and add marker to openstreetmaps when button clicked


Solution

  • In flutter_map official site itself they mentioned that its beyond their scope and we need to add flutter_map_location_marker to achieve marker. enter image description here