Android:How to Capture a Image of Gps Location

Android : how to capture a image of GPS location

I have solved this problem. I was having problem with image capturing of GPS location. I have just created the capture menu, In which after uploading the GPS location one can capture the image by clicking on capture menu button.

Here is the whole code for capturing the screenshot of GPS location & how to find GPS location.

public class TestGPSActivity extends MapActivity 
{
MapView mapView;
private MapController mc;
private GeoPoint p;
private double lng;
private double lat;
private Address address;

//google Map
class MapOverlay extends com.google.android.maps.Overlay
{
@Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);

//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);

//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.pin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
}
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());

Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);

String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}

Toast.makeText(getBaseContext(), add, Toast.LENGTH_LONG).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.gps_main);

mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();

zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);

mc = mapView.getController();

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {

addresses = geocoder.getFromLocationName(getIntent().getStringExtra("address"), 1);

} catch (IOException e) {
e.printStackTrace();
}

try{
address = addresses.get(0);
}
catch (Exception e) {
flash("Unable to locate given address");
startActivity(new Intent(this, GPSMainActivity.class));
finish();
}
try{
//stores the Longitude n lattitude in log file
lng = address.getLongitude();
lat = address.getLatitude();

//for writing into log.text
HomeActivity.writeLog(getIntent().getStringExtra("address") +" GPS co-ordibnates : "+lat+" , "+lng);

}catch (Exception e) {
e.printStackTrace();
}
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));

mc.animateTo(p);
mc.setZoom(17);

//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);

mapView.invalidate();

//mapView.invalidate();
}

//ScreenShot of Image
private void screenshot() {
try{
String mapDIR = HomeActivity.DIRECTORY+"/Image";

File f = new File(mapDIR);

if(! f.exists())
{
f.mkdir();
}

MapView v1 = (MapView)findViewById(R.id.mapView);
v1.setDrawingCacheEnabled(true);

Bitmap b = Bitmap.createBitmap(v1.getDrawingCache());

try
{
FileOutputStream fos = new FileOutputStream(mapDIR+"/"+System.currentTimeMillis()+".png");
b.compress(CompressFormat.PNG, 50, fos);
fos.close();

} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(), e.getMessage(),Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.getMessage(),Toast.LENGTH_LONG).show();
e.printStackTrace();
}
v1.setDrawingCacheEnabled(false); // clear drawing cache
}catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),Toast.LENGTH_LONG).show();
e.printStackTrace();
}

}

private void flash(String data) {
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
}

@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}

public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
startActivity(new Intent(this, GPSMainActivity.class));
finish();
}
return super.onKeyDown(keyCode, event);
}
//menu button
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
super.onCreateOptionsMenu(menu);

menu.add(0, 1, 0 , "Exit");
menu.add(0, 2, 0 , "Capture Image");

return true;
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
switch(item.getItemId())
{
case 1:
startActivity(new Intent(this, GPSMainActivity.class));
finish();
break;
case 2:
screenshot();
Toast.makeText(getApplicationContext(), "Captured Map", Toast.LENGTH_SHORT).show();
break;
}
return super.onMenuItemSelected(featureId, item);
}
}

Thanks for All.. Hope this will help some one..

Android: how to get an image of a location with latitude and longitude

You can use "google static map" to get an image with location by coordinates.

You can load the generated image by creating a URL request, for example:

String url = "http://maps.google.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=15&size=300x300&sensor=false&key=YOUR_API_KEY"

Furthermore, you can dive into the documentation of static maps.
https://developers.google.com/maps/documentation/maps-static/overview

How to find location from where image is captured?

You can not fetch GPS in emulator.But there is a work around for that

telnet localhost 5554

Connect to your emulator.Like shown above and then

geo fix -23.234334 32.234344 4392

First two are longitude and latitude values and the last one is altitude in meters.

Now from there you can call from GeoCoder
http://developer.android.com/reference/android/location/Geocoder.html

 public List<Address> getFromLocation (double latitude, double longitude, int maxResults)

It will return a list of Address that has a method getLocality

Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0)
Log.i("address",""+addresses.get(0).getLocality());

Try with various values and check!

GPS tagged captured images in android

you can't set it to the Bitmap, the Bitmap is just a byte array with the image pixels.
You have to apply those coordinates after you save it to a file that supports Metadata (for example PNG or JPG)

To do that you use the ExifInterface

Code is similar to that:

String filePath = Enviroment.getExternalStorageDirectory() + "/MyApp/photo.png";
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
photo.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
ExifInterface exif = new ExifInterface(filePath);

// call this next setAttributes a few times to write all the GPS data to it.
exif.setAttribute(... );

// don't forget to save
exif.saveAttributes();

How to fetch the location(Location at which image was taken) of selected image from gallery in Android Studio?

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

Have a look at this link for better understanding.

Also, it's better to refer the documentation here.

Getting location data for a taken photo in Android

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

// 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 context) {
this.mContext = context;
getLocation();
}

public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);

// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);

// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
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();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

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

}

when u take the picture in ActivityforResult() use this code to get the location
like this

  GPSTracker gps;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
gps = new GPSTracker(AndroidGPSTrackingActivity.this);

if (resultCode == RESULT_OK)
{
previewCapturedImage();
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();

// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
// Can't get location.
// GPS or network is not enabled.
// Ask user to enable GPS/network in settings.

}

} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"Cancelled", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Error!", Toast.LENGTH_SHORT)
.show();
}
}

}

How to get the latitude and longitude of an image in sdcard to my application?

You Should Go with ExifInterface class to read various EXIF metadata from Images:

Example :

ExifInterface exif = new ExifInterface(filepath);
exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);

Edited :

Now Here you will get lat-long as Below format.

lat = 30/1,12/1,34/1,
long=81/1,22/1,41/1

To Convert this into Real Values this Blog Helped Me.

we need to do conversion from degree, minute, second form to GeoPoint form.

By Below Way you can Do it.

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

// your Final lat Long Values
Float Latitude, Longitude;

if((LATITUDE !=null)
&& (LATITUDE_REF !=null)
&& (LONGITUDE != null)
&& (LONGITUDE_REF !=null))
{

if(LATITUDE_REF.equals("N")){
Latitude = convertToDegree(LATITUDE);
}
else{
Latitude = 0 - convertToDegree(LATITUDE);
}

if(LONGITUDE_REF.equals("E")){
Longitude = convertToDegree(LONGITUDE);
}
else{
Longitude = 0 - convertToDegree(LONGITUDE);
}

}

private Float convertToDegree(String stringDMS){
Float result = null;
String[] DMS = stringDMS.split(",", 3);

String[] stringD = DMS[0].split("/", 2);
Double D0 = new Double(stringD[0]);
Double D1 = new Double(stringD[1]);
Double FloatD = D0/D1;

String[] stringM = DMS[1].split("/", 2);
Double M0 = new Double(stringM[0]);
Double M1 = new Double(stringM[1]);
Double FloatM = M0/M1;

String[] stringS = DMS[2].split("/", 2);
Double S0 = new Double(stringS[0]);
Double S1 = new Double(stringS[1]);
Double FloatS = S0/S1;

result = new Float(FloatD + (FloatM/60) + (FloatS/3600));

return result;

};

@Override
public String toString() {
// TODO Auto-generated method stub
return (String.valueOf(Latitude)
+ ", "
+ String.valueOf(Longitude));
}

public int getLatitudeE6(){
return (int)(Latitude*1000000);
}

public int getLongitudeE6(){
return (int)(Longitude*1000000);
}


Related Topics



Leave a reply



Submit