Фрагмент мини-карты, не показывающий местоположение, взятое из предыдущего действия.JAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Гость
 Фрагмент мини-карты, не показывающий местоположение, взятое из предыдущего действия.

Сообщение Гость »

У меня есть следующие значения, взятые из предыдущего действия, для отображения в следующем коде:
Scenario:
Emergency Type:
Specific location markers, if any

and the location of the selected user off a listview


Изображение

private GoogleMap mMap;
private double latitude;
private double longitude;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 99;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emergency_details);

// Receive data from intent extras
String scenarioData = getIntent().getStringExtra("Scenario");
String emergencyTypeData = getIntent().getStringExtra("Emergency Type");
latitude = getIntent().getDoubleExtra("Latitude", 0.0);
longitude = getIntent().getDoubleExtra("Longitude", 0.0);

// Find TextViews for scenario data and emergency type
TextView tvScenarioData = findViewById(R.id.tvScenario);
TextView tvEmergencyTypeData = findViewById(R.id.tvEmergencyType);

// Set text for scenario data and emergency type TextViews
tvScenarioData.setText(scenarioData);
tvEmergencyTypeData.setText(emergencyTypeData);

// Check and request location permission if needed
checkLocationPermission();

// Initialize SupportMapFragment and handle map customization
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.miniMapFragment);
if (mapFragment != null) {
mapFragment.getMapAsync(this);
} else {
Toast.makeText(this, "Error loading map!", Toast.LENGTH_SHORT).show();
}

Log.d("EmergencyDetails", "Received Latitude: " + latitude);
Log.d("EmergencyDetails", "Received Longitude: " + longitude);
}

private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// Permission already granted
// Proceed with map initialization or other location-dependent tasks
initializeMap();
} else {
// Request location permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
}
}

private void initializeMap() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (mMap != null) {
try {
// Add marker to the map if latitude and longitude are valid
LatLng location = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(location));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 15f));
mMap.setMyLocationEnabled(true);
} catch (SecurityException e) {
Log.e("MapError", "Error enabling location on map: " + e.getMessage());
}
} else {
Toast.makeText(this, "Map is not ready yet", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Location permission not granted", Toast.LENGTH_SHORT).show();
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Location permission granted, initialize the map
initializeMap();
} else {
// Location permission denied, handle accordingly
Toast.makeText(this, "Location permission denied", Toast.LENGTH_SHORT).show();
}
}
}

@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
mMap = googleMap;

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// Permission already granted, initialize the map
initializeMap();
} else {
// Request location permission if not granted
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
}
}
}

Данные о местоположении извлекаются из Firebase посредством предыдущего действия через намерения, однако в текущем действии полученное местоположение не отображается. Обратите внимание, что функция «Карты» для этого проекта настроена правильно, поскольку она уже используется в других действиях, но работает правильно.
Вот логарифм:
09:20:47.949 D Received Latitude: 120.7152931
09:20:47.949 D Received Longitude: 15.4487153

Вот как данные о местоположении извлекаются из предыдущего действия:
DatabaseReference selectedUserLocationRef = FirebaseDatabase.getInstance()
.getReference().child("User Location").child(selectedUid);
selectedUserLocationRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot locationSnapshot) {
if (locationSnapshot.exists()) {
Double latitude = locationSnapshot.child("latitude").getValue(Double.class);
Double longitude = locationSnapshot.child("longitude").getValue(Double.class);
if (latitude != null && longitude != null) {
// Data retrieved successfully, now start the new activity
Intent intent = new Intent(LocationLog.this, EmergencyDetails.class);
intent.putExtra("Emergency Type", model.getEmergencyType());
intent.putExtra("Scenario", model.getScenario());
intent.putExtra("Latitude", latitude);
intent.putExtra("Longitude", longitude);
startActivity(intent);
}
else {
// Handle missing location data
Log.e(TAG, "Latitude or Longitude is null");
}
}
else {
// Handle if the location data for the selected user doesn't exist
Log.e(TAG, "Location data does not exist for UID: " + selectedUid);
}

}


Подробнее здесь: https://stackoverflow.com/questions/784 ... s-activity
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»