Google Map in not Visible in android marshmallow? - android

Google Map not showing in marshmallow device when build an app at API level greater than 23 but it showing correctly below marshmallow version.I have used MapView.
Actally i am getting Current lat lang (0,0) in Marshmallow that's why i am facing issue in marshmallow.For getting current lat lang i am using this line:-
private void getCurrentLatLong() {
try {
gps = new GPSTracker(getActivity());
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
System.out.println("latitude print==" + latitude);
lat = String.valueOf(latitude);
lng = String.valueOf(longitude);
System.out.println("lat long check====" + "lati :" + lat + " -- lng :" + lng);
if (lat.equalsIgnoreCase("0.0") || lng.equalsIgnoreCase("0.0")) {
getCurrentLatLong();
} else {
mMapView.onResume();
setMap();
}
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}

Grant app permissions first, Setting -> Your App -> Permission -> enabled require permission

Related

how to get current Location with android studio

I want get current location then i press one button in the app but it dont give me that instead it give unknown address but if i change my location to USA it gives the address? I dont get any errors everything is working good only the address dont show up? here is my code, If you could help me I would appreciate it.
try {
Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(currentLocation.getCoordinates().latitude, currentLocation.getCoordinates().longitude, 1);
if (addresses.isEmpty()) {
autocompleteFragmentFrom.setText(R.string.waiting_for_location);
} else {
addresses.size();
if (addresses.get(0).getThoroughfare() == null) {
pickupLocation.setName(addresses.get(0).getLocality());
} else if (addresses.get(0).getLocality() == null) {
pickupLocation.setName("unknown address");
} else {
pickupLocation.setName(addresses.get(0).getLocality() + ", " + addresses.get(0).getThoroughfare());
}
autocompleteFragmentFrom.setText(pickupLocation.getName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
enter image description here
After request location permission and enable GPS use FusedLocationProviderClient.
private val mFusedLocationProviderClient: FusedLocationProviderClient by lazy {
LocationServices.getFusedLocationProviderClient(requireActivity())
}
mFusedLocationProviderClient.lastLocation?.addOnSuccessListener(this) { location:Location? ->
val lat = location?.latitude
val lon = location?.longitude
}

Coordinates are not submitted

So I'm trying to get the actual coordinates of the smartphone and then submit it. For this purpose I am working with a (non-optimal) email solution. I want to get the coordinates and then submitting them by email.
If I press the button, it should get the coordinates and then putting them into mail.
Somehow I only get 0.0 into the email client, which should be the default values.
Anyway, here is my relevant code:
I initialise lat and lon with double in the public class.
public LatLng getLocation()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
finden
try {
lat = location.getLatitude();
lon = location.getLongitude();
//überschreiben der Variabeln lon & lat funktioniert
return new LatLng(lat, lon);
}
catch (NullPointerException e){
e.printStackTrace();
return null;
}
}
And this is my button.
final Button button = (Button) findViewById(R.id.addbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getLocation();
Intent i = new Intent(Intent.ACTION_SENDTO);
//i.setType("message/rfc822");
i.setData(Uri.parse("mailto:"));
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"adress#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "Subject - New Location was added");
i.putExtra(Intent.EXTRA_TEXT , "Latitude: " + lat + " Longitude: " + lon " );
try {
startActivity(i);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MapsActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
So what is my fault? The app is running, but it wont get the coordinates.
Have you provided the ACESS_FINE_LOCATION in the manifest file? You need this permission to access location.
You need to add this in the manifest file.
Edit:
Look, these days fused location provider is being used and there do come some instances where you don't get the permission and location doesn't come up. Read this file which is a basic example for retrieving location -
https://github.com/googlesamples/android-play-location/blob/master/BasicLocationSample/app/src/main/java/com/google/android/gms/location/sample/basiclocationsample/MainActivity.java
Also, this is the guide for it -
https://developer.android.com/training/location/retrieve-current.html

Android Geocoder returns null city name

I am new to Android development, following is my code about use Geocoder to get city name of current location, it returns null:
private void updateCurrentLocation(Location location) {
double lat = 0.0, lng = 0.0;
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
Log.i("tag", "Latitute is" + lat + ", Longtitute is" + lng);
} else {
City_Name = "Unavailable";
}
List<Address> list = null;
Geocoder geocoder = new Geocoder(this.getActivity());
try {
list = geocoder.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
//may provide multiple locations.
if (list != null && list.size() > 0) {
Address address = list.get(0);
City_Name = address.getLocality();
}
Log.i("Try", "CityName:" + City_Name);
//send empty message
handler.sendEmptyMessage(1);
}
I opened GPS services, add ACCESS_FINE_LOCATION and INTERNET permission in Manifest already. Also, I searched similar questions in Stackoverflow about Geocoder returns null, but haven't found useful solutions. One of them is analyze JSON from Geocoder website, but it doesn't work either.
Can anyone help with this? Thank you!
BTW, is there any better solution to receive a city name? Thank you!
If the "getFromLocation" method gives you an empty set then it's because the server that is being looked up doesn't have the address information for the coordinates you're passing it. This is also noted in the docs. So I think that you should let it go and use another service like the Google Maps geocoding service or another one like Nominatim from the OpenStreetMap project.

Android Google map shows black screen before loading

I have an application with an initial window with three buttons. When I click on one of them, I start a progress dialog while I am loading a Google Map V2 and drawing some markers on it.
In the onMapReady callback I dismiss the progress dialog:
#Override
public void onMapReady(final GoogleMap map) {
Log.i(MyMoneyBackActivity.TAG, "ShopsMapActivity onMapReady");
GMap = map;
if (needsInit) {
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(CAMERA_LAT,
CAMERA_LNG));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(12f);
map.moveCamera(center);
map.animateCamera(zoom);
}
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
// Clears all the existing coordinates
map.clear();
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
provider = mLocationManager.getBestProvider(criteria, true);
// Get best last location measurement
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
mLocationManager.requestLocationUpdates(provider, 20000, 0, this);
Log.i(MyMoneyBackActivity.TAG, "Map");
Geocoder geoCoder = new Geocoder(ShopsMapActivity.this, Locale.getDefault());
if ( geoCoder.isPresent() )
Log.i(MyMoneyBackActivity.TAG, "Geocoder available");
else
Log.i(MyMoneyBackActivity.TAG, "Geocoder NOT available");
// Add a marker for every shop
for (ShopElement rec : MyMoneyBackActivity.shopElementsList) {
//String addressStr = "Aquileia 39,Udine,Italy";
String addressStr = rec.getaddress() + "," + rec.getcity() +",Italy";
Log.i(MyMoneyBackActivity.TAG, "addressStr -" + addressStr + "-");
try {
List<Address> addresses = geoCoder.getFromLocationName(addressStr, 1);
if (addresses.size() > 0) {
latitude = addresses.get(0).getLatitude();
longitude = addresses.get(0).getLongitude();
}
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(MyMoneyBackActivity.TAG, "Position : " + latitude + " " + longitude);
point = new LatLng(latitude, longitude);
// Add a new marker for this shop
drawMarker(map, point, rec, "");
}
map.setInfoWindowAdapter(new PopupAdapter(this,
getLayoutInflater(),
images));
//point = new LatLng(CAMERA_LAT, CAMERA_LNG);
//drawMarker(map, point, null, "Centro");
// Display last reading information
if(mBestReading!=null){
onLocationChanged(mBestReading);
}
if (MyMoneyBackActivity.progressDialog.isShowing()) {
MyMoneyBackActivity.progressDialog.dismiss();
MyMoneyBackActivity.progressDialog = null;
}
}
But what I got for some tens of seconds is a completely black screen before the map is actually drawn.
Hardware accelartion and largeheap was the issue in my case. I removed them from the app level and used them in the activity they used.
Issue was in Manifest.
<application
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:hardwareAccelerated="false"
android:largeHeap="true">
Remove from Manifest and Use in the Activity
<activity
android:name="com.mycompayname.activities.SignUpActivity"
android:hardwareAccelerated="false"
android:largeHeap="true"/>
Check if it works in Google Play Services 6.7.76 - see here https://code.google.com/p/gmaps-api-issues/issues/detail?id=7679.

Can't get current device location

I am trying to get current location of my android phone and display the longitude and latitude in a toast. Here is a function I wrote. While debugging the code I see that the control never goes inside onLocationChanged function.
From the following android documentation it looks like, when I call "locationMgr.requestLocationUpdates", it should call the callback function onLocationChanged. But that does not seem to happen in my code.
http://developer.android.com/training/basics/location/currentlocation.html
I checked my phone has GPS turned on. I can not figure out what is wrong in the following code. Please help.
public void getCurrentLocation(){
LocationManager locationMgr;
locationMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// A new location update is received. Do something useful with it
String latitude = "latitude: " + location.getLatitude();
String longitude = "longitude: " + location.getLongitude();
String toastString = "location is" + latitude + "," +longitude;
Toast.makeText( getApplicationContext(),toastString,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// No code here
}
#Override
public void onProviderEnabled(String provider) {
// No code here
}
#Override
public void onStatusChanged(String provider, int status,Bundle extras)
{
// No code here
}
};
locationMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, listener);
}
I also have following two lines in my Manifest file.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Thank you for your help.
I am using Eclipse and my phone(OS: Thuderbolt) has API level 15, target 4.0.4.
There are several reasons that you are not getting location.
1.) If you are trying to get location on emulator. Then you have to manually push the coordinates using DDMS.
2.) If You are checking it on device and still you are not getting location. Then as you said that you are expecting it from GPS. Then you should have Clear sky view to get that. As GPS receiver dont work under roofs or under some hinderances. They must have sky view.
3.) You can get location from using wi-fi or cell-Tower. Also you can opt for Last known location if location accuracy is not as much important.
What i think is that may be second point will resolve your problem.
The problem was google-play-services library.
I had to download the library code and compile it in eclipse. Then I added the path to the library in my project. This solved the problem.
Earlier I had included the google-play-services .jar file in my project, but it was not working. Not sure why.
Here is example i wrote that uses LocationManager to get the location data every two minutes. Its not perfect but should be sufficient to solve your issue: It can be found here
Focus on:
#Override
public void onLocationChanged(final Location location) {
this.location=location;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
int cnt=1;
public void run() {
handler.post(new Runnable() {
public void run() {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
Double altitude = location.getAltitude();
Float accuracy = location.getAccuracy();
textView.setText("Latitude: " + latitude + "\n" + "Longitude: " + longitude+ "\n" + "Altitude: " + altitude + "\n" + "Accuracy: " + accuracy + "meters"+"\n" + "Location Counter: " + cnt);
try {
jsonData = new JSONObject();
jsonData.put("Latitude", latitude);
jsonData.put("Longitude", longitude);
jsonData.put("Altitude", altitude);
jsonData.put("Accuracy", accuracy);
System.out.println(jsonData.toString()); //not required, for testing only
if(url!=null) {
new HttpPostHandler().execute();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cnt++;
}
});
}};
ourtimer.schedule(timerTask, 0, 120000);

Categories

Resources