Retrieve user current location using Google play service in not working - android

I'm using new Google API for retrieving current location, and I got the current location. However, if the location services are not enabled in the app by default, and if I enable any location service using location intend, the client does not reconnect, in onActivityResult method, and I cannot fetch the current location.
public void onConnected(Bundle bundle) {
// TODO Auto-generated method stub
System.out.println(R.string.connected);
System.out.println("error");
startPeriodicUpdates();
if (mUpdatesRequested) {
startPeriodicUpdates();
}
if (!locationServiceEnabled)
return;
if(mLocationClient.isConnected()&& servicesConnected())
{
fetchlocation = new FetchingLocation(getActivity());
// mLocationClient = new LocationClient(getActivity(), this,this );
Location currentLocation = mLocationClient.getLastLocation();
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>" +
mLocationClient.getLastLocation());
latitude=currentLocation.getLatitude();
System.out.println(currentLocation.getLatitude());
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
+ String.valueOf(latitude));
}
else
{
}
}
But I can't get the location. As the app crashes, it shows the error:
client not connected wait for connect
Any ideas on how to solve this issue?

You have to get longitude and latitude value and then juste use that function
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 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;
}
Refer to this tutorial
http://www.codeproject.com/Articles/112044/GPSLocator-App-to-Find-Current-Nearest-Location-us

public void setLatLong(double lat, double lng) {
Longitude = lng;
Latitude = lat;
}
public double getLatitude() {
return Latitude;
}
public double getLongitude() {
return Longitude;
}
public void getLocation() {
locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Utility obj = new Utility(context);
if (obj.isGPSAvailable() && obj.isInternetAvailable())
{
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, locListener);
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0, 0, locListener);
}
else
Toast.makeText(context, "Internet or GPS not available",
Toast.LENGTH_LONG).show();
if (locManager != null)
{
Location loc = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc!=null)
{
setLatLong(loc.getLatitude(), loc.getLongitude());
}
else
{
loc = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(loc!=null)
{
setLatLong(loc.getLatitude(), loc.getLongitude());
}
}
}
}
Use above code for retrieving current location and you could get more help # following link:
http://www.vogella.com/articles/AndroidGoogleMaps/article.html

Related

Get user country by using Wi-Fi

I am looking for a way to get the user's country by using the Wi-Fi.
So far I have managed to do it using TelephonyManager and the SIM card, like this
TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String s = telephonyManager.getSimCountryIso();
This works ok, but the problem is, the user may not have a sim card (a tablet), so I also need to be able to determine the country by using the Wi-Fi they are connected to.
I tried this code, but its not working as I want it to, I simply want a country code, like US, UK, DE, instead this method returns GPS coordinates...
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.v("LOCATION", location.getProvider());
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
How can I get the country using the Wi-Fi?
You require to do reverse geocoding, i.e. converting location you get to address. For this you can use Geocoder
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1); //1 - is number of result you want you write it any integer value. But as you require country name 1 will suffice.
if (addresses.size() > 0)
System.out.println(addresses.get(0).getCountryName());
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
This can be done with GeoCoder, heres a snippet of code for checking WiFi and obtaining location info:
public Location getLocation() {
try {
// any location
// Getting network status
Log.e("GPS Service", "Get Location Called");
isNetworkEnabled = mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.e("GPS Service", String.valueOf(isNetworkEnabled));
if (isNetworkEnabled) {
Log.e("GPS Service", "Yay Wifi Enabled");
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
Log.e("GPS Service", "Yay Location");
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If reaching here means, we were not able to get location neither
// from GPS not Network,
if (!isGPSEnabled) {
// so asking user to open GPS
//askUserToOpenGPS();
}
} catch (Exception e) {
e.printStackTrace();
}
// if reaching here means, location was not available, so setting the
// flag as false
isLocationAvailable = false;
return null;
}
public String getCountryCode() {
getLocation();
if (isLocationAvailable) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
mLatitude = getLatitude();
mLongitude = getLongitude();
addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
Log.e("returning", "tm");
//TelephonyManager tm = (TelephonyManager)mContext.getSystemService(mContext.TELEPHONY_SERVICE);
//return tm.getNetworkCountryIso();
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments "
+ Double.toString(mLatitude) + " , "
+ Double.toString(mLongitude)
+ " passed to address service";
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available), city, and
* country name.
*/
// Return the text
Log.e("returning", address.getCountryCode());
String countrycode;
if (address.getCountryCode() == null) {
countrycode = "null";
} else {
countrycode = address.getCountryCode();
}
return countrycode;
} else {
return "null";
}
} else {
//String locale = getResources().getConfiguration().locale.getCountry();
Log.e("returning", "wifi");
getJSON();
Log.e("ELSE", wifiCode);
return wifiCode;
}
}

Android fetch nearest locations or addresses of on google map according to a gps location

I need to fetch locations or addresses of nearest location of a current gps location to show on google map.Currently i am able to show some locaions on map but that are hardcoded i need to fetch all nearest location before drawing the map.
Is there any suggestion?
Here is the way, that how can you achieve it.
LocationManager locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
Double l1 = location.getLatitude();
Double l2 = location.getLongitude();
address = GetAddress(l1, l2);
}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
private String GetAddress(Double lat, Double lon) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
String ret = "";
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(lat, lon, 1);
if (!addresses.equals(null)) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("\n");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress
.append(returnedAddress.getAddressLine(i)).append(
"\n");
}
ret = "Around: " + strReturnedAddress.toString();
} else {
ret = "No Address returned!";
}
} catch (IOException e) {
e.printStackTrace();
ret = "Location: https://maps.google.co.in/maps?hl=en&q=" + lat
+ "," + lon;
} catch (NullPointerException e) {
e.printStackTrace();
ret = lat + "," + lon;
}
return ret;
}
And also add these permissions in AndroidManifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
First get your current location Lattitude & Longitude, then get Lattitude & Longitude of each locations you have and find out distance of each place from your current location using distanceTo method of Location class and after that find out least distance from your list.

Trouble calling and getting location in oncreate method from location listener android

i need your help regarding the location update in android. Following is my code for getting location update and it is working fine. But it returns invalid message body when i get the stored variable with location in oncreate method of main class. After thorough research it seems that the variable i called in oncreate method is empty. Can you please tell me how to get the address as it appears in onlocationChanged Method. Thank you!
Calling class with oncreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new Mylocation();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
String address1= listener.getAddress();
{
sendSms(phone, message, false);
} catch (Exception e) {
Log.i("Error Is ", e.toString());
}
}
location class:
class Mylocation implements LocationListener{
double lat, lon;
static final String address="";
public void onLocationChanged(Location location)
{
//...
lat = location.getLatitude();
lon = location.getLongitude();
address = GetAddressDetail(lat, lon);
Log.i("Messge is", address); //working here
}
public String getAddress(){ //not returning the address
return address;
}
public String GetAddressDetail(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
}
Make sure your variables are initialized properly. I don't see evidence of this in the question so I am just checking.
// Instantiation
Mylocation listener;
String phone;
String message;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
listener = new Mylocation(this);
phone = "";
message = "";
// These two lines aren't really necessary,
// this should be in your MyLocation class
//locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
// Add this line, we are going to initialize this class
// and make sure that address gets set
listener = new Mylocation();
String address1 = listener.getAddress();
try {
// If neither phone nor message is empty lets sendSms()
if (!phone.isEmpty() || !message.isEmpty()) {
sendSms(phone, message, false);
}
} catch (Exception e) {
Log.i("Error Is ", e.toString());
}
}
Change the String address to private and in the getter try return this.address;
class Mylocation implements LocationListener {
double lat, lon;
// Let's make this private so it can't be accessed directly,
// since you have the setter and getter.
private String address = "";
// Make sure you are overriding this method
#Override
public void onLocationChanged(Location location) {
/** ... */
lat = location.getLatitude();
lon = location.getLongitude();
address = GetAddressDetail(lat, lon);
Log.i("Messge is", address);
}
public String getAddress(){
return (address.isEmpty()) ? "Address not set" : this.address;
}
public String GetAddressDetail(Double lat2, Double lon2) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
}
Edit
I made changes to your code in my answer above, check the comments. I am also going to suggest additional methods for your MyLocation class:
class Mylocation implements LocationListener {
protected LocationManager locationManager;
private Context activityContext;
// The initializing method, this fires off first
// when a new instance of the class is created
public MyLocation(Context context) {
this.activityContext = context;
locationManager = (LocationManager) activityContext.getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);) {
locationManager.requestLocationUpdates(
NETWORK_PROVIDER,
MIN_TIME,
MIN_DISTANCE,
this
);
}
getLocation();
}
private double lat;
private double lon;
public double getLat() {
return this.lat;
}
public double getLng() {
return this.lng;
}
public void getLocation() {
if (location == null) {
locationManager.requestLocationUpdates(NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(NETWORK_PROVIDER);
if (location != null) {
// Set the coordinate variables
lat = location.getLatitude();
lon = location.getLongitude();
Log.i("Network", "Lat: " + latitude + " / Lng: " + longitude);
}
}
}
}
}
You are calling getAdress directly after you set the locationmanager to probe for a location. The onLocationChanged method probably hasn't been called yet when you call getAddress this way. I would recommend changing it to something like below to make sure it has been called:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new Mylocation();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,new LocationListener(){
#Override
public void onLocationChanged(Location location) {
//...
long lat = location.getLatitude();
long lon = location.getLongitude();
String address = GetAddressDetail(lat, lon);
//Do whatever you want to do with the address here, maybe add them to the message or something like that.
sendSms(phone, message, false);
}
});
}
public String GetAddressDetail(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}

Android GPS is returning null location

I have written code in that if GPS is disabled it will be enabled by code and try to get Location from gps but I am getting a null value. Below is my code
public void getValue() {
LocationManager mlocManager = (LocationManager) MySettings.this.getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
System.out.println("GPS IS "+gpsEnabled);
if (!gpsEnabled) {
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy");
try {
getBatteryLevel();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MySettings.this);
Location location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mLocation = location;
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
address = getAddress();
alt = location.getAltitude();
if (meterFootFlag) {
diameter = location.getAccuracy();
} else
diameter = location.getAccuracy() / 3.28084;
} else {
lat = 0.0;
lon = 0.0;
alt = 0.0;
}
} catch (Exception e) {
lat = 0.0;
lon = 0.0;
alt = 0.0;
}
Also I have added permission in manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
but I am getting a null value for the location.
Any ideas on how I can get the location?
Your code is correct just wait until GPs get altitude from a satellite it may take mroe than 1 minute.
try:
public Location showLocation(){
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Class model, save latitude and longitude
NavegadorCoordenadas locate = new NavegadorCoordenadas();
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = lm.getBestProvider(crit, false);
Location loc = getLastKnownLocation(lm);
locate.setLatitude(loc.getLatitude());
locate.setLongitude(loc.getLongitude());
return loc;
}
private Location getLastKnownLocation(LocationManager location) {
List<String> providers = location.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = location.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
Make sure that you are checking on DEVICE only.. In Emulator it will give Null Values for GPS as it is running in the system so it doesnot have permission for GPS
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10,
locationListener);
Now make MyLocationListener class in same activity.
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " +loc.getLongitude();
String latitude = "Latitude: " +loc.getLatitude();
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
System.out.println("MESSAGE:"+cityName);
}
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude+"\t city name:"+cityName;
Log.v("OUTPUT, s);
}
#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
}
}
Run your application in Actual device.
you can figure out that automatic start GPS and see console logcat.
Make sure to open Permissions through the
Settings--> Applications-->YourApp-->permissions
And another reason could be delay, it takes time to connect to network, somethimes more than a minute

android get current location name

I want to get the current location with name. I did coding for get current location (lat,lang), how can I show the relative place name?
(ie) 13.006389 - 80.2575 : Adyar,Chennai,India
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the location provider status changes. Possible status: OUT_OF_SERVICE, TEMPORARILY_UNAVAILABLE or AVAILABLE.
}
public void onProviderEnabled(String provider) {
// called when the location provider is enabled by the user
}
public void onProviderDisabled(String provider) {
// called when the location provider is disabled by the user. If it is already disabled, it's called immediately after requestLocationUpdates
}
public void onLocationChanged(Location location) {
double latitute = location.getLatitude();
double longitude = location.getLongitude();
// do whatever you want with the coordinates
}
});
This will convert the lat & lng into String Address and i have set it in the text field for your example. This is done by using the concept of Reverse Geocoding & there is a class called Geocoder in Android.
// Write the location name.
//
try {
Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
yourtextboxname.setText("Waiting for Location");
}
else {
yourtextboxname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
}
}
Here is code to get current location and draw it on Google Maps
public class Showmap extends MapActivity {
private MapView mapView;
private MapController mapController;
private LocationManager locationManager;
private LocationListener locationListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showmap);
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
mapView = (MapView) findViewById(R.id.mapView);
// enable Street view by default
mapView.setStreetView(true);
// enable to show Satellite view
// mapView.setSatellite(true);
// enable to show Traffic on map
// mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(16);
}
protected boolean isRouteDisplayed() {
return false;
}
private class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
mapController.animateTo(point);
mapController.setZoom(16);
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT)
.show();
mapView.invalidate();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(getBaseContext(),
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0)
.getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
Log.i(address, address);
}
} catch (IOException e) {
e.printStackTrace();
}
return address;
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider,int status,Bundle extras){}
}
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.marker);
// 24 is the height of image
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
Use reverse geocoding,feed the latitude and longitude and get the address.
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myAddress.setText("Canont get Address!");
}
The phrase you're looking for is "Reverse Geocoding". Another question on StackOverflow discusses the same topic- You can use that one's selected answer :)
This is only for Hint add your code !
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
System.out.println("in onlocationchanged");
String locationString=location.convert(location.getLatitude(),1);
Toast.makeText(this,"locationString=="+locationString, Toast.LENGTH_LONG).show();
double lat = location.getLatitude();
double lng = location.getLongitude();
String currentLocation = "The location is changed to Lat: " + lat + " Lng: " + lng;
Toast.makeText(this,currentLocation, Toast.LENGTH_LONG).show();
use this two method
public double getLattitude() {
return lattitude;
}
}
public double getLongitude() {
return longitude;
public class MainActivity extends AppCompatActivity {
double latitude, longitude;
private TextView tvLocation;
private Button btnGetLocation;
private FusedLocationProviderClient locationProviderClient;
private Geocoder geocoder;
private List<Address> addresses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
locationProviderClient = LocationServices.getFusedLocationProviderClient(this);
tvLocation = findViewById(R.id.tv_location);
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
btnGetLocation = findViewById(R.id.btn_location);
btnGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationProviderClient.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
tvLocation.setText(location.toString());
latitude = location.getLatitude();
longitude = location.getLongitude();
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String addressLine1 = addresses.get(0).getAddressLine(0);
Log.e("line1", addressLine1);
String city = addresses.get(0).getLocality();
Log.e("city", city);
String state = addresses.get(0).getAdminArea();
Log.e("state", state);
String pinCode = addresses.get(0).getPostalCode();
Log.e("pinCode", pinCode);
String fullAddress = addressLine1 + ", " + city + ", " + state + ", " + pinCode;
tvLocation.setText(fullAddress);
} catch (IOException e) {
e.printStackTrace();
Log.e("MainActivity", e.getMessage());
}
}
}
});
}
});
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
}
}
Here Is my code to get the current country Name.
private String getCountry() {
String country_name = null;
LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
#SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
country_name =addresses.get(0).getCountryName();
return country_name;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
return null;
}
But don't forget to add this permission in the manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Categories

Resources