I am using two methods for it getAddress() and address()..One to get latitude and and other one to get address from latitude and longitude..
public String getAddress(){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
latitude= location.getLatitude();
longitude= location.getLongitude();
try {
val = address(latitude, longitude);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText( CurrentLoc.this, val,
Toast.LENGTH_LONG).show();
return val;
}
Using another method to get address():
public String address(double lt,double lg) throws IOException{
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(lt, lg, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
return address +"\n"+ city +"\n"+ country;
}
To get current location on map using InitializeMap():
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(location.getLatitude(), location.getLongitude())).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Hello Maps ");
googleMap.addMarker(marker);
googleMap.isMyLocationEnabled();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
And the full code is following but the problem is that not getting address:
public class CurrentLoc extends Activity {
// latitude and longitude
static double latitude ;
static double longitude ;
// Google Map
private GoogleMap googleMap;
private LocationManager locationManager;
private Location location;
private String val,val1;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new3);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
val1 = getAddress();
// Loading map
initilizeMap();
}
/**
* function to load map. If map is not created it will create it for you
* */
public String getAddress(){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
latitude= location.getLatitude();
longitude= location.getLongitude();
try {
val = address(latitude, longitude);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText( CurrentLoc.this, val,
Toast.LENGTH_LONG).show();
return val;
}
public String address(double lt,double lg) throws IOException{
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(lt, lg, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
return address +"\n"+ city +"\n"+ country;
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(CurrentLoc.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(CurrentLoc.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(CurrentLoc.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(CurrentLoc.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(location.getLatitude(), location.getLongitude())).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Hello Maps ");
googleMap.addMarker(marker);
googleMap.isMyLocationEnabled();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mnew1, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.home:
openSearch();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openSearch(){
Intent intnt=new Intent(getApplicationContext(),SendSms.class);
intnt.putExtra("loct", val1);
startActivity(intnt);
}
}
First you have to do Googling:
Like This: Googling
You will get Following Link:
Displaying a Location Address
use the following code to get address using geocode. Make sure that you have INTERNET permission in your androidManifest.xml
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
StringBuilder stringBuilder = new StringBuilder();
if (addressList.size() > 0) {
Address address = addressList.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName()).append("\n");
}
addressString = stringBuilder.toString();
}
Related
I am working in a app with maps, in the first activity I have a NavigationDrawer with differents fragments, in one of them I get the last Location every 10 seconds and with it set a TextView with the address of that location. Everything was going perfect since I create a new Activity for details of a Place with a MapView and when you put a Marker it get its address, but it always return null I don´t know why..
There is my code.
1rst Activity with Fragment
public void setLocationListeners() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSION_LOCATION);
} else {
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location lastLocation = locationResult.getLastLocation();
Address address = getAddress(lastLocation.getLongitude(), lastLocation.getLatitude(), getContext());
myLocation = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
if (address == null) {
((TextView) mView.findViewById(R.id.txtVosEstas)).setText(String.valueOf(
lastLocation.getLongitude() + " " + lastLocation.getLatitude()));
} else
((TextView) mView.findViewById(R.id.txtVosEstas)).setText(address.getAddressLine(0).split(",")[0]);
((TextView) mView.findViewById(R.id.txtBearing)).setText(String.valueOf(lastLocation.getBearing()));
((TextView) mView.findViewById(R.id.txtVelocidad)).setText(String.valueOf(lastLocation.getSpeed()));
}
};
}
}
"getAddress" is the static method in my MapHelper
public static Address getAddress(double lng, double lat, Context c) {
Geocoder geocoder = new Geocoder(c, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
return addresses.get(0);
} catch (IOException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
}
return null;
}
I call the same method in the other Activity when the map is ready.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng));
String lat = String.format("%.7f", latLng.latitude);
String lng = String.format("%.7f", latLng.longitude);
((TextView) findViewById(R.id.txtLat)).setText(lat);
((TextView) findViewById(R.id.txtLng)).setText(lng);
Address address = getAddress(Double.valueOf(lat), Double.valueOf(lng), getApplicationContext());
((MultiAutoCompleteTextView) findViewById(R.id.txtDireccion)).setText(address != null? address.getAddressLine(0) : "Sin dirección");
}
});
if (mLugar != null){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLugar.getLatLng(), 15));
MarkerOptions marker = new MarkerOptions()
.position(mLugar.getLatLng())
.title(mLugar.getNombre());
mMap.addMarker(marker);
}
}
And in it I never get results.
public class AddNewLocationActivity extends Activity {
GoogleMap googleMap;
EditText edtLocation;
Marker marker;
List<Address> addressList = null;
VibRIngDatabase vibRIngDatabase;
double latitude, longitude;
Geocoder geocoder;
LatLng latLng;
String locationAddress, name, mode;
AlertDialog.Builder dialogBuilder;
double lati1, longi1;
TextView lat, longi, location_name;
RadioButton selectedModeRadioButton;
RadioGroup rg;
Button setMode;
int selectedId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addnewlocation);
createMapView();// Rendering the Google Map in the fragment
addMarkerAtCurrent(); // Adding marker at the current location of the device
mapClick(); // On clicking the map
vibRIngDatabase = new VibRIngDatabase(this);
}
//Display the Google Map inside the fragment
private void createMapView() {
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.setMyLocationEnabled(true); //To See my current location
/**
* If the map is still null after attempted initialisation,
* show an error to the user
*/
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Error creating map", Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception) {
Log.e("mapApp", exception.toString());
}
}
// Adding marker to the current location
public void addMarkerAtCurrent() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
latitude = myLocation.getLatitude();
// Get longitude of the current location
longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
String address = getLocationAddress(latitude, longitude);
marker = googleMap.addMarker(
new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(address));
// Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
}
public LatLng search(View v) {
edtLocation = (EditText) findViewById(R.id.edtLocation);
String location = edtLocation.getText().toString();
if (location != null) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
// To get address from list<Address>
Address address = addressList.get(0);
String locality = address.getLocality();
String adminArea = address.getAdminArea();
String locationAddress = locality + " " + adminArea;
latitude = address.getLatitude();
longitude = address.getLongitude();
latLng = new LatLng(latitude, longitude);
googleMap.clear();
marker = googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
}
return latLng;
}
// Clicking the GoogleMap
public LatLng mapClick() {
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng arg) {
latLng = arg;
latitude = latLng.latitude;
longitude = latLng.longitude;
String name = getLocationAddress(latitude, longitude);
googleMap.clear();
marker = googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
});
return latLng;
}
public String getLocationAddress(double lat, double longi) {
latitude = lat;
longitude = longi;
geocoder = new Geocoder(getApplicationContext());
try {
addressList = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
String addressLine = address.getAddressLine(0);
String locality = address.getLocality();
String adminArea = address.getAdminArea();
locationAddress = addressLine + " " + locality + " " + adminArea;
return locationAddress;
}
// On clicking add button openDialog method will be called
public void openDialog(View v) {
dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_dialog, null, false);
dialogBuilder.setTitle("Set Mode");
dialogBuilder.setView(view);
AlertDialog dialog = dialogBuilder.create();
dialog.show();
lat = (TextView) view.findViewById(R.id.lblLatitude);
longi = (TextView) view.findViewById(R.id.lblLongitude);
location_name = (TextView) view.findViewById(R.id.lblLocationName);
setMode = (Button) view.findViewById(R.id.btnSetMode);
latLng = marker.getPosition();
lati1 = latLng.latitude;
longi1 = latLng.longitude;
name = getLocationAddress(lati1, longi1);
lat.setText(Double.toString(lati1));
longi.setText(Double.toString(longi1));
location_name.setText(name);
rg = (RadioGroup) view.findViewById(R.id.modesRadioGroup);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.vibrationRadioButton:
Toast.makeText(getApplicationContext(), "Vibration clicked", Toast.LENGTH_LONG).show();
break;
case R.id.muteRadioButton:
Toast.makeText(getApplicationContext(), "Mute clicked", Toast.LENGTH_LONG).show();
break;
case R.id.ringingRadioButton:
Toast.makeText(getApplicationContext(), "Ringing clicked", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
});
}
}
Here in this code ,I am using the concept of Google Map.We can search a location by entering location name through EditText and then clicking on Search Button which call search() method .Here i will get the latitude and logitude of entered location.Also i can click on map which will call onMapClick() method.Here also i can get the latitude and longitude of the clicked position.While executing this code , i am getting different latitude and longitude value using these 2 methods for the same location.Just focus on search() and onMapClick() method .Please help me the resolve the issue.
Actually i am using geocoder to get the address..but i am getting address value as null.According to me I wrote the correct code to get current location from methods like getAddress() and address().The code i used is as following:
public class CurrentLoc extends Activity {
// latitude and longitude
static double latitude ;
static double longitude ;
// Google Map
private GoogleMap googleMap;
private LocationManager locationManager;
private Location location;
private String val;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new3);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
getAddress();
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* function to load map. If map is not created it will create it for you
* */
public String getAddress(){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
if (location != null) {
latitude= location.getLatitude();
longitude= location.getLongitude();
/*String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
lat, lng);*/
try {
val = address(latitude, longitude);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText( CurrentLoc.this, val,
Toast.LENGTH_LONG).show();
}
return val;
}
public String address(double lt,double lg) throws IOException{
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(lt, lg, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
return address +"\n"+ city +"\n"+ country;
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
// Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(CurrentLoc.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(CurrentLoc.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(CurrentLoc.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(location.getLatitude(), location.getLongitude())).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Hello Maps ");
googleMap.addMarker(marker);
googleMap.isMyLocationEnabled();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mnew1, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.home:
openSearch();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openSearch(){
String val1 = null;
val1 = getAddress();
Intent intnt=new Intent(getApplicationContext(),SendSms.class);
intnt.putExtra("loct", val1);
startActivity(intnt);
}
}
Move your code:
if (location != null) {
latitude= location.getLatitude();
longitude= location.getLongitude();
value=address(latitude, longitude);
Toast.makeText( CurrentLoc.this, value,
Toast.LENGTH_LONG).show();
}
Inside your public void onLocationChanged(Location location) method.
When you request a new location, you don't get the result immediately. Instead, you need to register a listener, like you did when you called locationManager.requestLocationUpdates, so the location provider can notify it when it fetches a location for you.
Also, from what I understood from your code, you may benefit from calling locationManager.requestSingleUpdate if you just need to get the phone's address in the current location instead of constantly getting location updates that requestLocationUpdates will give you.
Finally, consider this blog post for best practices on fetching the user location. You don't always need to get location updates if the current location is already known.
Hope it helps.
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;
}
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"/>