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);
}
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 implemented a mini project and there i need to display currency symbol based on Location.
ex: If i am in India it should display rupee symbol if USA $ symbol, I have implemented but it always gives Pound symbol
My Code:
LocationManager locationManager = (LocationManager) getSystemService(ListActivity.LOCATION_SERVICE);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
Geocoder code = new Geocoder(ListActivity.this);
try {
List<Address> addresses = code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
Address obj = addresses.get(0);
String cc = Currency.getInstance(obj.getLocale()).getSymbol();
Log.d("Currency Symbol : ", cc);
} catch (IOException e) {
e.printStackTrace();
}
}
I needed to show currency symbol of respective country and get country are from GPS i searched lot finally came up with below code its working properly so i want to share this code others could not waste there time
here you need first country code like IN,US from latitude longitude we get full address
Please check GPS permission in manifest file before run code.
below are the some permissions
need GPSTracker.java file code create GPSTracker java file and write below code. in this some red line dont worry it affect nothing
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // Longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS() {
if (locationManager != null) {
//locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#
Override
public void onLocationChanged(Location location) {}
#
Override
public void onProviderDisabled(String provider) {}
#
Override
public void onProviderEnabled(String provider) {}
#
Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#
Override
public IBinder onBind(Intent arg0) {
return null;
}
}
here is mainactivity.java class
public class MainActivity extends AppCompatActivity {
public static SortedMap < Currency, Locale > currencyLocaleMap;
TextView t;
Geocoder geocoder;
private static final Map < String, Locale > COUNTRY_TO_LOCALE_MAP = new HashMap < String, Locale > ();
static {
Locale[] locales = Locale.getAvailableLocales();
for (Locale l: locales) {
COUNTRY_TO_LOCALE_MAP.put(l.getCountry(), l);
}
}
public static Locale getLocaleFromCountry(String country) {
return COUNTRY_TO_LOCALE_MAP.get(country);
}
String Currencysymbol = "";
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.text);
GPSTracker gpsTracker = new GPSTracker(MainActivity.this);
geocoder = new Geocoder(MainActivity.this, getLocaleFromCountry(""));
double lat = gpsTracker.getLatitude();
double lng = gpsTracker.getLongitude();
Log.e("Lat long ", lng + "lat long check" + lat);
currencyLocaleMap = new TreeMap < Currency, Locale > (new Comparator < Currency > () {
public int compare(Currency c1, Currency c2) {
return c1.getCurrencyCode().compareTo(c2.getCurrencyCode());
}
});
for (Locale locale: Locale.getAvailableLocales()) {
try {
Currency currency = Currency.getInstance(locale);
currencyLocaleMap.put(currency, locale);
Log.d("locale utill", currency + " locale1 " + locale.getCountry());
} catch (Exception e) {
Log.d("locale utill", "e" + e);
}
}
try {
List < Address > addresses = geocoder.getFromLocation(lat, lng, 2);
Address obj = addresses.get(0);
Currencysymbol = getCurrencyCode(obj.getCountryCode());
Log.e("getCountryCode", "Exception address " + obj.getCountryCode());
Log.e("Currencysymbol", "Exception address " + Currencysymbol);
} catch (Exception e) {
Log.e("Exception address", "Exception address" + e);
// Log.e("Currencysymbol","Exception address"+Currencysymbol);
}
t.setText(Currencysymbol);
}
public String getCurrencyCode(String countryCode) {
String s = "";
for (Locale locale: Locale.getAvailableLocales()) {
try {
if (locale.getCountry().equals(countryCode)) {
Currency currency = Currency.getInstance(locale);
currencyLocaleMap.put(currency, locale);
Log.d("locale utill", currency + " locale1 " + locale.getCountry() + "s " + s);
s = getCurrencySymbol(currency + "");
}
} catch (Exception e) {
Log.d("locale utill", "e" + e);
}
}
return s;
}
public String getCurrencySymbol(String currencyCode) {
Currency currency = Currency.getInstance(currencyCode);
System.out.println(currencyCode + ":-" + currency.getSymbol(currencyLocaleMap.get(currency)));
return currency.getSymbol(currencyLocaleMap.get(currency));
}
}
You can use this to get locale of your Location
Locale locale= getResources().getConfiguration().locale;
Currency currency=Currency.getInstance(locale);
String symbol = currency.getSymbol();
Refernce : Getting Current Locale
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