Multiple markers : why? - java

I just want to know why that code gives me a lot of markers at the same place when I try to
get users current location ?
I didn't manage to do that in a different class service if anyone knows how to do that in a service or AsyncTask that will help me a lot in my project.
Thanks!
package toutel.testcarte;
import org.osmdroid.ResourceProxy;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
private MapController mapController;
private MapView mapView;
private GeoPoint myposition;
private ItemizedOverlay<OverlayItem> mMyLocationOverlay;
private ResourceProxy mResourceProxy;
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapview);
mapController = (MapController) mapView.getController();
GeoPoint myposition = new GeoPoint(48.856614, 2.3522219000000177);
mapView.setTileSource(TileSourceFactory.MAPNIK);
mapView.setBuiltInZoomControls(false);
mapView.setMultiTouchControls(true);
// mapController.animateTo(myposition);
mapController.setZoom(13);
mapController.setCenter(myposition);
Context context = getApplicationContext();
CharSequence text = "Activez votre GPS pour utiliser la localisation ";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menu) {
switch (menu.getItemId()) {
case (R.id.fermer): {
System.exit(0);
break;
}
case (R.id.position): {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
while (true) {
LocationListener mylocationlistener = new LocationListener() {
public void onLocationChanged(Location location) {
Context ctx = getApplicationContext();
GeoPoint myposition = new GeoPoint(
location.getLatitude(), location.getLongitude());
mapController.animateTo(myposition);
mapController.setCenter(myposition);
mapController.setZoom(17);
Marker marker = new Marker(mapView);
marker.setPosition(myposition);
marker.setAnchor(Marker.ANCHOR_CENTER,
Marker.ANCHOR_BOTTOM);
mapView.getOverlays().add(marker);
mapView.invalidate();
try {
Thread.sleep(10 * 1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
#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
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, mylocationlistener);
break;
}
}
case (R.id.itineraire): {
}
}
return false;
}
}

Multiple markers : why?
You are getting multiple markers because every time location is changed you are placing a marker on the map.even change in the position is too small.You are placing marker.Try to zoom in you will see that all markers are not at same position.
My suggestion there is no need of service here.Because OnlocationChanged listener automatically do your job.I have written this single class.Now where ever in the project you need the GPS coordinates, just instantiate the class object and get the Latitude and Longitude.
LocationSender loc = new LocationSender(YourClass.this);
As i declared lat,lng (in LocationSender.java) as static so i can get any where its values.
double latitude = LocationSender.lat;
double longitude = LocationSender.lng;
LocationSender.java
public class LocationSender {
Context context;
LocationManager locationManager;
Location location;
static double lat,lng;
public LocationSender(Context ctx) {
context=ctx;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
// Acquire a reference to the system Location Manager
public void getNewLocation(Location location) throws JSONException
{
String latLongString = "";
if (location != null) {
this.location=location;
lat= location.getLatitude();
lng = location.getLongitude();
latLongString = "Lat:" + String.valueOf(LocationActivity.lat) + "\nLong:" + String.valueOf(LocationActivity.lng);
Log.d("Location Found", latLongString);
} else
{
location=null;
latLongString = "No location found";
}
Toast.makeText(context, latLongString, Toast.LENGTH_LONG).show();
}
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
try {
getNewLocation(location);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onProviderEnabled(String provider) {
Toast.makeText(context, "Provider: "+provider+" : Enabled", Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(context, "Provider: "+provider+" : disabled", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(context, "Provider: "+provider+" : status: "+status, Toast.LENGTH_LONG).show();
}
};
}
Also don't forget to add the permissions in AndroidManifest.xml

Do you really need a custom implementation for the location manager / location service's onLocationChanged() callback ?
Otherwise, you could take a look at OSMDroid's MyLocationNewOverlay class https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/main/java/org/osmdroid/views/overlay/mylocation/MyLocationNewOverlay.java?r=1220
There is also another implementation, (deprecated unfortunatelly) called MyLocationOverlay https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/org/osmdroid/views/overlay/MyLocationOverlay.java?r=902
In my implementation, I use it like this:
//declare variable; global - because I need reference elsewhere
private MyLocationOverlay self;
//somewhere in code
//'this' - is the context
//mapMainView - my mapView
self = new MyLocationOverlay(this, mapMainView);
self.enableMyLocation();
self.enableFollowLocation();
//add the overlay to the map and refresh the view
mapMainView.getOverlays().add(COUNT+1, self);//COUNT is the size of the List<Overlay> returned by mapMainView.getOverlays(); this is just because I want my 'self' to be always the last overlay added
mapMainView.invalidate();//refresh the view
This puts a default icon at my location on the map, and it updates constantly as I move.

Related

How can I use AlarmReceiver to ping GPS location every 10 minutes?

I'm really sorry ahead of time, but this question is pretty lengthy.
I have a functioning GPSTracker class that contains the means of pinging GPS Location for a device. In my MainActivity, I have a button that uses the GPS tracker to display the location in a toast. I'm trying to convert this button into an automatic action to be repeated every X minutes, let's go with 10.(Right now the alarm receiver is setup for 10 seconds)
Even when the app is in the background. So I set up an AlarmReceiver to try to do this, but I can't quite get it working.
Here's my GPSTracker class:
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean canGetLocation = false;
boolean isNetworkEnabled = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context.getApplicationContext();
getLocation();
}
public Location getLocation(){
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
}else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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(locationManager !=null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
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;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS isn't enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
And here's my MainActivity:
package com.example.gwyn.locationnabtest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends ActionBarActivity {
Button btnShowLocation;
Button btnStartService;
Button btnStopService;
GPSTracker gps;
//GoogleMap mMap;
private PendingIntent pendingIntent;
private AlarmManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.show_location);
btnShowLocation.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
FragmentActivity activity = (FragmentActivity)view.getContext();
FragmentManager manager = activity.getSupportFragmentManager();
//MapFragment myMap = (MapFragment) (MainActivity.getFragmentManager()).findFragmentById((R.id.mapFragment));
// Test, remove me.
// mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment)).getMap();
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()) {
// Location Achieved.
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// Draw Marker for Current Location on Fragment
// Currently Crashing App
// mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
// Toast a popup of the location data.
Toast.makeText(getApplicationContext(), "Your Location is -\nLat:" + latitude + "\nLong:" + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
btnStartService = (Button) findViewById(R.id.start_service);
btnStartService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 10000;
// 10 Second Interval. Good for testing, but turn this off.
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_SHORT).show();
//startService(new Intent(getBaseContext(), MyServices.class));
}
});
btnStopService = (Button) findViewById(R.id.stop_service);
btnStopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Cancel pending intents
manager.cancel(pendingIntent);
Toast.makeText(getApplicationContext(), "Pending Intents Cancelled", Toast.LENGTH_SHORT).show();
}
});
}
}
To highlight specifically, this is the part in MainActivity that works to display the GPS:
public void onClick(View view) {
FragmentActivity activity = (FragmentActivity)view.getContext();
FragmentManager manager = activity.getSupportFragmentManager();
//MapFragment myMap = (MapFragment) (MainActivity.getFragmentManager()).findFragmentById((R.id.mapFragment));
// Test, remove me.
// mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment)).getMap();
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()) {
// Location Achieved.
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// Draw Marker for Current Location on Fragment
// Currently Crashing App
// mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
// Toast a popup of the location data.
Toast.makeText(getApplicationContext(), "Your Location is -\nLat:" + latitude + "\nLong:" + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
My AlarmReceiver is as follows, and produces an error when creating the GPSTracker:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
GPSTracker gps;
#Override
public void onReceive(Context arg0, Intent arg1) {
// Here's where we'd grab location and store it into DB.
//gps = new GPSTracker(AlarmReceiver.this);
// if(gps.canGetLocation()) {
// double latitude = gps.getLatitude();
// double longitude = gps.getLongitude();
// Draw Marker for Current Location on Fragment
// Toast a popup of the location data.
// Toast.makeText(arg0, "Your Location is -\nLat:" + latitude + "\nLong:" + longitude, Toast.LENGTH_LONG).show();
// } else {
// gps.showSettingsAlert();
// }
// Toast that the alarm ran.
Toast.makeText(arg0, "Location Pinged.", Toast.LENGTH_SHORT).show();
}
More specifically, a part of the problem is the way I'm calling for the new gps Tracker object here:
//gps = new GPSTracker(AlarmReceiver.this);
I'm not sure how to achieve the original result while using the alarmreceiver instead of a button, which is the main source of my problem. Does anyone know exactly what I can tinker with here to get the alarm receiver to properly use the GPSTracker Class?
DO not use GPSTracker. Its broken in over a dozen ways. Forget it exists. If you want a better version, you can use http://gabesechansoftware.com/location-tracking/ That link also explains why GPSTracker is broken by design and why it should never be used. It basically kinda works if used in optimal circumstances, and gives you horrible data in all the others.
Secondly, if you're using GPS and not network- you need to give it time to get a location sync. This can take seconds to minutes (or hours, if the user is in a basement or something) so the immediate forms of getting a location won't work- you have to wait for it to actually sync the location.
I suggest you not look for libraries to solve this and actually try to understand how the base APIs work. Until you do, you're going to have troubles with anything you use as there's lots of corner cases here and its not a trivial thing to do.

Why the function getLastKnownLocation return Null on Android SDK?

I use android sdk on eclipse and i want to get location from device so i wrote an program in other class(diffrent from main) and i call mContext function inside this class from main class:
package com.example.deomanapp;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import com.example.deomanapp.MainActivity.PlaceholderFragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
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.widget.TextView;
import android.widget.Toast;
public class Mhelper {
public void mContext(Context context)
{
LocationManager lm;
lm = (LocationManager)context.getSystemService(context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
String slongitude = String.valueOf((long) longitude);
String slatitude = String.valueOf((long) latitude);
Toast.makeText(context, slongitude, Toast.LENGTH_SHORT).show();
}
}
The problem is getLongitude or getLatitude return null,so the program crash on this line with this log:
04-20 04:30:30.410: E/AndroidRuntime(5151): java.lang.NullPointerException
04-20 04:30:30.410: E/AndroidRuntime(5151): at com.example.deomanapp.Mhelper.mContext(Mhelper.java:29)
What is wrong with this code ?
PS: I read other question with the same title and non of theme help (non of them have actual answer) because:
1-I test this program on the real device(not emulator) with GPS ON and working , but this program can't able to get location although the Device get its location before and it must show LastKnownLocation.
2-I gave the program ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION permission.
3-I even use an function to see if the GPS is on, when i turn it off program alert me.
It was silly question to ask ,It was null because it was NULL,i understand it by comments on main question, my solution was to download android api image in sdk manager,run Google map once and send GPS location to it by DDMS and then run the program.
I have tried to modify some of my code, hopefully it works for your needs.
You will find the implementation of my LocationsCoreModule code in the bottom of the answer:
LocationsCoreModule locationService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationRequest mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(5000);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(1000);
locationService = new LocationsCoreModule(this, mLocationRequest);
locationService.setLocationsListener(new LocationsCoreModuleCallback() {
#Override
public void locationClientConnected() {
Location location = locationService.getLastLocation();
double longitude = location.getLongitude();
double latitude = location.getLatitude();
String slongitude = String.valueOf((long) longitude);
String slatitude = String.valueOf((long) latitude);
Toast.makeText(getApplicationContext(), slongitude, Toast.LENGTH_SHORT).show();
}
});
}
If you want the application to start listening for new GPS locations right away:
#Override
protected void onStart() {
super.onStart();
locationService.start(new LocationListener() {
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
}, new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onStop() {
super.onStop();
locationService.stop();
}
And finally, the LocationsCoreModule:
public class LocationsCoreModule implements
GooglePlayServicesClient.ConnectionCallbacks {
private static final String TAG = "LocationsCoreModule";
public interface LocationsCoreModuleCallback {
public void locationClientConnected();
}
private LocationsCoreModuleCallback locationsCoreModuleCallback;
private com.google.android.gms.location.LocationListener locationListener;
private Location lastLocation;
private LocationClient mLocationClient;
private final LocationRequest mLocationRequest;
private final Context context;
#Inject
public LocationsCoreModule(Context context, LocationRequest locationRequest) {
this.context = context;
this.mLocationRequest = locationRequest;
}
public void setLastLocation(Location lastLocation) {
this.lastLocation = lastLocation;
}
public void setLocationsListener(
LocationsCoreModuleCallback locationsCoreModuleCallback) {
this.locationsCoreModuleCallback = locationsCoreModuleCallback;
}
public void start(
com.google.android.gms.location.LocationListener locationListener,
GooglePlayServicesClient.OnConnectionFailedListener connectionFailedListener) {
this.locationListener = locationListener;
mLocationClient = new LocationClient(context, this,
connectionFailedListener);
mLocationClient.connect();
}
public void stop() {
if (mLocationClient != null) {
// If the client is connected
if (mLocationClient.isConnected() && locationListener != null) {
/*
* Remove location updates for a listener. The current Activity
* is the listener, so the argument is "this".
*/
mLocationClient.removeLocationUpdates(locationListener);
}
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
}
}
public boolean isConnected() {
if (mLocationClient == null) return false;
return mLocationClient.isConnected();
}
public Location getLastLocation() {
if (lastLocation != null) {
return lastLocation;
}
if (mLocationClient != null) {
if (mLocationClient.isConnected()) {
return lastLocation = mLocationClient.getLastLocation();
}
if (!mLocationClient.isConnecting())
mLocationClient.connect();
}
return null;
}
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "GooglePlayServices connected!");
Location lastLocation = mLocationClient.getLastLocation();
if (lastLocation == null)
Log.e(TAG, "Lastlocation is null even after connected!!!!");
if (locationsCoreModuleCallback != null) {
locationsCoreModuleCallback.locationClientConnected();
locationsCoreModuleCallback = null; // single shot
}
}
public void requestLocationUpdates() {
if (mLocationClient != null && mLocationClient.isConnected()) {
Log.d(TAG, "Requesting location updates");
mLocationClient.requestLocationUpdates(mLocationRequest,
locationListener);
}
}
public void stopLoactionUpdates() {
if (mLocationClient != null && mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(locationListener);
}
}
#Override
public void onDisconnected() {
Log.d(TAG, "GooglePlayServices disconnected!");
}
}

How to get different latitude and longitude while moving for every 1 minute in android?

now i am working with GPS for getting different latitude and longitude for every 1 minute while moving and that has to be stored into array list. I am using thread for this. I followed this link. http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/
And my code is
Tracking.java
package com.example.getlatlang;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Tracking extends Activity
{
Button btnShowLocation;
boolean isRepeat = true;
protected int splashTime = 1000;
int timer =0;
Thread th;
ArrayList<Double> lat_array = new ArrayList<Double>();
ArrayList<Double> lon_array = new ArrayList<Double>();
// GPSTracker class
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.currentlocation);
btnShowLocation = (Button) findViewById(R.id.start_bt);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// create class object
if(isRepeat)
{
isRepeat = false;
btnShowLocation.setBackgroundResource(R.drawable.stop);
if(lat_array.size()>0 && lon_array.size()>0)
{
lat_array.clear();
lon_array.clear();
System.out.println("Array cleared...");
}
// check if GPS enabled th=new Thread()
th=new Thread()
{
#Override
public void run(){
try
{
for (timer = 0; timer < 20; timer++)
{
// int waited = 0;
// while(waited < splashTime)
// {
Thread.sleep(100);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
try
{ gps = new GPSTracker(Tracking.this);
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
lat_array.add(latitude);
lon_array.add(longitude);
// \n is for new line
System.out.println("lat_array"+lat_array+"lon_array"+lon_array);
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat_array + "\nLong: " + lon_array, Toast.LENGTH_LONG).show();
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
// waited += 100;
//}
}}
catch (InterruptedException e)
{
}
}
};
th.start();
}
else
{
isRepeat = true;
th.interrupt();
btnShowLocation.setBackgroundResource(R.drawable.start);
}
}
});
}
public void ohDestroy()
{
th.stop();
}
}
GPSTracker.java
package com.example.getlatlang;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.util.Log;
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 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;
}
/**
* 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/wifi enabled
* #return boolean
* */
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) {
}
#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;
}
}
Now my issue is can't able to get different latitude and longitude points while moving. The first value only stored into an array for 20 times. Because i am setting the Tread must be run 20 times like that. But i want to get different points and stored into an array list. I don't know where i did the mistake. Can any body help me to resolve this problem? Thanks in advance.
you have used sleep(100) on the loop of collecting latitude.
The unit of time is micro-second here.(as far as i know)
20*100 = 2000 which is just 2 second. and i don't think GPS update that fast.
Have a look at this.
Rather you can use the same loop but store the value only if it is different from previous one.
if(oldLat != curLat){
//store curLat to array
//and make oldLat = curLat
}
Apply this. It will refresh every 10 seconds.
Handler mHandler1 = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler1.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// creating GPS Class object
GPSTracker gps = new GPSTracker (Tracking .this);
// check if GPS location have some values
if (gps.canGetLocation()) {
double currentlat = gps.getLatitude();
double currentlong = gps.getLongitude();
} else {
// no current location
gps.showSettingsAlert();
}
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();

onLocationChanged doesn't work?

on LocationChanged listener don't work.
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class SimpleLocation extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
Toast.makeText(getApplicationContext(),
"Lat:" + lat + " Lng:" + lng, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "No Value",
Toast.LENGTH_LONG).show();
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1,
(LocationListener) this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates((LocationListener) this);
}
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
Toast.makeText(getApplicationContext(),
"onLocationChanged Lat:" + lat + " Lng:" + lng,
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
locationManager.requestLocationUpdates(provider, 400, 1,
(LocationListener) this);
which is of the format:
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
This line in your code specifies that the location changes will be registered in your application only when there is minimum of "1" distance movement. Set that to 0 and try running your code again. Or set both minTime and minDistance to 0 and try.

how can i retrieve user location and show him the map

i have questions that i am really need some help on it:
i develop application and i want :
1-retrieve the user location and show it in the map.
2- the user can put pin in any place in the map and i should take the coordination to this pin and store it in variable
Note:my application in 2.1 should i use google API? if yes, does the google API support any activity rather than maps?
i search in google and find this code :
package com.java.locate;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class AndroidLbsGeocodingProjectActivity extends Activity {
/** Called when the activity is first created. */
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(AndroidLbsGeocodingProjectActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(AndroidLbsGeocodingProjectActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(AndroidLbsGeocodingProjectActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(AndroidLbsGeocodingProjectActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(AndroidLbsGeocodingProjectActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
this is another code, this by using google API, but i have 2 issues in using this code :
1-it does not retrieve the user location, it is just show me the maps.
2-does google API working with another activity not just map?
package our.google.maps;
import java.util.List;
import java.util.Locale;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;
public class MapsActivity extends MapActivity {
/** Called when the activity is first created. */
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
MapView map;
//136
int x,y;
GeoPoint touchedPoint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
map=(MapView) findViewById(R.id.mvMain);
map.setBuiltInZoomControls(true);
Touchy t = new Touchy();
List<Overlay> overlaylist= map.getOverlays();
overlaylist.add(t);
compass = new MyLocationOverlay (MapsActivity.this, map);
overlaylist.add(compass);
//map controller to go to Specific Location n36eeh el 6ol & el 3r'9 135
controller=map.getController();
GeoPoint point = new GeoPoint (51643234 , 7848593);
controller.animateTo(point);
controller.setZoom(6);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
compass.disableCompass();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
compass.enableCompass();
super.onResume();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay {
public boolean onTouchEvent(MotionEvent e,MapView m){
if(e.getAction() == MotionEvent.ACTION_DOWN){
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = map.getProjection().fromPixels(x, y);
}
if (e.getAction() == MotionEvent.ACTION_UP) {
stop =e.getEventTime();
}
if(stop - start >1500) {
AlertDialog alert = new AlertDialog.Builder(MapsActivity.this).create();
alert.setTitle("Pick an option");
alert.setMessage(" i told u to pick an option");
alert.setButton("place a pin", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
} );
alert.setButton2("get an address", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Geocoder geocode = new Geocoder (getBaseContext(),Locale.getDefault());
try {
}
finally{}}}
);
alert.setButton3("option3 ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
} );
alert.show();
return true;
}
return false;
}
}
private class MyLocationListener implements LocationListener{
public void onLocationChanged1(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MapsActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MapsActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MapsActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MapsActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
}
}
also,if my code is not correct, can you please give me the correct coed?
StackOverFlow members you are My HERO! help me PLEASE!
You can Use Google Maps.
You will require Map Api key.
If you are coding Using Eclipse then you can follow the procedure given on link
http://mobiforge.com/developing/story/using-google-maps-android

Categories

Resources