How to set text to Google Maps current location from another class - java

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!!!

Related

why the city of my current location is null in android studio?

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

Creating customized info windows for a Marker when using a cluster manager?

I was following this guide, until I realized that he was adding marker directly to the map and not letting a cluster manager handle it.
I created a CustomInfo class that implements InfoWindowAdapter. In the getInfoContents(Marker marker) I get the data from the marker using getTag(). The problem is that I never set a tag to my marker (where would I?).
This is the code for when I read in my location objects:
private void generateShelterObjects()
{
Log.i(TAG, "METHOD generateShelterObjects() STARTED");
InputStream is = getResources().openRawResource(R.raw.shelters_csv_file);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
try {
while ((line = reader.readLine()) != null) {
// Split the line into different tokens (using the comma as a separator).
String[] tokens = line.split(",");
String address = tokens[0];
double latitude = Double.parseDouble(tokens[1]);
double longitude = Double.parseDouble(tokens[2]);
LatLng latLng = new LatLng(latitude, longitude);
String numberOfOccupants = tokens[3];
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title(address).snippet("Antal platser: " + numberOfOccupants);
ShelterObject obj = new ShelterObject(latLng, address, numberOfOccupants);
listMarkers.add(markerOptions);
}
} catch (IOException e1) {
Log.e(TAG, "Error" + line, e1);
e1.printStackTrace();
}
}
To add markers to the map I use this method for my cluster manager:
private void addClusterItems()
{
for (MarkerOptions markerOptions : listMarkers) {
ShelterObject clusterItem = new ShelterObject(markerOptions.getPosition(), markerOptions.getTitle(), markerOptions.getSnippet());
clusterManager.addItem(clusterItem);
}
}
Thanks in advance!
Check this,
private void setUpcustomInfoWindow(){
myMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View myContentView =getActivity().getLayoutInflater().inflate(
R.layout.custom_info_window, null);
TextView tvAddress = ((TextView) myContentView
.findViewById(R.id.tv_address_info_window));
TextView tvAveragePrice = ((TextView) myContentView
.findViewById(R.id.tv_averageprice_info_window));
TextView tvAverageSqft = ((TextView) myContentView
.findViewById(R.id.tv_averagesqft_info_window));
MicroLocality microLocality = (MicroLocality) marker.getTag();
tvAddress.setText(microLocality.getMicroLocality());
tvAveragePrice.setText(getActivity().getString(R.string.Rs)+" "+microLocality.getPricerange());
tvAverageSqft.setText(getActivity().getString(R.string.Rs)+" "+microLocality.getPricePerSqft());
return myContentView;
}
});
}

Location returning null on some devices

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

Geocoder is not working in android above kitkat version

I was working with geocoder in my android app to get country name using latitude and longitude. I found that it was working good in kitkat version and below. But when i test my app in above versions it was giving null. So my question is simple that how to use geocoder above kitkat versions.
If there is any other better option instead of geocoder then please suggest me!
Thanks in advance!
I post my code for Geocoder. Follow it
//Keep this GeocodingLocation.java in a separate file.
public class GeocodingLocation {
private static final String TAG = "GeocodingLocation";
public static void getAddressFromLocation( final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
String latitude = null;
String longitude = null;
try {
List<Address> addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
Log.e("GeocodingLocation --> getAddressFromLocation ==>" +
addressList.toString());
Address address = (Address) addressList.get(0);
StringBuilder sb = new StringBuilder();
latitude = String.valueOf(address.getLatitude());
longitude = String.valueOf(address.getLongitude());
Logger.infoLog("GeocodingLocation --> Lat & Lang ==>" + latitude +" "+longitude);
//sb.append(address.getLatitude()).append("\n");
//sb.append(address.getLongitude()).append("\n");
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (latitude != null && longitude != null) {
message.what = 1;
Bundle bundle = new Bundle();
bundle.putString("latitude", latitude);
bundle.putString("longitude", longitude);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
call the class from your fragment.
private void getAddressLatitudeLongitude(String branchAddress) {
Log.e("getAddressLatitudeLongitude ==>" + branchAddress);
GeocodingLocation.getAddressFromLocation(branchAddress, thisActivity, new GeocoderHandler());
}
Keep this class as inner class in same fragment
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:
try {
Bundle bundle = message.getData();
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
Log.e("CreateBranch --> GeocoderHandler ==>" + latitude + " " + longitude);
}catch (Exception e){
e.printStackTrace();
}
break;
default:
latitude = null;
longitude = null;
}
latitudeList.add(latitude);
longitudeList.add(longitude);
if(latitude==null || longitude==null){
showAlertDialog("Please enter correct address", Constants.APP_NAME);
}
Log.e("Latitude list =>" + latitudeList);
Log.e("Longitude list =>" + longitudeList);
}
}
Output will get latitude and longitude. Hope this answer helps.

How do I output the location using gps on Android

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

Categories

Resources