Get Current Location Name using Network Provider - android

I have tried using this code. It is not giving the location name. It is giving only latitude and longitude.
String latLongString;
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
}
else
{
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" + latLongString);

Location by default means Co-ordinates which is latitude and longitude
and that is what you are getting. To get the actual Address you need
to geocode the coordinates.
There are 2 steps to be follow to get current location name.
1) To get current lovation that you have done,
now
2) Using the Geocoder class to convert that lat long into Address
See this answer for links and detail expression.

Try this:
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
} else {
location = new Location("");
location.setLatitude((double) 38.0000000000);
location.setLongitude((double) -97.0000000000);
lat = location.getLatitude();
lng = location.getLongitude();
}

Related

Options to save data from a map marker to be used in a different activity android studio

I am looking advice on options i have to save data from markers and searches from placepicker on google maps.
Ive looked into shared preferences and tried the code out but not working.
I need to take address data from a place picker search and save it so that a history activity can generate a list.
is there any option that place picker saves searches?
im using android studio
This is an example of my place picker
Place place = PlacePicker.getPlace(data, this);
LatLng placeLatLng = place.getLatLng(); // gett lat lng from place
double placeLat = placeLatLng.latitude;
double placeLong = placeLatLng.longitude;
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
Marker destination = mMap.addMarker(new MarkerOptions().position(new LatLng(placeLat, placeLong)).title("This is your destination"));
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Current Location
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location myLocation = locationManager.getLastKnownLocation(provider);
//Current Location LatLong
final double currentLat = myLocation.getLatitude();
final double currentLng = myLocation.getLongitude();
List<CharSequence> listItems = new ArrayList<>();
//Directions From Current Location To Destination
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?" + "saddr=" + currentLat + "," + currentLng + "&daddr=" + placeLat + "," + placeLong));
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
listItems.add(name);
listItems.add(address);
startActivity(intent);
}
}
public void saveInfo(View v){
SharedPreferences sharedPreferences = getSharedPreferences("Place Deatils", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
}
get location address using Geocoder and store the information in SharedPreferences
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latt,lang, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String area = addresses.get(0).getSubLocality();
String dist= addresses.get(0).getSubAdminArea();
String city = addresses.get(0).getLocality();
mapMarker.setTitle(area+","+dist+","+city);
} catch (IOException e) {
e.printStackTrace();
}
check this SharedPreferences

Getting latitude & longitude from address in android

i am try to get latitude & longitude from address , problem is that .. when i give only city name than it give me correct latitude & longitude and when i give complete address (like state , city name , street No.) than it do not give me correct latitude & longitude ...
thanks for your cooperative response ...
my code is ..
//String addressStr = "faisalabad";/// this give me correct address
String addressStr = "Sainta Augustine,FL,4405 Avenue A";
Geocoder geoCoder = new Geocoder(MapClass.this, Locale.getDefault());
try {
List<Address> addresses =
geoCoder.getFromLocationName(addressStr, 1);
if (addresses.size() > 0) {
latitude = addresses.get(0).getLatitude(); longtitude =
addresses.get(0).getLongitude(); }
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace(); }
pos = new LatLng(latitude, longtitude);
googleMap.addMarker(new MarkerOptions().icon(
BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.position(pos));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 15));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
i don it ... :)
only sequence is incorrect ...
first give street address than city name and than state ... it give me correct latitude and longitude from address .. :)
and change
Geocoder geoCoder = new Geocoder(MapClass.this, Locale.getDefault());
to
Geocoder geoCoder = new Geocoder(MapClass.this);
thanks, all of you for your time ...
This is my solution :
private void createMarkerWithLocation() {
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300000, 40, this);
Location location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
/*check both providers even for lastKnownLocation*/
if (location == null)
location = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng currentLatLng = new LatLng(latitude, longitude);
if(isConnected(this)) {
Geocoder gCoder = new Geocoder(ChoiceDestinationActivity.this);
List<Address> addresses = gCoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
Toast.makeText(this, country + ", " + city + ", " + address, Toast.LENGTH_SHORT).show();
marker = map.addMarker(new MarkerOptions()
.position(currentLatLng)
.title(city)
.snippet(address)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
}
}
}
public static boolean isConnected(Context context) {
NetworkInfo ni = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
return (ni!=null && ni.isAvailable() && ni.isConnected());
}
I use it to add a marker on google map. It allows you to retrieve all the information regarding the location of the user.
I hope you have helped!

How i save my current location?

I create a simple application for show me the current location ( Lat , Lon ) when i move.How i save my current location when i want?
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
}
Use SharedPreferences.
To save the location, use:
getPreferences(MODE_PRIVATE).edit().putDouble("lng", lng).putDouble("lat", lat).commit();
To read the location, use:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
double lng = prefs.getDouble("lng", -1);
double lat = prefs.getDouble("lat", -1);

How to round a double to two decimal places in Java?

I am currently try to retrieve a latitude and longitude value from a location. When i convert the location to integer values using the following code:
LocationManager locMan;
Location location;
String towers;
private static double lat;
private static double lon;
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = locMan.getBestProvider(crit, false);
location = locMan.getLastKnownLocation(towers);
if (location != null)
{
lat = (int) (location.getLatitude() * 1E6);
lon = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lati, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String", "2nd String");
CustomPinpoint custom = new CustomPinpoint(d, MainMap.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
overlayList.clear();
lat = (double) lat;
lon = (double) lon;
System.out.println("Lat is " + lat);
System.out.println("Longi is " + lon);
}
else
{
System.out.println("Location is null! " + towers);
Toast.makeText(MainMap.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();
}
it comes back in the format of 0.000000
lat is 5.494394
long is -7.724457
how can i get it back in the format 00.000000
I have tried DecimalFormat, Math.Round and various other solutions i found on Stack Overflow but still get the same result. Please help!
Have you tried this:
DecimalFormat sf = new DecimalFormat("00.000000");
String s = sf.format(5.494394);
System.out.println(s); //prints 05.494394
EDIT
Based on your new question, why don't you do this:
double latitude = location.getLatitude();
double longitude = location.getLongitude();
GeoPoint ourLocation = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
//....
System.out.println("Lat is " + latitude);
System.out.println("Longi is " + longitude);
Convert to String, add leading zero.
StringFormatter might help.
An integer will never have leading zeroes.
You do a confusion between "real data" and "representation"
5.494394 is the "real data", that's an integer inferior to 10, it's logical to haven't a decade when you display it directly.
I you want to display every time the decade, also there is equal to 0, you have to test if your integer are inferior to 10 are not.
With an atomic test, this can be done with this way in java:
(lat < 10) ? "0"+lat : lat;
with this function, you are always the decade displayed before the "real data".
public String formatFigureToTwoPlaces(double value) {
DecimalFormat myFormatter = new DecimalFormat("00.00");
return myFormatter.format(value);
}

Location changed notification android

I am just testing out the onLocationChanged method in Android , I have implemented a way that when I click a button the app returns a String with the new lat and lng values. But now I am trying to show the results automatically every time the location changes. This is what I have so far to do so:
location manager
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
int minTime = 30000;
LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
MyLocationListener myLocListener = new MyLocationListener();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setSpeedRequired(false);
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, minTime, 1, myLocListener );
onlocationchanged
public void onLocationChanged(Location loc) {
if(loc != null){
lat1 = loc.getLatitude();
lng1 = loc.getLongitude();
currentlocation = "Location changed to lat: " + lat + "" + "lng: " + lng1 ;
Context context = getApplicationContext();
CharSequence text = currentlocation;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
I have set the requestlocationupdates method to request and update every 60000 millseconds
My problem is that the application never toasts the lat and lng values when the location changes. I have tested the app with the emulator and tried telneting the lat and lng values. And I have also drove around in my car to see if the values change.
Try:
currentlocation = "Location changed to lat: " + String.valueOf(lat1) + "" + "lng: " + String.valueOf(lng1) ;
and for test you can just use:
requestLocationUpdates(LocationManager.GPS_PROVIDER...

Categories

Resources