Erased polylines shows on google maps - android

I need a little bit of help. I'm building a GPS tracking app where the app draws polylines of my movement and when I stop the tracking of my movement and click start again the app would erase all of the previously drawed polylines and start drawing newones. Bud everytime I start the polylinedrawing again the app after a while shows the previously drawed lines (even after they been erased).
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
import java.util.List;
public class MapsActivity extends AppCompatActivity implements LocationListener {
private GoogleMap mMap;
Button start,stop;
double OLDlatitude = 100;
double OLDlongitude = 100;
boolean draw = false;
int width = 5;
int color = Color.BLUE;
LocationManager locationManager;
Polyline polyline = null;
PolylineOptions polylineOptions;
List<Polyline> mPolylines = new ArrayList<Polyline>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
start = (Button) findViewById(R.id.start);
stop = (Button) findViewById(R.id.stop);
stop.setEnabled(false);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startK();
}});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopK();
}});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap=mapFragment.getMap();
polylineOptions = new PolylineOptions();
polylineOptions.width(width);
polylineOptions.color(color);
polylineOptions.geodesic(true);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean gps_enabled = false;
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled ) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Aplikácia potrebuje aktívne GPS na fungovanie. Chcete ho zapnúť ?")
.setCancelable(false)
.setPositiveButton("Áno", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("Nie", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
System.exit(0);
}
});
final AlertDialog alert = builder.create();
alert.show();
}
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 2000, 0, this);
Toast.makeText(this, "Na začatie kreslenia polohy kliknite na štart", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng NEWlatLng = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(NEWlatLng)
.zoom(17)
.bearing(0)
.tilt(0)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if(draw)
{
if(OLDlatitude==100 && OLDlongitude==100)
{
OLDlatitude = latitude;
OLDlongitude = longitude;
}
Location loc1 = new Location("");
loc1.setLatitude(OLDlatitude);
loc1.setLongitude(OLDlongitude);
Location loc2 = new Location("");
loc2.setLatitude(latitude);
loc2.setLongitude(longitude);
float distanceInMeters = loc1.distanceTo(loc2);
if(distanceInMeters >= 1.0 )
{
polylineOptions.add(NEWlatLng);
mPolylines.add(this.mMap.addPolyline(polylineOptions));
OLDlatitude = latitude;
OLDlongitude = longitude;
}
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
public void startK() {
Toast.makeText(this, "Kreslenie bolo začaté", Toast.LENGTH_LONG).show();
draw = true;
stop.setEnabled(true);
start.setEnabled(false);
if(mPolylines.size() != 0)
{
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Na mape je nakreslená trasa chcete túto trasu uložiť ?")
.setCancelable(false)
.setPositiveButton("Áno", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
}
})
.setNegativeButton("Nie", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
for(Polyline line : mPolylines)
{
line.remove();
}
mPolylines.clear();
mPolylines = new ArrayList<Polyline>();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
}
public void stopK() {
Toast.makeText(this, "Kreslenie bolo zastavené", Toast.LENGTH_LONG).show();
OLDlongitude = 100;
OLDlatitude = 100;
draw = false;
stop.setEnabled(false);
start.setEnabled(true);
}
#Override
protected void onPause() {
if (this.isFinishing()){
draw = false;
locationManager.removeUpdates(this);
}
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
}

You should clear your map:
mMap.clear();
https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.html#public-methods
public final void clear ()
Removes all markers, polylines, polygons, overlays, etc from the map.

Just figured it by my self instead of
mPolylines = new ArrayList<Polyline>();
I've put there
polylineOptions = new PolylineOptions();
not entirely shore but I think polylineOptions keeps track of all added latlang objects even when they are erased from arrayList. If someone have some more complex explanation I would gratefully apprishiate it.

Related

I am trying to use Geofire to store and display the users that are logged in on a map

I am trying to use Geofire to store and display the users that are logged in on a map i am new in android studio
i am getting this error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.parthtiwari.trace/com.example.parthtiwari.trace.tracking}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Circle com.google.android.gms.maps.GoogleMap.addCircle(com.google.android.gms.maps.model.CircleOptions)' on a null object reference
import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.FragmentActivity;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.GeoQuery;
import com.firebase.geofire.GeoQueryEventListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.*;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Map;
public class tracking extends FragmentActivity implements
GeoQueryEventListener,OnMapReadyCallback,
GoogleMap.OnCameraChangeListener{
private static final GeoLocation INITIAL_CENTER = new GeoLocation(22.7789,
-78.4017);
private static final int INITIAL_ZOOM_LEVEL = 14;
private static final String GEO_FIRE_DB = "https://trace-
5fa8c.firebaseio.com";
private static final String GEO_FIRE_REF = GEO_FIRE_DB + "/_geofire";
private GoogleMap mMap;
private GoogleMap map;
private Circle searchCircle;
private GeoFire geoFire;
private GeoQuery geoQuery;
private Map<String,Marker> markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracking);
// Obtain the SupportMapFragment and get notified when the map is ready
to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude,
INITIAL_CENTER.longitude);
this.searchCircle = this.map.addCircle(new
CircleOptions().center(latLngCenter).radius(1000));
this.searchCircle.setFillColor(Color.argb(66, 255, 0, 255));
this.searchCircle.setStrokeColor(Color.argb(66, 0, 0, 0));
this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter,
INITIAL_ZOOM_LEVEL));
this.map.setOnCameraChangeListener(this);
FirebaseOptions options = new FirebaseOptions.Builder().setApplicationId("geofire").setDatabaseUrl(GEO_FIRE_DB).build();
FirebaseApp app = FirebaseApp.initializeApp(this, options);
// setup GeoFire
this.geoFire = new GeoFire(FirebaseDatabase.getInstance(app).getReferenceFromUrl(GEO_FIRE_REF));
// radius in km
this.geoQuery = this.geoFire.queryAtLocation(INITIAL_CENTER, 1);
// setup markers
this.markers = new HashMap<String, Marker>();
}
#Override
protected void onStop() {
super.onStop();
// remove all event listeners to stop updating in the background
this.geoQuery.removeAllListeners();
for (Marker marker: this.markers.values()) {
marker.remove();
}
this.markers.clear();
}
#Override
protected void onStart() {
super.onStart();
// add an event listener to start updating locations again
this.geoQuery.addGeoQueryEventListener(this);
}
#Override
public void onKeyEntered(String key, GeoLocation location) {
// Add a new marker to the map
Marker marker = this.map.addMarker(new MarkerOptions().position(new
LatLng(location.latitude, location.longitude)));
this.markers.put(key, marker);
}
#Override
public void onKeyExited(String key) {
// Remove any old marker
Marker marker = this.markers.get(key);
if (marker != null) {
marker.remove();
this.markers.remove(key);
}
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
// Move the marker
Marker marker = this.markers.get(key);
if (marker != null) {
this.animateMarkerTo(marker, location.latitude, location.longitude);
}
}
#Override
public void onGeoQueryReady() {
}
#Override
public void onGeoQueryError(DatabaseError error) {
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage("There was an unexpected error querying GeoFire: " +
error.getMessage())
.setPositiveButton(android.R.string.ok, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
// Animation handler for old APIs without animation support
private void animateMarkerTo(final Marker marker, final double lat, final
double lng) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long DURATION_MS = 3000;
final Interpolator interpolator = new
AccelerateDecelerateInterpolator();
final LatLng startPosition = marker.getPosition();
handler.post(new Runnable() {
#Override
public void run() {
float elapsed = SystemClock.uptimeMillis() - start;
float t = elapsed/DURATION_MS;
float v = interpolator.getInterpolation(t);
double currentLat = (lat - startPosition.latitude) * v +
startPosition.latitude;
double currentLng = (lng - startPosition.longitude) * v +
startPosition.longitude;
marker.setPosition(new LatLng(currentLat, currentLng));
// if animation is not finished yet, repeat
if (t < 1) {
handler.postDelayed(this, 16);
}
}
});
}
private double zoomLevelToRadius(double zoomLevel) {
// Approximation to fit circle into view
return 16384000/Math.pow(2, zoomLevel);
}
#Override
public void onCameraChange(CameraPosition cameraPosition) {
LatLng center = cameraPosition.target;
double radius = zoomLevelToRadius(cameraPosition.zoom);
this.searchCircle.setCenter(center);
this.searchCircle.setRadius(radius);
this.geoQuery.setCenter(new GeoLocation(center.latitude,
center.longitude));
// radius in km
this.geoQuery.setRadius(radius/1000);
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
You are requesting the GoogleMap instance asynchronously with this statement:
mapFragment.getMapAsync((OnMapReadyCallback) this);
When the map is available for use, it will be reported to you in this callback:
#Override
public void onMapReady(GoogleMap googleMap) {
}
You need to take all initialization code that uses the map out of your activity's onCreate() method and move it into onMapReady() or methods that are called from onMapReady(). For example:
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
//mMap = googleMap; // not used?
// all the map init stuff
LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude,
INITIAL_CENTER.longitude);
this.searchCircle = this.map.addCircle(new
CircleOptions().center(latLngCenter).radius(1000));
this.searchCircle.setFillColor(Color.argb(66, 255, 0, 255));
this.searchCircle.setStrokeColor(Color.argb(66, 0, 0, 0));
this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter,
INITIAL_ZOOM_LEVEL));
this.map.setOnCameraChangeListener(this);
}
It's not clear why you are creating another app instance. I don't think Geofire needs it. Try using the default:
//FirebaseOptions options = new FirebaseOptions.Builder().setApplicationId("geofire").setDatabaseUrl(GEO_FIRE_DB).build();
//FirebaseApp app = FirebaseApp.initializeApp(this, options);
// setup GeoFire
this.geoFire = new GeoFire(FirebaseDatabase.getInstance().getReferenceFromUrl(GEO_FIRE_REF));

Android GPS service returns 0.0 every time

I've been searching around for days but can't find what the problem can be. I want to know my current position when I'm clicking button A, and also know my position when I'm clicking button B. Problem is this, when I click B it seems to work fine, but not in A. I use the exact same code on both of them, but in some way it just wont work for A.
Here is my GetGPSLocation code
`
package com.example.eandl.gps;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class GetGPSLocation {
private Context context;
private static double lat;
private static double lang;
public GetGPSLocation(Context context){
this.context = context;
this.lat = 0.0;
this.lang = 0.0;
}
public void setLat(double lat) {
this.lat = lat;
}
public void setLang(double lang) {
this.lang = lang;
}
public Boolean displayGpsStatus() {
final LocationManager manager = (LocationManager) context.getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) ) {
return false;
}else{
return true;
}
}
public double[] getLatLong(){
double[] latLong = new double[2];
if(displayGpsStatus()){
LocationManager locationMangaer = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener(context, this);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, 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.
ActivityCompat.requestPermissions((Activity)context,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
if(checkLocationPermission()){
locationMangaer.requestLocationUpdates(LocationManager
.NETWORK_PROVIDER, 0, 0, locationListener);
}
Log.d("findError", getLang() + "");
latLong[0] = getLat();
latLong[1] = getLang();
}else{
alertbox("Gps status", "Your Device's GPS is Disable");
}
return latLong;
}
public boolean checkLocationPermission()
{
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = context.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(mymessage)
.setCancelable(false)
.setTitle(title)
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
`
And the Listiener
package com.example.eandl.gps;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MyLocationListener implements LocationListener {
private Context context;
private GetGPSLocation getGPSLocation;
public MyLocationListener(Context context, GetGPSLocation getGPSLocation) {
this.context = context;
this.getGPSLocation = getGPSLocation;
}
#Override
public void onLocationChanged(Location loc) {
if(loc != null){
getGPSLocation.setLat(loc.getLatitude());
getGPSLocation.setLang(loc.getLongitude());
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
The way I'm trying to call it is by new GetGPSLocation(context).getLatLong but as I said, sometimes it returns my position and sometimes 0.0
Thank you!
Alright so first I'm setting it up when I create my view like this
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
//Fixa vit med blå text
myView = inflater.inflate(R.layout.fragment_signup, container, false);
placements = new ArrayList<CheckBox>();
GetPlacements getPlacements = new GetPlacements(this);
getPlacements.execute();
getGPSLocation = new GetGPSLocation(myView.getContext());
getGPSLocation.getLatLong();
Then this is the onclicklistener on the button A
getGPSLocation.getLatLong();
DatabasSender databasSender = new DatabasSender(myView.getContext());
User user = new User(name.getText().toString(), email.getText().toString(), 0);
user.setSignup(true);
user.setEdu(edu.getText().toString());
user.setPhone(phone.getText().toString());
user.setPlacements(places);
databasSender.execute(user);
That goes to my databassender that uses a AsyncTask
public DatabasSender(Context context) {
this.context = context;
getGPSLocation = new GetGPSLocation(context);
}
#Override
protected void onPreExecute() {
latLong = getGPSLocation.getLatLong();
}
#Override
protected Object doInBackground(Object[] objects) {
urlPatten = "..../"+latLong[0]+"&"+latLong[1];
}
And I use the exact same code for Button B.

Lat and Lng always return 0.0,0.0

hi im going through this tutorial and i faced a annoying problem that latitude and longitude always return 0.0 .im using api 16 on nexus 4.
GPSTracker.java
package ir.ketabe_zard.www.maps;
import android.Manifest;
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.Criteria;
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.util.Log;
/**
* Created by Pedram Hassas on 11/24/2016.
*/
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;
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;
// First get location from Network Provider
if (isNetworkEnabled) {
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.
}
Criteria locationCritera = new Criteria();
String providerName = locationManager.getBestProvider(locationCritera,
true);
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(providerName);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long 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;
}
/**
* 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 if best network provider
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* */
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?");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.delete);
// On pressing 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 cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public void stopUsingGPS() {
if (locationManager != null) {
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;
}
locationManager.removeUpdates(GPSTracker.this);
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location loc) {
if(location!=null){
location=loc;
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}<br>
MapsActivity.java
package ir.ketabe_zard.www.maps;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
View.OnClickListener {
Location location;
TextView txtLatLng;
protected LocationManager locationManager;
Double Lat, Lng;
LocationListener locationListener = new LocationListener() {
#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) {
}
};
#Override
public void onMapLongClick(LatLng latLng) {
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
#Override
protected void onStart() {
txtLatLng = (TextView) findViewById(R.id.txtLatLng);
super.onStart();
}
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void btnLocation_clicked(View view) {
GPSTracker gps = new GPSTracker(this);
if(gps.canGetLocation()){
Lat=gps.getLatitude();
Lng=gps.getLongitude();
txtLatLng.setText(String.valueOf(Lat)+","+String.valueOf(Lng));
}else {
gps.showSettingsAlert();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
final TextView LatLng;
// Add a marker in Sydney and move the camera
LatLng Tehran = new LatLng(35.689197, 51.388974);
mMap.addMarker(new MarkerOptions().position(Tehran).title("Marker in Tehran").draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Tehran, 12));
}
#Override
public void onClick(View v) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#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) {
}
}<br>
i have a button when user taped it . show lat and lng in a textview in x.x,x.x format.

How to toggle Action Bar while touching the map like Uber

I have implemented a map that behaves like Uber app i.e pin in center and map drags under the pin and the pin gets the location from map. But I am not able to implement the touch event for toggling the action bar just exactly Uber do. Please help me to implement that feature. First I have used support map fragment but to set touch events a view was required so later on I used MapView.Below is my code:
package com.example.myfastapp;
import java.util.List;
import java.util.Locale;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentSender.SendIntentException;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class mapFragment extends Fragment implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
MapView mapView;
//private View touch;
private GoogleMap map;
private LatLng center;
private LatLng currentpoint;
private Geocoder geocoder;
private List<Address> addresses;
double latitude;
double longitude;
protected Context context;
SupportMapFragment mf;
View v;
private static final CharSequence[] MAP_TYPE_ITEMS = { "Road Map",
"Satellite", "Terrain" };
// A request to connect to Location Services
private LocationRequest mLocationRequest;
private TextView markerText, Address;
private LinearLayout markerLayout;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private GPSTracker gps;
// Milliseconds per second
public static final int MILLISECONDS_PER_SECOND = 1000;
// The update interval
public static final int UPDATE_INTERVAL_IN_SECONDS = 5;
// A fast interval ceiling
public static final int FAST_CEILING_IN_SECONDS = 1;
// Update interval in milliseconds
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* UPDATE_INTERVAL_IN_SECONDS;
// A fast ceiling of update intervals, used when the app is visible
public static final long FAST_INTERVAL_CEILING_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* FAST_CEILING_IN_SECONDS;
public mapFragment(Context context) {
super();
this.context = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.mapfragment, container, false);
// v.setOnDragListener(new MyDragListener());
mapView = (MapView)v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
ImageButton mapType = (ImageButton) v.findViewById(R.id.mapType);
mapType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMapTypeSelectorDialog();
}
});
ImageButton myLocationCustomButton = (ImageButton)v.findViewById(R.id.myLocationCustom);
myLocationCustomButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
gps = new GPSTracker(getActivity());
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
currentpoint = new LatLng(latitude, longitude);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(currentpoint, 18);
map.animateCamera(cameraUpdate);
map.setMyLocationEnabled(true);
}
});
markerText = (TextView) v.findViewById(R.id.locationMarkertext);
Address = (TextView) v.findViewById(R.id.adressText);
markerLayout = (LinearLayout) v.findViewById(R.id.locationMarker);
// Getting Google Play availability status
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
getActivity(), requestCode);
dialog.show();
} else {
// Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
return v;
}
public void toggleActionBar()
{
ActionBar ab = getActivity().getActionBar();
if (ab != null)
{
if (ab.isShowing())
{
ab.hide();
}
else
{
if(!ab.isShowing())
{
ab.show();
}
}
}
}
private void setupMap() {
try {
/*map = ((SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map)).getMap();*/
map = mapView.getMap();
// Enabling MyLocation in Google Map
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.getUiSettings().setCompassEnabled(false);
map.getUiSettings().setRotateGesturesEnabled(true);
map.getUiSettings().setZoomGesturesEnabled(true);
try {
MapsInitializer.initialize(this.getActivity());
} catch (Exception e) {
e.printStackTrace();
}
PendingResult<Status> result = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient, mLocationRequest,
new LocationListener() {
#Override
public void onLocationChanged(Location location) {
markerText.setText("Location received: "
+ location.toString());
}
});
Log.e("Reached", "here");
result.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.e("Result", "success");
} else if (status.hasResolution()) {
// Google provides a way to fix the issue
try {
status.startResolutionForResult(getActivity(), 100);
} catch (SendIntentException e) {
e.printStackTrace();
}
}
}
});
gps = new GPSTracker(getActivity());
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
currentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(currentpoint).zoom(16f).tilt(30).bearing(90).build();
map.setMyLocationEnabled(true);
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
map.clear();
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
//toggleActionBar();
center = map.getCameraPosition().target;
markerText.setText(" Set your Location ");
map.clear();
markerLayout.setVisibility(View.VISIBLE);
try
{
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
markerLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
LatLng latLng1 = new LatLng(center.latitude,
center.longitude);
Marker m = map.addMarker(new MarkerOptions()
.position(latLng1)
.title(" Set your Location ")
.snippet("")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.my_location)));
m.setDraggable(true);
markerLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
setupMap();
}
#Override
public void onConnectionSuspended(int cause) {
}
#Override
public void onLocationChanged(Location location) {
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected void onPreExecute() {
Address.setText(" Getting location ");
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(context, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + " ");
str.append(city + " " + region_code + " ");
str.append(zipcode + " ");
}
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0) + ", "
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
/*
* public void addMarker(double lati, double longi) {
*
* LatLng latlng = new LatLng(lati, longi);
*
* MarkerOptions mo = new MarkerOptions(); mo.position(latlng);
* mo.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_location));
* mo.title("My Location:"+ latlng); map.addMarker(mo);
*
* //map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng,
* 15));//previous code CameraPosition cameraPosition = new
* CameraPosition.Builder() .target(latlng) .zoom(11.0f) .bearing(90) //
* Orientation of the camera to east .tilt(30) // Tilt of the camera to 30
* degrees .build();
* map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
* map.setMyLocationEnabled(true);
* map.getUiSettings().setCompassEnabled(true);
* map.getUiSettings().setZoomControlsEnabled(true);
* //map.setMapType(GoogleMap.MAP_TYPE_NORMAL); }
*/
public void showMapTypeSelectorDialog() {
// Prepare the dialog by setting up a Builder.
final String fDialogTitle = "Select Map Type";
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(fDialogTitle);
// Find the current map type to pre-check the item representing the
// current state.
int checkItem = map.getMapType() - 1;
System.out.print(checkItem);
// Add an OnClickListener to the dialog, so that the selection will be
// handled.
builder.setSingleChoiceItems(MAP_TYPE_ITEMS, checkItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
// Locally create a finalised object.
// Perform an action depending on which item was
// selected.
switch (item)
{
case 1:
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 2:
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
default:
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
dialog.dismiss();
}
});
// Build the dialog and show it.
AlertDialog fMapTypeDialog = builder.create();
fMapTypeDialog.setCanceledOnTouchOutside(true);
fMapTypeDialog.show();
}
#Override
public void onResume()
{
super.onResume();
mapView.onResume();
mapView.getMap();
}
#Override
public void onPause()
{
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory()
{
super.onLowMemory();
mapView.onLowMemory();
}
}
The onCameraChangeListener is deprecated, but good news is that google has released 3 new listeners.
See: GoogleMap.OnCameraChangeListener
This interface was deprecated.
Replaced by GoogleMap.OnCameraMoveStartedListener, GoogleMap.OnCameraMoveListener and GoogleMap.OnCameraIdleListener. The order in which the deprecated onCameraChange method will be called in relation to the methods in the new camera change listeners is undefined.
I have used these listeners and now i am able get the hold and release event on map.
I believe you should add an onMarkerDragListener to your map object and do your code inside.
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
});
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"/>
<ImageButton
android:id="#+id/fabButton"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_gravity="bottom|right"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:background="#drawable/fab_bcg"
android:src="#drawable/ic_favorite_outline_white_24dp"
android:contentDescription="Desc"/>
This is methods for show and hide views
private void hideViews() {
mToolbar.animate().translationY(-mToolbar.getHeight()).setInterpolator(new AccelerateInterpolator(2));
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mFabButton.getLayoutParams();
int fabBottomMargin = lp.bottomMargin;
mFabButton.animate().translationY(mFabButton.getHeight()+fabBottomMargin).setInterpolator(new AccelerateInterpolator(2)).start();
}
private void showViews() {
mToolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
mFabButton.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
}

how to get current location through gps using android

I am trying to create an android program to get the location
but unfortunately its throwing the exception as unfortunately APP is stopped
Can you suggest me please .code is the following
package com.example.ngo;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
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.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to"+
" see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----Method to Check GPS is enable or disable ----- */
#SuppressLint("NewApi") private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}

Categories

Resources