Как получить местоположение (местоположение, в котором было снято изображение) выбранного изображения из галереи в Android Studio? - PullRequest
0 голосов
/ 10 мая 2019

Я занимаюсь разработкой приложения, которое выполняет такие операции, как фотографирование с помощью камеры и просмотр сделанных фотографий. Теперь у меня есть кнопка, по нажатию которой она попадает в галерею, где я могу выбрать изображение. После выбора изображения я загружаю изображение в активность, а также местоположение изображения. Но местоположение является одинаковым (текущее местоположение) для любой выбранной фотографии.

Я использую это для получения местоположения. Но независимо от того, какое изображение я выбираю, это мое текущее местоположение.

GPSTRACKER.JAVA

package com.elno.bescomcoe;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import static android.content.ContentValues.TAG;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // Flag for GPS status
    boolean isGPSEnabled = false;

    // Flag for network status
    boolean isNetworkEnabled = false;

    // Flag for GPS status
    boolean canGetLocation = false;

    Location location; // Location
    double latitude; // Latitude
    double longitude; // Longitude

    int geocoderMaxResults = 1;

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context mContext) {
        this.mContext = mContext;
        getLocation();
    }

    @SuppressLint("MissingPermission")
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // Getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            System.out.println("GPS : " + isGPSEnabled);

            // Getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            System.out.println("NETWORK : " + isNetworkEnabled);

            if (isGPSEnabled) {
                this.isGPSEnabled = true;

            }

            if (!isGPSEnabled && !isNetworkEnabled) {
                // No network provider is enabled
                System.out.println("Inside gps and network");
            } else {
                System.out.println("outside gps and network");

                this.canGetLocation = true;
                if (isNetworkEnabled) {



                        //ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);

                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }

                }
            // If GPS enabled, get latitude/longitude using GPS Services
               if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
             }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }


    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app.
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }


    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch Settings Options.
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing the Settings button.
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // On pressing the cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    //Get list of Addresses by latitude and longitude
    //return List<Adresses> - list of addresses or null
    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }

    //Get the Address Line
    //Return address line or null
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    //Get the Locality
    //Return the locality or null
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        }
        else {
            return null;
        }
    }

    /**
     * Try to get Postal Code
     * @return null or postalCode
     */
    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        } else {
            return null;
        }
    }

    /**
     * Try to get CountryName
     * @return null or postalCode
     */
    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        } else {
            return null;
        }
    }



    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

И это моя активность, в которую я загружаю выбранное изображение и местоположение.

package com.elno.bescomcoe;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewGalleryAcitvity extends AppCompatActivity {

    private TextView LocationTextView;
    private ImageView SelectedImageView;

    GPSTracker gps;
    double latitude ;
    double longitude;
    String country;
    String city;
    String postalcode;
    String addressline;

    Uri imageUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_gallery);
        LocationTextView = findViewById(R.id.LoctextView);
        SelectedImageView = findViewById(R.id.selectedimage);
        Bundle bundle = getIntent().getExtras();


        if(bundle != null){

            imageUri = Uri.parse(bundle.getString("picture"));
            SelectedImageView.setImageURI(imageUri);
            gps = new GPSTracker(getApplicationContext());
            if(gps.canGetLocation())
            {
                latitude = gps.getLatitude();
                longitude = gps.getLongitude();
                country = gps.getCountryName(this);
                city = gps.getLocality(this);
                postalcode = gps.getPostalCode(this);
                addressline = gps.getAddressLine(this);

                Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                LocationTextView.setText("Latitude - "+latitude+"\nLongitude - "+longitude);


            } else  {
                // Can't get location.
            }
        }
        else {
           //Bundle is empty
        }
    }
}

Теперь мне нужна помощь о том, как получить местоположение изображения, где оно было снято, а не только мое текущее местоположение.

Ответы [ 2 ]

0 голосов
/ 10 мая 2019
    ExifInterface exif = new ExifInterface(getContentResolver().openInputStream(selectedImage));
float[] latLong = new float[2];
  boolean hasLatLong = exif.getLatLong(latLong)
   if (hasLatLong) {
      System.out.println("Latitude: " + latLong[0]);
      System.out.println("Longitude: " + latLong[1]);
   }

Посмотрите эту ссылку для лучшего понимания.

Кроме того, лучше обратиться к документации здесь.

0 голосов
/ 10 мая 2019

Вы можете получить атрибуты изображения, используя ExifInterface

Пример:

    ExifInterface exif = new ExifInterface(filepath);
    String LATITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
    String LATITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
    String LONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
    String LONGITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);

или

  ExifInterface exif = new ExifInterface(filepath);
  float[] latLong = new float[2];
  boolean hasLatLong = exif.getLatLong(latLong)
   if (hasLatLong) {
      System.out.println("Latitude: " + latLong[0]);
      System.out.println("Longitude: " + latLong[1]);
   }
...