I don't know why this crashed mostly on OnePlus
the error log
Geocoder geocoder = new Geocoder(ShopLocationActivity.this, Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
binding.cityName.setText(addressList.get(0).getLocality());
binding.streetAddressTextView.setText(addressList.get(0).getAddressLine(0));
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title(addressList.get(0).getAddressLine(0));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.addMarker(markerOptions);
} catch (IOException e) {
e.printStackTrace();
fetchLocation();
}
this is the code for my geocoder callback
implementation 'com.google.android.gms:play-services-location:19.0.1'
implementation 'com.google.android.gms:play-services-maps:18.0.2'
this is the dependency
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!!!
Getting "always true" result on if (location != null || !location.equals("")) and when I search something like "sldjfuhsdhfj" it closes the app, but when I enter something like "Central Park" it works correctly.
What am I doing wrong?
Code I am using
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText1);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 3s
mMap.clear();
}
}, 3000);
}
}
Address address = addressList.get(0)
You gave it junk so it is returning no results. addressList is empty. You are accessing the 0 element of something that is empty. You should have seen a message in the Android Monitor window of Android Studio that pointed you to this exact line / issue.
I'm trying to implement a zoom that fits all the marker points, these marker points is coming from a database, I made an array of markers, but when I run the app it gives me a zoom in only one marker, what am I missing here?
public class MapaViagem extends FragmentActivity {
private GoogleMap googleMap;
private String rm_IdViagem;
private List<ClienteModel> mClienteModel = new ArrayList<ClienteModel>();
private ViagemModel mViagemModel = new ViagemModel();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
try {
Bundle parametros = getIntent().getExtras();
rm_IdViagem = parametros.getString("id_viagem");
Repositorio ca = new Repositorio(this);
mViagemModel = ca.getViagemPorId(Integer.valueOf(rm_IdViagem));
Repositorio cl = new Repositorio(this);
mClienteModel = cl.getClientesViagem(Integer.valueOf(rm_IdViagem));
for (int i = 0; i < mClienteModel.size(); i++) {
Repositorio mRepositorio = new Repositorio(this);
EnderecoModel mEnderecoModel = mRepositorio.getEnderecosDoCliente(Integer.valueOf(mClienteModel.get(i).getClientes_id()));
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(false);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
float latitude = Float.parseFloat(mEnderecoModel.getLatitude());
float longitude = Float.parseFloat(mEnderecoModel.getLongitude());
// before loop:
List<Marker> markers = new ArrayList<Marker>();
Marker marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)));
markers.add(marker);
markers.size();
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker m : markers) {
builder.include(m.getPosition());
}
LatLngBounds bounds = builder.build();
final CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 25, 25, 0);
googleMap.animateCamera(cu);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
You are adding only one marker here:
List<Marker> markers = new ArrayList<Marker>();
Marker marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)));
markers.add(marker);
and no one more. So your list has only one marker, and the map will show only one marker.
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