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.
Related
public void pointLocation(){
if(gmap!=null){
gmap.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latlng) {
// TODO Auto-generated method stub
double lat = latlng.latitude;
double lng = latlng.longitude;
mVisible=gmap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)));
Toast.makeText(getApplicationContext(), "Latitude :"+" "+lat+"Longitude :"+" "+lng, Toast.LENGTH_LONG).show();
}
});
mVisible.setVisible(false);//marker setVisible off so that old marker get destroy and new get appear
}
}
package com.sample;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.sample.R;
public class MainActivity extends FragmentActivity {
GoogleMap gmap;
// GPSTracker gpsTracker;
SupportMapFragment mapFragment;
Marker mVisible;
boolean checkCall = true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.selectlocation);
// gpsTracker = new GPSTracker(this);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.maplocation);
userPosition();
pointLocation();
}
public void userPosition() {
gmap = mapFragment.getMap();
if (gmap != null) {
// if (gpsTracker.canGetLocation()) {
// double latCurrentloc = gpsTracker.getLatitude();
// double lngCurrentloc = gpsTracker.getLongitude();
LatLng pointer = new LatLng(17.2145632, 8.2345876);
gmap.addMarker(new MarkerOptions().position(pointer).title(
"Hello world"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(pointer).zoom(12).build();
gmap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// }
}
}
public void pointLocation() {
if (gmap != null) {
// mVisible.setVisible(true);
gmap.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latlng) {
if (checkCall) {
double lat = latlng.latitude;
double lng = latlng.longitude;
mVisible = gmap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng)));
Toast.makeText(
getApplicationContext(),
"Latitude :" + " " + lat + "Longitude :" + " "
+ lng, Toast.LENGTH_LONG).show();
checkCall = false;
}
}
});
}
}
}
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;
}
}
}
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..
This is my Map Activity class and i have to extract the current location lat n long points and have to show them on map.And i also have incorporated a search box which will display the location of an address on map. Its showing the location but at difference of 200 meter. And when i reopen it, it always show the previous traced location or searched location. I want to show the extracted lat n long points on map.Please Help me out. Thanks in advance..
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MapViewActivity extends MapActivity implements LocationListener {
private MapView mapView;
Button search;
EditText address;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search=(Button)findViewById(R.id.find_loc);
address=(EditText)findViewById(R.id.enter_address);
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
address=(EditText)findViewById(R.id.enter_address);
if (address.getText().toString().trim().length() == 0) {
showMessage("Error", "Please enter address!");
return;
}
Geocoder geoCoder = new Geocoder(MapViewActivity.this,
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
address.getText().toString(), 1);
// Getting latitude
double latitude = addresses.get(0).getLatitude();
// Getting longitude
double longitude = addresses.get(0).getLongitude();
if (addresses.size() > 0) {
GeoPoint p = new GeoPoint(
(int) ( latitude * 1E6),
(int) (longitude * 1E6));
// Getting MapController
MapController mapController =
mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(p);
//Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the
image of mark in the map
Drawable drawable =
MapViewActivity.this.getResources().getDrawable(R.drawable.cur_position);
// Creating an instance of ItemizedOverlay to mark
the current location in the map
CurrentLocationOverlay currentLocationOverlay = new
CurrentLocationOverlay(drawable);
// Creating an item to represent a mark in the
overlay
OverlayItem currentLocation = new OverlayItem(p,
"Current Location", "Latitude : " + latitude + ", Longitude:" + longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
} catch (IOException e) {
e.printStackTrace();
}
catch(Exception e)
{
showMessage("Error", "Address not found!");
e.printStackTrace();
}
}
});
// Getting reference to MapView
mapView = (MapView) findViewById(R.id.map_view);
// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
//Criteria criteria = new Criteria();
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onBackPressed() {
finish();
}
#Override
public void onDestroy() {
if (locationManager != null) {
locationManager.removeUpdates(this);
}
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
// Setting latitude and longitude in the TextView tv_location
//tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude
);
// Creating an instance of GeoPoint corresponding to latitude and longitude
GeoPoint point = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));
// Getting MapController
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point);
// Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the image of mark in the map
Drawable drawable =
this.getResources().getDrawable(R.drawable.cur_position);
// Creating an instance of ItemizedOverlay to mark the current location in
the map
CurrentLocationOverlay currentLocationOverlay = new
CurrentLocationOverlay(drawable);
// Creating an item to represent a mark in the overlay
OverlayItem currentLocation = new OverlayItem(point, "Current Location",
"Latitude : " + latitude + ", Longitude:" + longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
private void showMessage(final String title, final String message) {
runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder alert = new AlertDialog.Builder(MapViewActivity.this);
alert.setTitle(title);
alert.setPositiveButton("OK", null);
alert.setMessage(message);
alert.show();
}
});
}
#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 this is my CurrentLocationOverlay class
package com.ceolution.bhinstitute.crm;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import android.util.Log;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class CurrentLocationOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public CurrentLocationOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
// Executed, when populate() method is called
#Override
protected OverlayItem createItem(int arg0) {
return mOverlays.get(arg0);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay){
mOverlays.add(overlay);
populate(); // Calls the method createItem()
}
#Override
protected boolean onTap(int arg0) {
Log.d("Tapped", mOverlays.get(arg0).getSnippet());
return true;
}
}
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
String provider;
if(!isGPSEnabled)
{
provider = LocationManager.NETWORK_PROVIDER;
}
else
provider=LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(provider, 20000, 0, this);
use above code after
// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);
hope this will help and also you can give alert to user to enable gps.
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");
}
}