【发布时间】:2021-11-28 02:02:03
【问题描述】:
我需要帮助。我已经以正确的方式设置了 Google 控制台、正确的 API 和正确的包名称以及 SHA-1 以限制 Android 应用程序的使用,我可以看到绿色的复选标记。换句话说,它以前可以工作,但现在 Google Map 中的地图消失了,只显示徽标,我的按钮,仍然可以检测到我的 LatLong。
我的另一个问题是我的 Google 地图无法显示 LatLong、我的位置按钮,并且如果我关闭 GPS,则无法使用标记。我需要在活动之外打开 GPS。即使我制作了刷新按钮,但我仍然需要在活动之外打开 GPS(就像在进入地图活动之前一样)。
这是我的 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();
}
}
【问题讨论】:
标签: android android-studio google-maps latitude-longitude android-gps