Home > Mobile >  My current location always locates google plex in Flutter
My current location always locates google plex in Flutter

Time:04-13

My current location always shows Google Plex when I clicked the current location button. I don't know where is the error as I already added my API and asked for user permissions which are

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

in AndriodManifest.xml. I really need help to solve this problem. Thank you in advance!

location_map.dart

import 'package:final_year_project/constant.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class LocationMap extends StatefulWidget {
  const LocationMap({Key? key}) : super(key: key);

  @override
  _LocationMapState createState() => _LocationMapState();
}

class _LocationMapState extends State<LocationMap> {
  late GoogleMapController mapController;

  final LatLng _center = const LatLng(3.140853, 101.693207);

  Set<Marker> markers = {};

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Stack(
          children: [
            SizedBox(
                height: MediaQuery.of(context).size.height,
                width: double.infinity,
                child: GoogleMap(
                    markers: markers,
                    mapType: MapType.normal,
                    myLocationEnabled: true,
                    onMapCreated: _onMapCreated,
                    initialCameraPosition:
                        CameraPosition(target: _center, zoom: 10),
                    
                )
            ),
            Padding(
              padding: const EdgeInsets.fromLTRB(5, 10, 70, 0),
              child: SizedBox(
                height: 40,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                        flex: 1,
                        child: IconButton(
                          icon: const Icon(Icons.arrow_back_ios),
                          onPressed: () {
                            Navigator.pop(context);
                          },
                        )),
                    Expanded(
                      flex: 9,
                      child: TextField(
                        decoration: InputDecoration(
                            filled: true,
                            fillColor: Colors.white,
                            hintText: 'Enter Your Location',
                            hintStyle: primaryFontStyle,
                            suffixIcon: const Icon(Icons.search),
                            contentPadding: const EdgeInsets.only(
                                left: 20, bottom: 0, right: 0),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5),
                              //borderSide: const BorderSide(width: 0.5),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5),
                              //borderSide: const BorderSide(width: 0.5),
                            )),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Positioned(
              bottom: 20,
              left: 10,
              child: FloatingActionButton.extended(
                onPressed: () async {
                  Position position = await _determinePosition();

                  mapController.animateCamera(CameraUpdate.newCameraPosition(
                      CameraPosition(
                          target: LatLng(position.latitude, position.longitude),
                          zoom: 12.0)));

                  markers.clear();

                  markers.add(Marker(
                      markerId: const MarkerId('currentLocation'),
                      position: LatLng(position.latitude, position.longitude)));

                  setState(() {});
                },
                backgroundColor: secondaryColor,
                label: const Text('Current Location'),
                icon: const Icon(Icons.location_history),
              ),
            )
          ],
        ),
      ),
    );
  }

  Future<Position> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();

    if (!serviceEnabled) {
      return Future.error('Location services are disabled');
    }

    permission = await Geolocator.checkPermission();

    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();

      if (permission == LocationPermission.denied) {
        return Future.error('Location permission denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return Future.error('Location permissions are permanently denied');
    }

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high,
        forceAndroidLocationManager: true);
    print(position.latitude);
    print(position.longitude);
    return position;
  }
}

AndriodManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.final_year_project">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

   <application
        android:label="final_year_project"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
         
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        // Don't delete the meta-data below.
             // This is used by the Flutter tool to generate GeneratedPluginRegistrant.java
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
        <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="MY_API_KEY"/>
    </application>
</manifest>

CodePudding user response:

Are you using emulator or a real device? The emulator uses Google Plex as its default location. To set a different location, you must open the emulator's extended controls by clicking on the ellipsis at the bottom of the sidebar.

  • Related