I want to get user coordinate, the gps is on , I've asked for permission it has the permissions.
the location is set , I've my locations on other apps like google map but in my application , it doesn't work :
public boolean startService() {
try {
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
return false;
}
}
LocationManager mlocManager = null;
LocationListener mlocListener;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
startService();
}
public class FetchCordinates extends AsyncTask<String, Integer, String> {
AlertDialog.Builder a;
AlertDialog dialog;
public double lati = 0.0;
public double longi = 0.0;
public LocationManager mLocationManager;
public FetchCordinates.VeggsterLocationListener mVeggsterLocationListener;
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new FetchCordinates.VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
a = new AlertDialog.Builder(Admins.this);
a.setMessage("در حال به دست آوردن موقعیت جغرافیایی...");
a.setPositiveButton(("بیخیال"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
FetchCordinates.this.cancel(true);
}
});
dialog = a.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.RIGHT);
messageText.setTypeface(typeface);
}
#Override
protected void onCancelled() {
System.out.println("Cancelled by user!");
dialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
Log.v("this","got the location");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0 && !isCancelled()) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) location.getLatitude(); // * 1E6);
int log = (int) location.getLongitude(); // * 1E6);
int acc = (int) (location.getAccuracy());
String info = location.getProvider();
try {
// LocatorService.myLatitude=location.getLatitude();
// LocatorService.myLongitude=location.getLongitude();
lati = location.getLatitude();
longi = location.getLongitude();
} catch (Exception e) {
// progDailog.dismiss();
// Toast.makeText(getApplicationContext(),"Unable to get Location"
// , Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.i("onStatusChanged", "onStatusChanged");
}
}
}
it shows me the dialog for getting the location but it never get the current location .
What's wrong with my code ?
Please provide what you wrote in your Manifest.xml file. Maybe there is something wrong with the permissions.
You need
android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION
for API 5.0 or higher also:
android.hardware.location.gps
Related
I've a very strange problem with using google map in my application , I've build an application , it shows the map in my phone and it has not problem but it doesn't show in another phone , it has a white screen like this :
and then it shows this:
on the same phone, in another app it shows map with no problem .
could you help me ?
this is my code :
public class Maps extends AppCompatActivity {
FetchCordinates fetchCordinates;
Intent locatorService = null;
MapView mMapView;
private GoogleMap googleMap;
Double lat = 0.0, lon = 0.0;
Typeface typeface;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
typeface = Func.getTypeFace(this);
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
mapBuilder();
try {
Bundle bl = getIntent().getExtras();
if (bl != null) {
lat =(bl.getDouble("lat"));
lon = (bl.getDouble("lon"));
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
mMapView.setVisibility(View.VISIBLE);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(sydney).title(""));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 17));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
}
} catch (Exception e) {
}
}
private void mapBuilder() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& checkSelfPermission(
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Maps.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
doGPS();
}
} catch (Exception e) {
MyToast.makeText(Maps.this, e.getMessage());
e.printStackTrace();
}
Button mapbutton=(Button)findViewById(R.id.mapbutton);
mapbutton.setTypeface(typeface);
mapbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences("settings", MODE_PRIVATE);
SharedPreferences.Editor pref= settings.edit();
pref.putString("lat", lat+"");
pref.putString("lon", lon+"");
pref.commit();
onBackPressed();
}
});
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mapBuilder();
} else {
MyToast.makeText(Maps.this, "دسترسی به جی پی اس غیرفعال است");
}
return;
}
}
}
public boolean stopService() {
if (this.locatorService != null) {
this.locatorService = null;
}
return true;
}
public boolean startService() {
try {
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
return false;
}
}
public AlertDialog CreateAlert(String title, String message) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle(title);
alert.setMessage(message);
return alert;
}
public class FetchCordinates extends AsyncTask<String, Integer, String> {
AlertDialog.Builder a;
AlertDialog dialog;
public double lati = 0.0;
public double longi = 0.0;
public LocationManager mLocationManager;
public VeggsterLocationListener mVeggsterLocationListener;
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
}
#Override
protected void onCancelled() {
System.out.println("Cancelled by user!");
dialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
try {
if(dialog!=null)
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
lat = lati;
lon = longi;
MyToast.makeText(Maps.this, "موقعیت شما با موفقیت ثبت شد");
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
mMapView.setVisibility(View.VISIBLE);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(sydney).title(""));
googleMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 22));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) location.getLatitude(); // * 1E6);
int log = (int) location.getLongitude(); // * 1E6);
int acc = (int) (location.getAccuracy());
String info = location.getProvider();
try {
// LocatorService.myLatitude=location.getLatitude();
// LocatorService.myLongitude=location.getLongitude();
lati = location.getLatitude();
longi = location.getLongitude();
} catch (Exception e) {
// progDailog.dismiss();
// Toast.makeText(getApplicationContext(),"Unable to get Location"
// , Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.i("onStatusChanged", "onStatusChanged");
}
}
}
private void doGPS() {
try {
LocationManager mlocManager = null;
LocationListener mlocListener;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
startService();
} else {
android.support.v7.app.AlertDialog.Builder a = new android.support.v7.app.AlertDialog.Builder(Maps.this);
a.setMessage(("جی پی اس خاموش است. آیا میخواهید روشن کنید؟"));
a.setPositiveButton(("بله"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
});
a.setNegativeButton(("خیر"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
android.support.v7.app.AlertDialog dialog = a.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.RIGHT);
messageText.setTypeface(typeface);
}
} catch (Exception e) {
MyToast.makeText(Maps.this, e.getMessage());
}
}
#Override
protected void onStart() {
super.onStart();
if (mMapView != null && mMapView.getVisibility() == View.VISIBLE)
mapBuilder();
}
could you help me ?
I am using this code for fetching current location, this code is working fine but now need to put
this code on Asynctask class , I don't have any idea how can implement this code on Asynctask
Please help me How can do this
public class GetLoc implements LocationListener{
SharedPreferences preferences = null;
SharedPreferences.Editor editor = null;
Context context;
LocationManager locationManager ;
String provider;
double lati;
double logi;
ProgressDialog pd;
public static String state;
String zz;
public GetLoc(Context context)
{
this.context= context;
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
//Toast.makeText(context, "Location can't be retrieved", Toast.LENGTH_SHORT).show();
Criteria criteria = new Criteria();
// pd = ProgressDialog.show(context, "","Please wait... ");
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
else
Toast.makeText(context, "Location can't be retrieved", Toast.LENGTH_SHORT);
}else{
Toast.makeText(context, "No Provider Found", Toast.LENGTH_SHORT);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location.getLatitude()>0 && location.getLongitude()>0)
{
lati=location.getLatitude();
logi=location.getLongitude();
state= getAddress(context, lati, logi);
}
// Toast.makeText(context, "No"+zz, Toast.LENGTH_SHORT).show();
// pd.dismiss();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public String getAddress(Context ctx, double latitude, double longitude) {
StringBuilder result = new StringBuilder();
try {
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
//String locality=address.getLocality();
//String city=address.getCountryName();
//String region_code=address.getCountryCode();
state= address.getAdminArea();
// zipcode=address.getPostalCode();
double lat =address.getLatitude();
double lon= address.getLongitude();
// result.append(locality+" ");
// result.append(city+" "+ region_code+" ");
//result.append(zipcode);
}
} catch (IOException e) {
// Log.e("tag", e.getMessage());
}
return state;
}
}
Try this way:
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
progDailog = new ProgressDialog(FastMainActivity.this);
progDailog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
FetchCordinates.this.cancel(true);
}
});
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(true);
progDailog.setCancelable(true);
progDailog.show();
}
#Override
protected void onCancelled(){
System.out.println("Cancelled by user!");
progDialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
progDailog.dismiss();
Toast.makeText(FastMainActivity.this,
"LATITUDE :" + lati + " LONGITUDE :" + longi,
Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) location.getLatitude(); // * 1E6);
int log = (int) location.getLongitude(); // * 1E6);
int acc = (int) (location.getAccuracy());
String info = location.getProvider();
try {
// LocatorService.myLatitude=location.getLatitude();
// LocatorService.myLongitude=location.getLongitude();
lati = location.getLatitude();
longi = location.getLongitude();
} catch (Exception e) {
// progDailog.dismiss();
// Toast.makeText(getApplicationContext(),"Unable to get Location"
// , Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.i("onStatusChanged", "onStatusChanged");
}
}
}
}
i tried a lot of "get current location" for android. But i think most of them are outdated, or i simply dont get it.
I DONT want to set a marker.addmarker(params..) i would like to use the blue default dot for my position on Gmaps. Here i've found somthing about that, but for my bad it also aint work.
Customize marker of myLocation Google Maps v2 Android
So in first line i need, my current Location with a Listener when my Location is updating. Im trying this right now (Testing on a real device). But myLocation is always =null.
//get GMaps Fragment
mMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true); //activate Blue dot
myLocation = mMap.getMyLocation(); //Testing, but not working = null
//Trying with LocationManager
locManager =(LocationManager)getSystemService(this.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locManager.getBestProvider(criteria, true);
myLocation = locManager.getLastKnownLocation(provider);
if(myLocation != null){
double lat = myLocation.getLatitude();
double lon = myLocation.getLongitude();
}
locManager.requestLocationUpdates(provider, 1000, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
myLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
Follow this http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ . Then just place the latitude and longitude you get(using gps.getLatitude(), gps.getLongitude()) in your google map and it will show your current location.
Try this code, it is worked in my application:
private LocationManager locationManager;
private String provider;
double lat,lon;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locate);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 1, this);
if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
gpsalert();
}
// Criteria to select location provider
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Toast.makeText(getApplicationContext(), "Provider is available", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Provider is not available", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String addr,city,country;
lat=location.getLatitude();
lon=location.getLongitude();
//Toast.makeText(getApplicationContext(), "lat"+lat+"long"+lon, Toast.LENGTH_LONG).show();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lon, 1);
addr = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getAddressLine(1);
country = addresses.get(0).getAddressLine(2);
t1.setText(addr+"\n"+city+"\n"+country);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_SHORT).show();
//t1.setText("");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Enabled provider " + provider, Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onResume() {
super.onResume();
//locationManager.requestLocationUpdates(provider, 400, 1, this);
}
// Remove LocationListener updates
#Override
protected void onPause() {
super.onPause();
//locationManager.removeUpdates(this);
}
public void gpsalert()
{
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
I'm trying to make a simple program to perform distance calculations that will be shown in listview. I use GPSTracker from androidhive, and calling latitude and longitude fo my List Activity
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled =false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double 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);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled&& !isNetworkEnabled){
//no network enable
}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(isGPSEnabled){
if(location == null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} catch (Exception e){
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch 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 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();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And My List Activity
public class Mobil extends ListFragment implements LocationListener{
GPSTracker gps;
private static final String url = "http://10.0.2.2/tambalban/car.php";
JSONArray tambalban = null;
ArrayList<HashMap<String, String>> listMobil = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new getJSONData().execute();
}
public class getJSONData extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromURL(url);
gps = new GPSTracker(getActivity()); // is it right calling from GPSTracker?
double lat_user = gps.getLatitude(); // get latitude, right?
double lng_user = gps.getLongitude();
System.out.println("lat_user : "+lat_user+""); // print in logcat return 0.00
System.out.println("lng_user : "+lng_user+"");// print in logcat return 0.00
try {
tambalban = json.getJSONArray(TAG_TAMBALBAN);
for (int i = 0; i < tambalban.length(); i++) {
JSONObject mtr = tambalban.getJSONObject(i);
String id_tb = mtr.getString(TAG_ID);
String name_tb = mtr.getString(TAG_NAMA);
String address_tb = mtr.getString(TAG_ALAMAT);
String telp_tb = mtr.getString(TAG_TELP);
String lat = mtr.getString(TAG_LAT);
String lng = mtr.getString(TAG_LNG);
double lat_tujuan = Double.parseDouble(lat);
double lng_tujuan = Double.parseDouble(lng);
double distance = hitungJarak(lat_user, lng_user, lat_tujuan, lng_tujuan);
distance = RoundDecimal(distance, 2);
String dist = Double.toString(distance)+" km";
HashMap<String, String> a = new HashMap<String, String>();
a.put(TAG_ID, id_tb);
a.put(TAG_NAMA, name_tb);
a.put(TAG_ALAMAT, address_tb);
a.put(TAG_TELP, telp_tb);
a.put(TAG_LAT, lat);
a.put(TAG_LNG, lng);
a.put(TAG_JARAK, dist);
listMobil.add(a);
}
} catch (JSONException e) {
e.printStackTrace();
}
return listMobil;
}
private double RoundDecimal(double distance, int i) {
BigDecimal bd = new BigDecimal(distance);
bd = bd.setScale(i, 6);
return bd.doubleValue();
}
private double hitungJarak(double lat_user, double lng_user,
double lat_tujuan, double lng_tujuan) {
double dist;
double radius = 6371;
double dLat = Math.toRadians(lat_tujuan - lat_user);
double dLon = Math.toRadians(lng_tujuan- lng_user);
double a = Math.sin(dLat/2) * Math.sin(dLat /2)
+ Math.cos(Math.toRadians(lat_user)) * Math.cos(Math.toRadians(lat_tujuan))
* Math.sin(dLon/ 2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = radius * c;
double km = valueResult/1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
dist = radius * c;
return dist;
}
#Override
protected void onPostExecute(
ArrayList<HashMap<String, String>> listMobil) {
// TODO Auto-generated method stub
super.onPostExecute(listMobil);
ListAdapter adapter = new SimpleAdapter(getActivity(), listMobil,
R.layout.list_item, new String[] { TAG_NAMA, TAG_ALAMAT, TAG_JARAK },
new int[] { R.id.namatb, R.id.alamattb,R.id.jarak });
setListAdapter(adapter);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.list_fragment, container, false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String pilih = getListAdapter().getItem(position).toString();
Toast.makeText(getActivity(),
pilih,
Toast.LENGTH_LONG).show();
Intent i = new Intent(getActivity(), DetailDaftar.class);
Bundle bundle = new Bundle();
bundle.putString("Selected", pilih);
i.putExtras(bundle);
startActivity(i);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
I check using Sytem.out.println, both latitude and longitude return 0.00.
Am I wrong with calling current Location? Thanks you for any help.
You should create your GPSTracker gps object outside your AsyncTask try like:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gps = new GPSTracker(getActivity()); // is it right calling from GPSTracker?
new getJSONData().execute();
}
And also add required permission into your manifest.xml file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
your GPSTracker class will return current location latitude and longitude. I have already checked and it is returning lat/long values.
In second part I am not getting, what you are trying to do with json but if you want to get latitude longitude in another activity then simply instantiate GPSTracker class like
Inside activity
GPSTracker tracker;
and inside onCreate method
tracker=new GPSTracker(this);
and another one thing ypu can not print or log any statement in doInBackground() method because it will run in background only.
Try to toast your output in onPostExecute() method
If you are using emulator for testing, then you should do the following:
1.In your editor (I assume you are using Eclipse) go to
Window -> Open Perspective -> Show View -> Emulator Control.
2 There you would see two editable textbox with tags 'latitude' and 'longitude'.
3 Set the values appropriately and click send.
Now your emulator has the values set by you.
This is my code for getting Longitude and Latitude , it works great for me
public void setLocation() {
LocationManager LM;
LM = (LocationManager) CurrentContext
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// adjust ur criteria with ur desired features
provider = LM.getBestProvider(criteria, true);
try {
LM.requestLocationUpdates(provider, 1000, 1, this);
if (LM != null) {
Loc = LM.getLastKnownLocation(provider);
if (Loc != null) {
userLocation = new Location("");
userLocation.setLatitude(Loc.getLatitude());
userLocation.setLongitude(Loc.getLongitude());
}
}
} catch (Exception e) {
DisplayUnexpected();
e.printStackTrace();
return;
}
LM.removeUpdates(this);
}
Use this code
public class LocationUpdateService extends Service {
private LocationManager _locationManager;
private boolean _gpsEnabled,_networkEnabled;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
_gpsEnabled = _locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
_networkEnabled = _locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void onStart(Intent intent, int startId) {
Log.e("onStart","onStart");
if( _gpsEnabled ) {
_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000, 0, locationListener);
} else if ( _networkEnabled ){
_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000, 0, locationListener);
}
};
LocationListener locationListener = new LocationListener() {
#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 onLocationChanged(final Location location) {
final Location currentLocation = location;
Log.e("onLocationChanged", " " + currentLocation);
_locationManager.removeUpdates(locationListener);
Toast.makeText(LocationUpdateService_2.this, "Location lat "+currentLocation.getLatitude()+ " long "+currentLocation.getLongitude() , Toast.LENGTH_LONG).show();
}
};
I can get longitude and latitude by network provider, but unable to get it by GPS. How can I do that?
public void onCreate(Bundle savedInstanceState) {
...
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (mLocation != null) {
gp1 = getGeoByLocation(mLocation);
gp2 = gp1;
refreshMapView();
if( !mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000,
10, mLocationListener);
}else{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000,
10, mLocationListener);
}
private GeoPoint getGeoByLocation(Location location) {
GeoPoint gp = null;
try {
if (location != null) {
double geoLatitude = location.getLatitude() * 1E6;
double geoLongitude = location.getLongitude() * 1E6;
gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return gp;
}
Get lat long using GPS in every 10 min.
// Des: Start Device's GPS and get current latitude and longitude
public void GPS() throws IOException {
// Des: This is a background service and called after every 10 minutes and fetch latitude-longitude values
background = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < j; i++) {
if (ProjectStaticVariable.GPSExit == true ) {
try {
Thread.sleep(600000); //10 minutes
mainhandler.sendMessage(mainhandler.obtainMessage());
j++;
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
});
background.start();
mainhandler = new Handler() {
public void handleMessage(Message msg) {
// Check Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
lat_long_Service_flag = true;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener(getApplicationContext());
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, mlocListener);
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
}
};
}
// Des: Location Listener through which we get current latitude and longitude
public class MyLocationListener implements LocationListener {
public MyLocationListener(Context mContext) {}
public MyLocationListener(Runnable runnable) {}
#Override
public void onLocationChanged(Location loc) {
longitude = loc.getLongitude();
latitude = loc.getLatitude();
final_latitude = Double.toString(latitude);
final_longitude = Double.toString(longitude);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}