How do I move marker on Google maps api V2 ? I am using below code but it does not move marker on the map. What am I doing wrong here ? This should work when location changes, so I have added onLocationChanged method and in that, am getting location details and trying to move marker on new details, but this doesn't work.
Here is my code:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
public class MapViewActivity extends Activity implements LocationListener,
SensorEventListener, OnClickListener {
GoogleMap googleMap;
private boolean started = false;
private ArrayList<AccelLocData> sensorData;
private SensorManager sensorManager;
private Button btnStart, btnStop;
private String provider;
// File root, dir, sensorFile;
FileOutputStream fOut;
private Sensor mAccelerometer;
private FileWriter writer;
private DatabaseHelper databaseHelper;
private BroadcastReceiver alarmReceiver;
private PendingIntent pendingIntentSender, pendingIntentReceiver;
private AlarmManager alarmManager;
private Intent alarmIntent,alarmIntent2;
// private Button btnUpload;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
databaseHelper = new DatabaseHelper(this);
databaseHelper.removeAll();
Log.v("datacount",
Integer.toString(databaseHelper.getLocDataCount()));
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services
// are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
this, requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment of
// activity_main.xml
// SupportMapFragment supportMapFragment = (MapFragment)
// getFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// can use for overlay on the map
List<Double> latList = new ArrayList<Double>();
latList.add(145.7309593);
latList.add(146.34);
latList.add(147.34);
List<Double> lonList = new ArrayList<Double>();
lonList.add(-122.6365384);
lonList.add(-123.6365384);
lonList.add(-124.6365384);
for (int i = 0; i < 3; i++) {
// LatLng latLng = new LatLng(45.7309593, -122.6365384);
LatLng latLng = new LatLng(latList.get(i).doubleValue(),
lonList.get(i).doubleValue());
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap
.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager
.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager
.requestLocationUpdates(provider, 20000, 0, this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void onSensorChanged(SensorEvent event) {
if (started) {
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
long timestamp = System.currentTimeMillis();
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locManager.getBestProvider(criteria, true);
Location location = locManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
AccelLocData accelLocData = new AccelLocData(timestamp, x, y, z,
latitude, longitude);
// Log.d("X data","data x:" + data.getX());
try {
// writer.write(data.toString());
if (databaseHelper != null)
databaseHelper.insertLocData(accelLocData);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
Context context = getApplicationContext();
alarmIntent = new Intent(context, AccelLocSender.class);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
pendingIntentSender = PendingIntent.getBroadcast(context, 0,
alarmIntent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 60000, pendingIntentSender);
alarmIntent2 = new Intent(context, AccelLocReceiver.class);
pendingIntentReceiver = PendingIntent.getBroadcast(context, 0,
alarmIntent2, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 30000, pendingIntentReceiver);
btnStart.setEnabled(false);
btnStop.setEnabled(true);
Log.d("startbutton", "cam on click of start");
started = true;
// delete all files..
// start thread to send data
sensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_FASTEST);
break;
case R.id.btnStop:
try {
btnStart.setEnabled(true);
btnStop.setEnabled(false);
// btnUpload.setEnabled(true);
started = false;
sensorManager.unregisterListener(this);
Context context1 = getApplicationContext();
AlarmManager alarmManager1 = (AlarmManager) context1
.getSystemService(Context.ALARM_SERVICE);
alarmManager1.cancel(pendingIntentSender);
alarmManager1.cancel(pendingIntentReceiver);
// System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
}
protected void onPause() {
super.onPause();
/*
* if (writer != null) { try { writer.close(); } catch (IOException e) {
* // TODO Auto-generated catch block e.printStackTrace(); } }
*/
}
protected void onResume() {
super.onResume();
/*
* try { Log.d("onresume","called onresume"); writer = new
* FileWriter(sensorFile, true); } catch (IOException e) { // TODO
* Auto-generated catch block e.printStackTrace(); }
*/
}
#Override
public void onProviderDisabled(String arg0) {
// 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 void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
}
Make variable
Marker now;
in this part add Marker and remove marker, of course put in the rest of your marker attributes:
#Override
public void onLocationChanged(Location location) {
if(now != null){
now.remove();
}
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
now = googleMap.addMarker(new MarkerOptions().position(latLng)));
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
Make the marker draggable using,
MarkerOptions markerOptions = new MarkerOptions().position(myLaLn).title(
"Current Location").draggable(true);
map.addMarker(markerOptions);
& Get the dragged position & details as follows,
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
Log.d(TAG, "latitude : "+ marker.getPosition().latitude);
marker.setSnippet(marker.getPosition().latitude);
map.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()));
}
#Override
public void onMarkerDrag(Marker marker) {
}
});
Optimized way to move marker :
marker mMarker;
After adding marker to map. while change the location you just need to set position rather than remove marker and add again.
mMarker.setPosition(new LatLon(latLng));
this will reduce the code from remove and add marker to direct set position and also reduce complexity. :)
Enjoy.
You are just moving camera on location change where as you should add marker as well then it will draw marker on current location. and before adding marker clear all the previous markers by calling googlmap.clear();
addMarker returns a reference to the marker which then later can be updated
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if(mMarker == null) {
mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
} else {
mMarker.setPosition(latLng);
}
}
});
Related
I want to add marker on map with long click. but it is not working. normal click is working.
This is my code.
public class Map extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.map);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
// Getting GoogleMap object from the fragment
googleMap = supportMapFragment.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
// Getting latitude of the current location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng).title("you are here" ));
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(5));
// Setting latitude and longitude in the TextView tv_location
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
public void onMapClick (LatLng point) {
// Do Something
googleMap =
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();
googleMap.addMarker(new MarkerOptions()
.position(point)
.title("TouchPoint"));
}
public void onMapLongClick(LatLng point) {
googleMap.addMarker(new MarkerOptions().position(point).title(
point.toString()));
Toast.makeText(getApplicationContext(),
"New marker added#" + point.toString(), Toast.LENGTH_LONG)
.show();
}
#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
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
How can i solve this ?
In onCreate
googleMap.setOnMapLongClickListener(longClickListener);
Inside the activity
private OnMapLongClickListener longClickListener = new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
//do work }
}
i try to put a Polyline on my Map from the current Location to a Marker.
If i put the Lat und Longitude directly in the code, the Polyline is drawing.
But if i try to take the Lat and Lon from the Locationlistener, it doesnt work and the googlemaps link looks like this: http://maps.googleapis.com/maps/api/directions/xml?origin=0.0, 0.0&destination=0.0, 0.0...
here is the code:
private GoogleMap myMap;
private final long zero = 0;
private HashMap<String, Spot> spots = null;
private Dialog dialog;
private double sourceLatitude;
private double sourceLongitude;
private double destLatitude;
private double destLongitude;
Button buttonRequest;
GoogleDirection gd;
Document mDoc;
LatLng start = new LatLng(sourceLatitude, sourceLongitude);
LatLng end = new LatLng(destLatitude, destLongitude);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.karte);
Dialog b = new Dialog(this);
dialog = b;
SupportMapFragment mySupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
myMap = mySupportMapFragment.getMap();
myMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
myMap.setMyLocationEnabled(true);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 0,
mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 0,
mlocListener);
SharedPreferences settings = getSharedPreferences("cityhallprefs", 0);
moveCamera(Double.longBitsToDouble(settings.getLong("camlat", zero)),
Double.longBitsToDouble(settings.getLong("camlng", zero)));
gd = new GoogleDirection(this);
gd.setOnDirectionResponseListener(new OnDirectionResponseListener() {
public void onResponse(String status, Document doc, GoogleDirection gd) {
mDoc = doc;
myMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
myMap.addMarker(new MarkerOptions().position(start)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
myMap.addMarker(new MarkerOptions().position(end)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
}
});
buttonRequest = (Button)findViewById(R.id.routereq);
buttonRequest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setVisibility(View.GONE);
gd.setLogging(true);
gd.request(start, end, GoogleDirection.MODE_DRIVING);
}
});
new QuerySpotsOperation().execute("");
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences settings = getSharedPreferences("cityhallprefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putLong("camlat", Double.doubleToLongBits(myMap.getCameraPosition().target.latitude));
editor.putLong("camlng", Double.doubleToLongBits(myMap.getCameraPosition().target.longitude));
editor.commit();
}
private void moveCamera(double latit, double longit) {
if(latit!= 0 || longit != 0) {
LatLng coordinate = new LatLng(latit, longit);
CameraUpdate updt = CameraUpdateFactory.newLatLngZoom(coordinate, 6);
myMap.animateCamera(updt);
}
}
class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
sourceLatitude = loc.getLatitude();
sourceLongitude = loc.getLongitude();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
to get the Lat Lon of the marker who was clicked:
#Override
public View getInfoWindow(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.infowindow,null);
Spot markerSpot = spots.get(arg0.getPosition().toString());
double Lat = markerSpot.getLatitude();
double Lon = markerSpot.getLongitude();
destLatitude = Lat;
destLongitude = Lon;
return v;
} else {
return null;
}
"LatLng start" and "LatLng end" are everytime 0 if i try to get it with sourceLatitude, sourceLongitude.
i hope anyone can help me to solve the problem and sorry for my bad english :)
You can get your current location LatLon:
....
myMap.setMyLocationEnabled(true);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = mlocManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = mlocManager.getLastKnownLocation(provider);
//get Lat Lon
Double lat = myLocation.getLatitude();
Double lon = myLocation.getLongitude();
....
i found a solution for my problem.
i set LatLng start and LatLng end in onResponse and onClick and now it works :)
gd = new GoogleDirection(this);
gd.setOnDirectionResponseListener(new OnDirectionResponseListener() {
public void onResponse(String status, Document doc, GoogleDirection gd) {
LatLng start = new LatLng(sourceLatitude, sourceLongitude);
LatLng end = new LatLng(destLatitude, destLongitude);
mDoc = doc;
myMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
myMap.addMarker(new MarkerOptions().position(start)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
myMap.addMarker(new MarkerOptions().position(end)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
}
});
buttonRequest = (Button)findViewById(R.id.routereq);
buttonRequest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LatLng start = new LatLng(sourceLatitude, sourceLongitude);
LatLng end = new LatLng(destLatitude, destLongitude);
v.setVisibility(View.GONE);
gd.setLogging(true);
gd.request(start, end, GoogleDirection.MODE_DRIVING);
}
});
I have an app which calculates distance and speed by gps
the speed is working well
but the distance always equals to zero !!
at first i didn't initialize float[] dist by zero .. but it crashed once gps was found !
that's the code
public class Main_Activity extends Activity {
TextView tvdistance;
TextView tvSpeed;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance = 0;
float[] dist = {
0, 0, 0
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
tvdistance = (TextView) findViewById(R.id.tvdistance);
tvSpeed = (TextView) findViewById(R.id.tvspeed1);
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);
Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc == null) {
tvdistance.setText("No GPS location found");
}
else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
}
// Set the last latitude and longitude
lastLat = currentLat;
lastLon = currentLon;
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
// Get last location
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Request new location
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
if (currentLat != 0 && currentLon != 0) {
Location.distanceBetween(currentLat, currentLon, location.getLatitude(),
location.getLongitude(), dist);
distance += (long) dist[0];
}
currentLat = location.getLatitude();
currentLon = location.getLongitude();
float speed = location.getSpeed();
tvSpeed.setText("Speed = " + speed / 1000 * 60 * 60 + "Km/h");
tvdistance.setText("Distance = " + distance);
}
#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
}
};
}
As you have just gotten a location fix, I fully expect the location returned from getLastKnownLocation to be the same as what you get in location. This means that your distance between the two is correctly 0. If you want your older location, you'll need to store that yourself.
Here is the complete code to get location updates from a GPS provider
public class MainActivity extends Activity {
private GoogleMap googleMap;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1
// meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000; // 1
// second
// Declaring a Location Manager
protected LocationManager locationManager;
// The alert dialog to enable GPS
private Dialog alertDialog;
// flag for GPS status
boolean isGPSEnabled = false;
Location location; // location
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onStart()
*/
#Override
protected void onStart() {
// fetching your current location
super.onStart();
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
if (googleMap != null) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
}
// Getting current location and adding the marker
locateMe();
}
/**
*
*/
private void locateMe() {
// Checking for GPS Enabled
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
// GPS is disabled
askUserToEnableGPS();
}
}
/**
*
*/
private void askUserToEnableGPS() {
// Asking user to enable GPS
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Chain together various setter methods to set the dialog
// characteristics
builder.setMessage(R.string.generic_gps_not_found)
.setTitle(R.string.generic_gps_not_found_message_title)
.setPositiveButton(R.string.generic_yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected yes
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton(R.string.generic_no,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected no
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onResume()
*/
#Override
protected void onResume() {
// Getting location from GPS
super.onResume();
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, listener);
Log.e("GPS Enabled", "GPS Enabled");
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// Setting the marker
if (googleMap == null || location == null) {
return;
} else {
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
location.getLatitude(), location.getLongitude())));
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 3000ms
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
}, 1000);
Marker myLocation = googleMap.addMarker(new MarkerOptions()
.position(
new LatLng(location.getLatitude(), location
.getLongitude()))
.title("Me")
.snippet("I am here")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
}
locationManager.removeUpdates(listener);
locationManager = null;
}
};
}
Now you can use various methods to store your location. Following are some ways:
Shared preferences
SQLite Database
Web Server
Saving in a file
You can refer this link.
i am developing one application in that i want to show my current location in the map,it shows but if i change location its shows previous location please tell me in my code mistake
my code
public class GetLatLongForTPActivity extends FragmentActivity implements LocationListener{
GoogleMap _googleMap;
static final LatLng SEC = new LatLng(17.433189,78.502223);
static final LatLng Safilguda = new LatLng(17.464166,78.536156);
static final LatLng Fathe = new LatLng(17.455932,78.450132);
LatLng myPosition;
LatLongDetails latLongDetails = new LatLongDetails();;
private EditText timeEdit;
private Button submitBtn;
private Button cancelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_lat_long_for_tp);
timeEdit = (EditText)findViewById(R.id.timeId);
submitBtn = (Button)findViewById(R.id.subId);
/*Intent intent = getIntent();
String anotherLAT=intent.getStringExtra("LAT");
String anotherLNG=intent.getStringExtra("LNG");
*/
ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>)
getIntent().getSerializableExtra("arrayList");
Log.e(" NEW LATLONG1",arl.get(0).toString());
Log.e(" NEW LATLONG2",arl.get(1).toString());
Log.e(" NEW LATLONG3",arl.get(2).toString());
_googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
if(_googleMap==null){
Toast.makeText(getApplicationContext(), "Google Map Not Available", Toast.LENGTH_LONG).show();
}
LocationManager locationManger = (LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria=new Criteria();
Marker perth = _googleMap.addMarker(new MarkerOptions()
.position(SEC)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));
/*Marker Safilg = _googleMap.addMarker(new MarkerOptions()
.position(Safilguda)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));
Marker Saf = _googleMap.addMarker(new MarkerOptions()
.position(Fathe)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));*/
String provider = locationManger.getBestProvider(criteria, true);
Location location = locationManger.getLastKnownLocation(provider);
if(location!=null){
double latitude = location.getLatitude();
double langitude = location.getLongitude();
latLongDetails.setLat(latitude);
latLongDetails.setLongi(langitude);
Log.e("lat",""+ latLongDetails.getLat());
Log.e("long", ""+latLongDetails.getLongi());
LatLng latlang = new LatLng(latitude, langitude);
LatLngBounds curScreen = _googleMap.getProjection().getVisibleRegion().latLngBounds;
curScreen.contains(latlang);
myPosition = new LatLng(latitude, langitude);
_googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
_googleMap.addMarker(new MarkerOptions().position(myPosition).title("start"));
//_googleMap.setOnMarkerClickListener(GetLatLongForTPActivity.this);
submitBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String
clreatime=timeEdit.getText().toString().trim();
latLongDetails.setClearTime(clreatime);
Log.e("time",
latLongDetails.getClearTime());
new
SendLatLongValAsync(GetLatLongForTPActivity.this).execute(latLongDetails);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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
}
Setup your Activity like below:
public class BasicMapActivity_new extends FragmentActivity implements LocationListener {
private GoogleMap mMap;
private LocationManager locationManager;
private String provider;
Double Latitude,longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2)).getMap();
mMap.setMyLocationEnabled(true);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(BasicMapActivity_new.this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else if(!enabledWiFi){
Toast.makeText(BasicMapActivity_new.this, "Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
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) {
onLocationChanged(location);
} else {
//do something
}
setUpMap();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2))
.getMap();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setTiltGesturesEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
}
Marker startPerc=null;
Location old_one;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng)
startPerc = mMap.addMarker(new MarkerOptions()
.position(coordinate)
.title("Current Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 18.0f))
}
#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
}
}
And do not forget to add permission into manifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You have used getLastKnownLocation() method while fetching the location details. This method always returns the last know co-ordinates. So, I suggest you to commenting this line Location location = locationManger.getLastKnownLocation(provider); from your code. Then it will run properly.
To update your location you have to register your Location Listener to location manager. And use override method onLocationChanged() to get latest location.
Please refer http://developer.android.com/guide/topics/location/strategies.html
I am writing an app in which I have to store data in a file for accelerometer values. How do I do that ? I have to create a file only once and append the data in that file. This is the flow of application:
User click on start button, it should start writing sensor data to file.
User click on stop button, it should stop writing the data to the file.
Plz help ..
Edit 1: code according to #iTech but it does not append data.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import app.AccelLocData;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
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.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapViewActivity extends Activity implements LocationListener,
SensorEventListener, OnClickListener {
GoogleMap googleMap;
private boolean started = false;
private ArrayList<AccelLocData> sensorData;
private SensorManager sensorManager;
private Button btnStart, btnStop;
private String provider;
File root, dir, sensorFile;
FileOutputStream fOut;
// ObjectOutputStream myOutWriter;
private Sensor mAccelerometer;
private FileWriter writer;
// private Button btnUpload;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
root = android.os.Environment.getExternalStorageDirectory();
dir = new File(root.getAbsolutePath() + "/myapp");
dir.mkdirs();
File oldFile = new File(dir, "data.txt");
boolean deleted = oldFile.delete();
System.out.println("Delete status = " + deleted);
sensorFile = new File(dir, "data.txt");
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services
// are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
this, requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment of
// activity_main.xml
// SupportMapFragment supportMapFragment = (MapFragment)
// getFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
// googleMap = supportMapFragment.getMap();
// can use for overlay on the map
List<Double> latList = new ArrayList<Double>();
latList.add(45.7309593);
latList.add(46.34);
latList.add(47.34);
List<Double> lonList = new ArrayList<Double>();
lonList.add(-122.6365384);
lonList.add(-123.6365384);
lonList.add(-124.6365384);
for (int i = 0; i < 3; i++) {
// LatLng latLng = new LatLng(45.7309593, -122.6365384);
LatLng latLng = new LatLng(latList.get(i).doubleValue(),
lonList.get(i).doubleValue());
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap
.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : "
+ latLng.longitude);
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
});
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager
.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager
.requestLocationUpdates(provider, 20000, 0, this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void onSensorChanged(SensorEvent event) {
if (started) {
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
long timestamp = System.currentTimeMillis();
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locManager.getBestProvider(criteria, true);
Location location = locManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
AccelLocData data = new AccelLocData(timestamp, x, y, z, latitude,
longitude);
System.out.println("data x:" + data.getX());
try {
writer.write(data.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// System.out.println("Latitude:" + latitude + ", Longitude:" +
// longitude);
// Setting latitude and longitude in the TextView tv_location
// tvLocation.setText("Latitude:" + latitude + ", Longitude:" +
// longitude);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
btnStart.setEnabled(false);
btnStop.setEnabled(true);
System.out.println("cam on click of start");
started = true;
sensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_FASTEST);
break;
case R.id.btnStop:
try {
btnStart.setEnabled(true);
btnStop.setEnabled(false);
// btnUpload.setEnabled(true);
started = false;
sensorManager.unregisterListener(this);
/*
* if(writer != null) { try { writer.close(); } catch
* (IOException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } }
*/} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
}
protected void onPause() {
super.onPause();
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
protected void onResume() {
super.onResume();
try {
System.out.println("called onresume");
writer = new FileWriter(sensorFile, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onProviderDisabled(String arg0) {
// 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 void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
}
Here is an example code for you to get started.
You can check android samples to learn how to read data from sensors and then just write it to a file.
To run this code, you will need to add two buttons and set their onClick to onStartClick and onStopClick. Also you can specify the output file path to be on the SD card.
public class Main extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private FileWriter writer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activiy_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
public void onStartClick(View view) {
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);
}
protected void onResume() {
super.onResume();
writer = new FileWriter("myfile.txt",true);
}
protected void onPause() {
super.onPause();
if(writer != null) {
writer.close();
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
writer.write(x+","+y+","+z+"\n");
}
}