小地图片段未显示先前活动的位置

问题描述 投票:0回答:1

我从之前的活动中获取了以下值,并在下面的代码中显示:

Scenario:
Emergency Type:
Specific location markers, if any

and the location of the selected user off a listview

enter image description here

 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);
        }
    }
}

位置数据是通过 Intents 通过先前的 Activity 从 Firebase 检索的,但是,在当前 Activity 上时,它不会显示检索到的位置。请注意,该项目的地图功能已正确设置,因为它已在其他活动中使用,但工作正常。

这是日志猫:

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);
                                        }

                                    }
java android firebase
1个回答
0
投票

如评论中所述,我已经仔细检查了位置如何发送到 Firebase,并且可以看到纬度和经度的值正在翻转:

之前的代码:

private void saveLocationToFirebase(double latitude, double longitude) {
    // Clear existing markers
    mMap.clear();
    // Add marker for the user's current location
    LatLng currentLocation = new LatLng(latitude, longitude); // Latitude and longitude swapped here
    mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15f));
    // Save location data to Firebase
    LocationSend locationSend = new LocationSend(latitude, longitude);
    reference.setValue(locationSend);
    Toast.makeText(this, "Location sent!", Toast.LENGTH_SHORT).show();
}

更新代码:

private void saveLocationToFirebase(double latitude, double longitude) {
    // Clear existing markers
    mMap.clear();
    // Add marker for the user's current location
    LatLng currentLocation = new LatLng(longitude, latitude); // Correct order: longitude, latitude
    mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15f));
    // Save location data to Firebase
    LocationSend locationSend = new LocationSend(latitude, longitude); // Correct order: latitude, longitude
    reference.setValue(locationSend);
    Toast.makeText(this, "Location sent!", Toast.LENGTH_SHORT).show();
}

我还更新了读取/写入位置值的整体代码。

© www.soinside.com 2019 - 2024. All rights reserved.