I am trying to output the location into a textview.
I have used the locationManager.toString(), but it would only give me the output android.location.LocationManager#44ee7718.
I would like to output the location like Los Angeles, CA 90501.
The code for LocationManager:
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//conversion
Criteria criteria = new Criteria();
String bp = lm.getBestProvider(criteria, false);
Location location = lm.getLastKnownLocation(bp);
double lat = location.getLatitude();
double lon = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try{
addresses = gc.getFromLocation(lat, lon, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Address address = addresses.get(0);
final String ad = address.getAddressLine(0);
//ends here
The code for the button:
Red.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent (Intent.ACTION_VIEW);
intent.putExtra("sms_body", ad);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
}
});
Try following code
try {
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager
.getLastKnownLocation(bestProvider);
double lat = location.getLatitude();
double lon = location.getLongitude();
Geocoder gc = new Geocoder(this);
List<Address> lstAdd = gc.getFromLocation(lat, lon, 1);
Address ad = lstAdd.get(0);
String str = ad.getAddressLine(0);
Toast tst = Toast.makeText(this, "Your current location is " + str,
Toast.LENGTH_LONG);
tst.show();
} catch (Exception e) {
Toast tst = Toast.makeText(this,"Please check your gps settings",
Toast.LENGTH_LONG);
tst.show();
}
Hope this helps.
Call appropriate Location methods (getLatitude(), getLongitude())
Read this, http://developer.android.com/reference/android/location/Location.html
Also for converting to human readable names, you need to use GeoCoding
Read this, http://developer.android.com/reference/android/location/Geocoder.html
Also, http://developer.android.com/training/basics/location/geocoding.html
Related
hi I made a simple app that gets current location with gps and shows the current city but when I run it, it shows latitude and longitude correctly but returns city as null
Location mLastLocation = locationResult.getLastLocation();
lat = mLastLocation.getLatitude() + "";
lon = mLastLocation.getLongitude() + "";
Geocoder gcd = new Geocoder(MLocationListener.this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
if (addresses.size() > 0) {
// Log.d("city", addresses.get(0).getLocality());
String cityName = addresses.get(0).getLocality();
//Toast.makeText(MLocationListener.this, cityName, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
Try this solution:
Google map = googleMap;
this.map = googleMap;
this.map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
this.map.getUiSettings().setZoomControlsEnabled(true);
this.map.getUiSettings().setCompassEnabled(true);
this.map.getUiSettings().setMyLocationButtonEnabled(true);
this.map.getUiSettings().setZoomGesturesEnabled(true);
this.map.getUiSettings().setRotateGesturesEnabled(true);
String s = "New York";
List<Address> addressList = null;
if(s!=null){
Geocoder geocoder = new Geocoder( ); //inside put "getActivity()" or "this"
try{
addressList=geocoder.getFromLocationName(s, 1);
}catch(IOException e){
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
map.addMarker(new MarkerOptions().position(latLng).title(s));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
}
Is good to put this type of solution inside a class which implements OnMapReadyCallback, inside the method OnMapReady(GoogleMap googleMap)
Hope this can help you
I created a seperate activity to create a Google Map and set a marker on the users current location. In another fragment class, I'd like to set the text of a text view to the location from the map activity.
CheckInFragment
mLocation = (TextView) v.findViewById(R.id.checkin_location_text);
mLocation.setText();
MapsActivity
private void handleNewLocation(Location location){
//SET THESE TWO VARIABLES TO THE TEXT vv
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Check In Location");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
float zoomLevel = 16.0f;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
You can try below code to get the string value of location:
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
String fullAddress = "";
if (addressList != null && addressList.size() > 0) {
if (addressList.get(0).getAddressLine(0) != null) {
fullAddress += addressList.get(0).getAddressLine(0) + " ";
}
if (addressList.get(0).getSubAdminArea() != null) {
fullAddress += addressList.get(0).getSubAdminArea() + " ";
}
} else {
Log.d("Address:", "Couldn't find Address");
}
} catch (IOException e) {
e.printStackTrace();
}
Then you can pass the fullAddress string value in a bundle when calling the your fragment class, something like:
YourFragment fragment = new YourFragment();
Bundle args = new Bundle();
args.putString("location_string", fullAddress);
fragment.setArguments(args);
Finally in onCreate method of your Fragment class fetch the string value as below:
if (getArguments() != null)
{
_location = getArguments().getString("location_string");
}
Hope this helps!!!
I have been working in an Application where i need to fetch the current location of users. For the same, I added the COARSE_LOCATION AND FINE_LOCATION permissions in Manifest file.
I also added the Runtime permission to the App and i checked that the permissions are enabled in the App Info.
I have been using the below code to fetch the user's location.
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if (null != locations && null != providerList && providerList.size() > 0) {
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
cityname = listAddresses.get(0).getLocality();
countryname = listAddresses.get(0).getCountryName();
regionname = listAddresses.get(0).getSubLocality();
System.out.println("Location updates = " + cityname + regionname + countryname);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This piece of code works good on some devices (REDMI NOTE 3, REDMI NOTE 4, MOTO E) and in some devices it returns null(SAMSUNG J7, MOTO G).
Did i went wrong anywhere? Any advise can be really great full for my project and my learning.
I had the same problem. I put locationManager.getLastKnownLocation(provider); code inside loop until I get current location latitude and longitude. See below code :
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Location location = null;
do {
location = getLastKnownLocation();
}
while (location == null);
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
}
private Location getLastKnownLocation() {
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = null;
try {
l = locationManager.getLastKnownLocation(provider);
} catch (SecurityException e) {
e.printStackTrace();
}
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
do{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}while (location == null);
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
Log.d("locationLinster",message);
}else{
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
Log.d("locationLinster",message);
}
This really help to kick start the Provider... it takes time if our having this problem for the 1st time. But when it kicks in. it works like a dream.
Thanks #RG
I have a google map. In the simulator, everything works fine but in android device never finds the current location (shows message Location Error - see code). The map opens in world view...
cnt = new MapContainer(new GoogleMapsProvider(""));
cnt.setMapType(MAP_TYPE_TERRAIN);
LocationManager locationManager = LocationManager.getLocationManager();
InfiniteProgress ip = new InfiniteProgress();
Dialog ipDlg = ip.showInifiniteBlocking();
Location loc = LocationManager.getLocationManager().getCurrentLocationSync(30000);
ipDlg.dispose();
if (loc == null) {
try {
loc = LocationManager.getLocationManager().getCurrentLocation();
} catch (IOException err) {
Dialog.show("Location Error", "Unable to find your current location, please be sure that your GPS is turned on", "OK", null);
return;
}
}
locationManager.setLocationListener(this);
if (loc != null) {
double lat = loc.getLatitude();
double lng = loc.getLongitude();
Coord coordinate = new Coord(lat, lng);
}
The GPS is active on the device.
I can see my location in other apps.
You can improve your code by falling back to some default locations if GPS reception is not good in a particular area:
cnt = new MapContainer(new GoogleMapsProvider(""));
cnt.setMapType(MAP_TYPE_TERRAIN);
LocationManager locationManager = LocationManager.getLocationManager();
Location loc = locationManager.getLastKnownLocation(); //default
if (locationManager.isGPSDetectionSupported()) {
if (locationManager.isGPSEnabled()) {
InfiniteProgress ip = new InfiniteProgress();
Dialog ipDlg = ip.showInifiniteBlocking();
Location loc2 = locationManager.getCurrentLocationSync(30000);
if (loc2 != null) {
loc = loc2;
}
} else {
Dialog.show("Location Error", "Unable to find your current location, please be sure that your GPS is turned on", "OK", null);
}
} else {
InfiniteProgress ip = new InfiniteProgress();
Dialog ipDlg = ip.showInifiniteBlocking();
Location loc2 = locationManager.getCurrentLocationSync(30000);
if (loc2 != null) {
loc = loc2;
} else {
loc = LocationManager.getLocationManager().getCurrentLocation();
}
}
if (loc != null) {
double lat = loc.getLatitude();
double lng = loc.getLongitude();
Coord coordinate = new Coord(lat, lng);
}
I am trying to pass geocoder values from MapFragment to LocationDetailsActivity.
I get the correct values for lat and lng, but when I try to display any of the other values, most of the times I get null values instead of the city and zip (but not always), while a lot of the times I get the correct country and state (also not always).
MapFragment Code:
// Set default latitude and longitude
double latitude = 15.4825766;
double longitude = -5.0076589;
// Get latitude and longitude of the current location and a LatLng object
if (myLocation != null) {
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude();
}
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng arg0) {
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> allAddresses = geocoder.getFromLocation(arg0.latitude, arg0.longitude, 1);
if (allAddresses.size() > 0 && allAddresses != null) {
Address address = allAddresses.get(0);
Intent intent = new Intent(getActivity(), LocationDetailsActivity.class);
intent.putExtra("latitude", arg0.latitude);
intent.putExtra("longitude", arg0.longitude);
intent.putExtra("city", allAddresses.get(0).getLocality());
intent.putExtra("zip", allAddresses.get(0).getPostalCode());
intent.putExtra("state", allAddresses.get(0).getAdminArea());
intent.putExtra("country", allAddresses.get(0).getCountryName());
startActivity(intent);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
LocationDetailsActivity Code:
Bundle bundle = getIntent().getExtras();
double lat = bundle.getDouble("latitude");
double lng = bundle.getDouble("longitude");
String city = intent.getStringExtra("city");
String zip = intent.getStringExtra("zip");
String state = intent.getStringExtra("state");
String country = intent.getStringExtra("country");
// I display my values here
mFirstValueDisplay.setText(String.valueOf(city));
mSecondValueDisplay.setText(String.valueOf(zip));
Android's geocoding api is pretty unreliable up-to my experience, I usually make a request to the Google's geocoding webservices on Url : "https://maps.googleapis.com/maps/api/geocode"
(If you are familiar with retrofit)
#GET("/json")
void reverseGeoCode(#Query("latlng") String latlng, #Query("language") String language,
#Query("key") String key, Callback<ReverseGeoCode> callback);
latlng The latitude and longitude you want to reverse geocode.
language language of the geocoded response
key Your Api key
Go here for more info
Geocoder often got the values right, but more often than not I got null values. Based on #insomniac's advice I modified my code:
public void onMapLongClick(final LatLng arg0) {
RequestQueue queue = Volley.newRequestQueue(getActivity());
String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + String.valueOf(arg0.latitude) + "," + String.valueOf(arg0.longitude) + "&key=myKeyCode";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jObj = new JSONObject(response).getJSONArray("results").getJSONObject(0).getJSONArray("address_components");
Intent intent = new Intent(getActivity(), LocationDetailsActivity .class);
for (int i = 0; i < jObj.length(); i++) {
String componentName = new JSONObject(jObj.getString(i)).getJSONArray("types").getString(0);
if (componentName.equals("postal_code") || componentName.equals("locality")) {
intent.putExtra(componentName, new JSONObject(jObj.getString(i)).getString("short_name"));
}
}
intent.putExtra("latitude", arg0.latitude);
intent.putExtra("longitude", arg0.longitude);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
int x = 1;
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
It still displays some areas as null. But those are smaller areas. Hope someone finds it helpful.