Android Accelerometer store data in file - android

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

Related

The method fromPixels(int, int) is undefined for the type Projection & The method getLatitudeE6() is undefined for the type GeoPoint

It is not working on fromPixels() & on getLatitudeE6() *getLongitudeE6()* at
public boolean onTouchEvent(MotionEvent event, MapView mapView)
method,which is situated at the last portion of this code.Can any one help plz.....
package com.mamun.tasktest;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
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 MapActivity<GeoPoint, OverlayItem> extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
private LocationManager manager;
private TextView tvAddress;
private Button btnSearch;
private EditText etSearch;
private LocationClient locationClient;
private GoogleMap googleMap;
private MapFragment mapFragment;
//private GeoPoint p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
tvAddress = (TextView) findViewById(R.id.tvaddress);
btnSearch = (Button) findViewById(R.id.btnSearch);
etSearch = (EditText) findViewById(R.id.etSearch);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(
R.id.maps);
googleMap = mapFragment.getMap();
locationClient = new LocationClient(this, this, this);
}
public void onSearch(View v) {
// Getting user input location
String location = etSearch.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationClient.connect();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationClient.disconnect();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location currentLocation = locationClient.getLastLocation();
double lat = currentLocation.getLatitude();
double lng = currentLocation.getLongitude();
// txtLocation.setText(lat + ", " + lng);
Geocoder geocoder = new Geocoder(this);
ArrayList<Address> address = (ArrayList<Address>) geocoder
.getFromLocation(currentLocation.getLatitude(),
currentLocation.getLongitude(), 5);
Address addr = address.get(0);
String currentAddress = (addr.getAddressLine(0) + "-"
+ addr.getAdminArea() + "-" + addr.getLocality() + "-"
+ addr.getPostalCode() + "-" + addr.getCountryCode());
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(lat, lng));
options.title(currentAddress);
options.snippet("Current location");
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
if (googleMap != null) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lat, lng), 14.0f));
googleMap.addMarker(options);
} else {
Toast.makeText(getApplicationContext(), "Map is null",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends
AsyncTask<String, Void, ArrayList<Address>> {
#Override
protected ArrayList<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
ArrayList<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = (ArrayList<Address>) geocoder.getFromLocationName(
locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(ArrayList<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found",
Toast.LENGTH_SHORT).show();
return;
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
LatLng latLng;
latLng = new LatLng(address.getLatitude(),
address.getLongitude());
String addressText = String.format(
"%s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address
.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
// markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0)
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
}
}
}
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
/*................. Add this method ........*/
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1) {
GeoPoint geopoint = googleMap.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
// latitude
double lat = (geopoint).getLatitudeE6() / 1E6;
// longitude
double lon = (geopoint).getLongitudeE6() / 1E6;
Toast.makeText(getBaseContext(), "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
}
return false;
}
}
}

get address corresponding to lattitude and longitude in google map api v2

Hi in my application i am getting the lattitude and longitude of a location.I want to convert that points into address, when i try to do so iam getting error
java.io.IOException: Service not Available at android.location.Geocoder.getFromLocation(Geocoder.java:136)
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
public class MapActivity extends FragmentActivity {
private GoogleMap map;
//Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GpsMapLocationActivity();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
private class GpsMapLocationActivity implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
/*final GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));*/
/* String address = ConvertPointToLocation(point);address.toString();
Log.i("ADRESSS", ""+point);*/
double latitude=location.getLatitude();
double longitude=location.getLongitude();
LatLng loca=new LatLng(latitude,longitude);
String address = ConvertPointToLocation(loca);
address.toString();
Toast.makeText(getApplicationContext(),"" +loca,
Toast.LENGTH_LONG).show();
Log.i("Adress",""+address);
CameraPosition cmp= new CameraPosition.Builder().target(loca).zoom(14).bearing(90).tilt(30).build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cmp));
MarkerOptions marker = new MarkerOptions()
.position(loca)
.title("MyMap")
.snippet("My Map View")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_gps));
map.addMarker(marker);
}
}
private String ConvertPointToLocation(LatLng loca) {
// TODO Auto-generated method stub
String address = "";
Geocoder geoCoder=new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
loca.latitude ,
loca.longitude, 1);
if (addresses.size() > 0) {
for (int index = 0;
index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
#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 am tried some codes but the error is repeating
plz help me thanks in advance..

Convert Latitude and longitude value to address in google map api v2

In my application i am getting the latitude and longitude value, i want it to convert into corresponding address.But when i do so i am getting error
java.io.IOException: Service not Available at android.location.Geocoder.getFromLocation(Geocoder.java:136)
This is my code
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
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.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
public class MapActivity extends FragmentActivity {
private GoogleMap map;
//Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GpsMapLocationActivity();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
private class GpsMapLocationActivity implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
/*final GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));*/
/* String address = ConvertPointToLocation(point);address.toString();
Log.i("ADRESSS", ""+point);*/
double latitude=location.getLatitude();
double longitude=location.getLongitude();
LatLng loca=new LatLng(latitude,longitude);
String address = ConvertPointToLocation(loca);
address.toString();
Toast.makeText(getApplicationContext(),"" +loca,
Toast.LENGTH_LONG).show();
Log.i("Adress",""+address);
CameraPosition cmp= new CameraPosition.Builder().target(loca).zoom(14).bearing(90).tilt(30).build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cmp));
MarkerOptions marker = new MarkerOptions()
.position(loca)
.title("MyMap")
.snippet("My Map View")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_gps));
map.addMarker(marker);
}
}
private String ConvertPointToLocation(LatLng loca) {
// TODO Auto-generated method stub
String address = "";
Geocoder geoCoder=new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
loca.latitude ,
loca.longitude, 1);
if (addresses.size() > 0) {
for (int index = 0;
index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
#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
}
}
}
Thanks in advance..
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
myMap = fm.getMap();
// myMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
final Location location = locationManager
.getLastKnownLocation(provider);
latitude = location.getLatitude();
longitude = location.getLongitude();
latLng = new LatLng(latitude, longitude);
Geocoder geocoder = new Geocoder(MainActivity.this,
Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
add = addresses.get(0).getAddressLine(0);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentloc = myMap.addMarker(new MarkerOptions()
.position(latLng)
.title(add)
.snippet("" + latitude + "," + "" + longitude)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.locdot)));
myMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
myMap.animateCamera(CameraUpdateFactory.zoomTo(11), 2000, null);
loc = (ImageButton) findViewById(R.id.loc);
loc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (location != null) {
onLocationChanged(location);
}
}
});
locationManager.requestLocationUpdates(provider, 20000, 0, this);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
myMap = fm.getMap();
// myMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
final Location location = locationManager
.getLastKnownLocation(provider);
latitude = location.getLatitude();
longitude = location.getLongitude();
latLng = new LatLng(latitude, longitude);
Geocoder geocoder = new Geocoder(MainActivity.this,
Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
add = addresses.get(0).getAddressLine(0);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentloc = myMap.addMarker(new MarkerOptions()
.position(latLng)
.title(add)
.snippet("" + latitude + "," + "" + longitude)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.locdot)));
myMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
myMap.animateCamera(CameraUpdateFactory.zoomTo(11), 2000, null);
loc = (ImageButton) findViewById(R.id.loc);
loc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (location != null) {
onLocationChanged(location);
}
}
});
locationManager.requestLocationUpdates(provider, 20000, 0, this);
You need reboot your device and Geocoder will work.

Location not updating

I have succeed in making a map that shows nearby locations but its not updating the locations...Is there something wrong with the code..coz i m not finding anythin wrong...any help wud be appreciated..thanks in advance
package com.example.travelplanner;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class NearbyPlacesActivity extends Activity implements LocationListener {
//instance variables for Marker icon drawable resources
private int userIcon, foodIcon, drinkIcon, shopIcon, otherIcon;
//the map
private GoogleMap theMap;
//location manager
private LocationManager locMan;
//user marker
private Marker userMarker;
//places of interest
private Marker[] placeMarkers;
//max
private final int MAX_PLACES = 20;//most returned from google
//marker options
private MarkerOptions[] places;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_places);
//get drawable IDs
userIcon = R.drawable.yellow_point;
foodIcon = R.drawable.red_point;
drinkIcon = R.drawable.blue_point;
shopIcon = R.drawable.green_point;
otherIcon = R.drawable.purple_point;
//find out if we already have it
if(theMap==null){
//get the map
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
//check in case map/ Google Play services not available
if(theMap!=null){
//ok - proceed
theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//create marker array
placeMarkers = new Marker[MAX_PLACES];
}
}
}
//location listener functions
#Override
public void onLocationChanged(Location location) {
Log.v("MyMapActivity", "location changed");
updatePlaces(location);
}
#Override
public void onProviderDisabled(String provider){
Log.v("MyMapActivity", "provider disabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.v("MyMapActivity", "provider enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v("MyMapActivity", "status changed");
}
/*
* update the place markers
*/
private void updatePlaces(Location givenlocation){
//get location manager
double lat = givenlocation.getLatitude();
double lng = givenlocation.getLongitude();
Toast.makeText(getApplicationContext(), lat+","+lng, Toast.LENGTH_LONG).show();
//create LatLng
LatLng lastLatLng = new LatLng(lat, lng);
//remove any existing marker
if(userMarker!=null) userMarker.remove();
//create and set marker properties
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
//move to location
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
//build places query string
#SuppressWarnings("deprecation")
String encodedstr = URLEncoder.encode("food|bar|movie_theater|museum|bank");
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=7000&sensor=true"+
"&types="+encodedstr+
"&key=AIzaSyBqDgqbxFenOtooTivY5YSsJ2JrwBK42hw";//ADD KEY
//execute query
new GetPlaces().execute(placesSearchStr);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... placesURL) {
//fetch places
//build result as string
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
//HTTP Get receives URL string
HttpGet placesGet = new HttpGet(placeSearchURL);
//execute GET with Client - return response
HttpResponse placesResponse = placesClient.execute(placesGet);
//check response status
StatusLine placeSearchStatus = placesResponse.getStatusLine();
//only carry on if response is OK
if (placeSearchStatus.getStatusCode() == 200) {
//get response entity
HttpEntity placesEntity = placesResponse.getEntity();
//get input stream setup
InputStream placesContent = placesEntity.getContent();
//create reader
InputStreamReader placesInput = new InputStreamReader(placesContent);
//use buffered reader to process
BufferedReader placesReader = new BufferedReader(placesInput);
//read a line at a time, append to string builder
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
//process data retrieved from doInBackground
protected void onPostExecute(String result) {
//parse place data returned from Google Places
//remove existing markers
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
try {
//parse JSON
//create JSONObject, pass stinrg returned from doInBackground
JSONObject resultObject = new JSONObject(result);
//get "results" array
JSONArray placesArray = resultObject.getJSONArray("results");
//marker options for each place returned
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
//if any values are missing we won't show the marker
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
//get place at this index
JSONObject placeObject = placesArray.getJSONObject(p);
//get location section
JSONObject loc = placeObject.getJSONObject("geometry")
.getJSONObject("location");
//read lat lng
placeLL = new LatLng(Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
//get types
JSONArray types = placeObject.getJSONArray("types");
//loop through types
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
//check for particular types - set icons
if(thisType.contains("food")){
currIcon = foodIcon;
break;
}
else if(thisType.contains("bar")){
currIcon = drinkIcon;
break;
}
else if(thisType.contains("movie_theater")){
currIcon = shopIcon;
break;
}
}
//vicinity
vicinity = placeObject.getString("vicinity");
//name
placeName = placeObject.getString("name");
}
catch(JSONException jse){
Log.v("PLACES", "missing value");
missingValue=true;
jse.printStackTrace();
}
//if values missing we don't display
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=theMap.addMarker(places[p]);
}
}
}
}
#Override
protected void onResume() {
super.onResume();
if(theMap!=null){
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
updatePlaces(lastLoc);
}
}
#Override
protected void onPause() {
super.onPause();
if(theMap!=null){
locMan.removeUpdates(this);
}
}
}
Please try to use this class.
public class LocationListenerClass {
private static LocationListenerClass instance;
private static Context context;
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private static Double latitude = 0d;
private static Double longitude = 0d;
public static LocationListenerClass getInstance(Context context) {
LocationListenerClass.context = context;
if (null == instance) {
instance = new LocationListenerClass();
}
return instance;
}
public void getCurrentLocation() {
try {
myLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 30000, 100,
myLocationListener);
Location location;
location = myLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
myLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 30000, 100,
myLocationListener);
location = myLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
try {
latitude = location.getLatitude();
Data.CURENT_LATITUDE = latitude;
Log.v(ConstantLib.LOG, " latitude : "
+ Data.CURENT_LATITUDE);
longitude = location.getLongitude();
Data.CURENT_LONGITUDE = longitude;
Log.v(ConstantLib.LOG, " longitude : "
+ Data.CURENT_LONGITUDE);
} catch (Exception e) {
}
}
} catch (Exception e) {
}
}
public void removeLocationUpdates() {
try {
if (myLocationManager != null) {
myLocationManager.removeUpdates(myLocationListener);
}
} catch (Exception e) {
}
}
class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
try {
if (location != null) {
Data.CURENT_LATITUDE = location.getLatitude();
Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " latitude : "
+ Data.CURENT_LATITUDE);
longitude = location.getLongitude();
Data.CURENT_LONGITUDE = location.getLongitude();
Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " longitude : "
+ Data.CURENT_LONGITUDE);
}
} catch (Exception e) {
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}

move marker on google maps api 2

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

Categories

Resources