I've looked high and low for an answer on this, and no one, in any forum question has been able to help. I've searched through the tutorials. The API Guide says:
The My Location button appears in the top right corner of the screen only when the My Location layer is enabled.
So I've been looking for this My Location layer and have been unable to find anything. How do I show my location on a Google Map?
This question is related to
android
geolocation
google-maps-android-api-2
From android 6.0 you need to check for user permission, if you want to use GoogleMap.setMyLocationEnabled(true)
you will get Call requires permission which may be rejected by user
error
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}
if you want to read more, check google map docs
Java code:
public class MapActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
LatLng myPosition;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(myPosition).title("Start"));
}
}
}
activity_map.xml:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
You will get your current location in a blue circle.
Call GoogleMap.setMyLocationEnabled(true)
in your Activity
, and add this 2 lines code in the Manifest
:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
To show the "My Location" button you have to call
map.getUiSettings().setMyLocationButtonEnabled(true);
on your GoogleMap object.
Before enabling the My Location layer, you must request location permission from the user. This sample does not include a request for location permission.
To simplify, in terms of lines of code, the request for the location permit can be made using the library EasyPermissions.
Then following the example of the official documentation of The My Location Layer my code works as follows for all versions of Android that contain Google services.
OnMyLocationClickListener
y OnMyLocationButtonClickListener
.implementation 'pub.devrel:easypermissions:2.0.1'
Forward results to EasyPermissions within method onRequestPermissionsResult()
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
Request permission and operate according to the user's response with requestLocationPermission()
requestLocationPermission()
and set the listeners to onMapReady()
.public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleMap.OnMyLocationClickListener,
GoogleMap.OnMyLocationButtonClickListener {
private final int REQUEST_LOCATION_PERMISSION = 1;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
requestLocationPermission();
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@SuppressLint("MissingPermission")
@AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
public void requestLocationPermission() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if(EasyPermissions.hasPermissions(this, perms)) {
mMap.setMyLocationEnabled(true);
Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
}
else {
EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
}
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
return false;
}
@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
}
}
Source: Stackoverflow.com