I need help. I have already set up Google Console in the right way, the right API and the right package name and SHA-1 for restricting usage in Android apps and I can see the green checkmark. In other words it worked before, but now the map in Google Map gone, just showing logo, my button and still can detect my LatLong.
My other problem is my Google Map can’t show LatLong, my location button, and can’t use mark if I turn off GPS. I need to turn ON the GPS outside of the activity. Even I make refresh button but still I need to turn on GPS outside of activity (like before get inside the map activity).
Here is my MapActivity:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private FloatingActionButton fabDone, fabRefresh;
private Location currentLocation;
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Double MyLat, MyLong;
private String kode;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
Marker incidentMarker;
Geocoder geo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
Intent intent = getIntent();
kode = intent.getStringExtra("kode");
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Map");
fabDone = findViewById(R.id.fab_done);
fabRefresh = findViewById(R.id.fab_refresh);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
geo = new Geocoder(getApplicationContext(), Locale.getDefault());
turnGPSOn();
fetchLocation();
fabRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
}
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
mMap = googleMap;
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
try {
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
currentLocation = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(network_enabled && currentLocation==null){
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
currentLocation = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (currentLocation != null) {
MyLat = currentLocation.getLatitude();
MyLong = currentLocation.getLongitude();
mMap.setMyLocationEnabled(true);
LatLng latLng = new LatLng(MyLat, MyLong);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} else {
Location loc= getLastKnownLocation(this);
if (loc != null) {
MyLat = loc.getLatitude();
MyLong = loc.getLongitude();
mMap.setMyLocationEnabled(true);
LatLng latLng = new LatLng(MyLat, MyLong);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
}
}
locManager.removeUpdates(locListener);
try {
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng latLng) {
if (incidentMarker != null)
incidentMarker.remove();
MarkerOptions options = new MarkerOptions().position(latLng).title("Incident Location");
try {
Address address = geo.getFromLocation(latLng.latitude, latLng.longitude, 2).get(0);
String addressLine = address.getAddressLine(0); // If any additional
String snippets = addressLine;
Log.d("MAP", snippets);
options.snippet(snippets);
} catch (IOException e) {
e.printStackTrace();
}
incidentMarker = mMap.addMarker(options);
incidentMarker.showInfoWindow();
}
});
fabDone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (incidentMarker == null) {
Toast.makeText(getApplicationContext(), "Points the incident location using Long Click!", Toast.LENGTH_SHORT).show();
return;
} else {
if (kode.equals("1")) {
Intent intent = new Intent(MapActivity.this, AddReportActivity.class);
intent.putExtra("address", incidentMarker.getSnippet());
intent.putExtra("latitude", incidentMarker.getPosition().latitude);
intent.putExtra("longitude", incidentMarker.getPosition().longitude);
startActivity(intent);
finish();//finishing activity
} else if (kode.equals("2")) {
Intent intent = new Intent(MapActivity.this, EditReportActivity.class);
intent.putExtra("address", incidentMarker.getSnippet());
intent.putExtra("latitude", incidentMarker.getPosition().latitude);
intent.putExtra("longitude", incidentMarker.getPosition().longitude);
startActivity(intent);
finish();//finishing activity
}
}
}
});
} catch (Exception e){e.printStackTrace();}
if (gps_enabled && network_enabled && currentLocation!=null){
MyLat = currentLocation.getLatitude();
MyLong = currentLocation.getLongitude();
mMap.setMyLocationEnabled(true);
LatLng latLng = new LatLng(MyLat, MyLong);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} else if (gps_enabled && network_enabled && currentLocation==null){
Toast.makeText(this, "Location can't be found.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Please turn ON the GPS.", Toast.LENGTH_SHORT).show();
}
}
private void fetchLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
Toast.makeText(getApplicationContext(), currentLocation.getLatitude() + "" + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fama_map);
assert supportMapFragment != null;
supportMapFragment.getMapAsync(MapActivity.this);
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
fetchLocation();
}
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.map_options, menu);
return true;
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null) {
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
public static Location getLastKnownLocation(Context context) {
Location location = null;
@SuppressLint("WrongConstant") LocationManager locationmanager = (LocationManager)context.getSystemService("location");
List list = locationmanager.getAllProviders();
boolean i = false;
Iterator iterator = list.iterator();
do
{
//System.out.println("---------------------------------------------------------------------");
if(!iterator.hasNext())
break;
String s = (String)iterator.next();
if(i != false && !locationmanager.isProviderEnabled(s))
continue;
@SuppressLint("MissingPermission") Location location1 = locationmanager.getLastKnownLocation(s);
if(location1 == null)
continue;
if(location != null)
{
float f = location.getAccuracy();
float f1 = location1.getAccuracy();
if(f >= f1)
{
long l = location1.getTime();
long l1 = location.getTime();
if(l - l1 <= 600000L)
continue;
}
}
location = location1;
i = locationmanager.isProviderEnabled(s);
// System.out.println("---------------------------------------------------------------------");
} while(true);
return location;
}
public void turnGPSOn(){
try
{
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
catch (Exception e) {
}
}
// Method to turn off the GPS
public void turnGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
// turning off the GPS if its in on state. to avoid the battery drain.
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
turnGPSOff();
}
}
2
Answers
I Think this will help you. First see the package name is same you register on console
build.gradle
AndroidManifest.xml
Kotlin MapsActivity.kt
activity_maps.xml
I Think this will help you. First see the package name is same you register on console
build.gradle
AndroidManifest.xml
Java MapsActivity.java
activity_maps.xml