Android: Get directions from Google Map - android

I'm trying to give a direction to the user using google map from one location to another.
I'm using the code bellow but I have no idea why it's not working. I can't figure out the problem everything seems right.
final double latitude = 37.894404;
final double longitude = -122.0660386;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
if(lastKnownLocation != null){
double lat = lastKnownLocation.getLatitude();
double longi = lastKnownLocation.getLongitude();
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr="+lat+","+longi+"&daddr="+latitude+","+longitude));
startActivity(intent);
}else{
Toast.makeText(contactus.this,"Coudn't get provider", Toast.LENGTH_SHORT).show();
}
}

First off you need to wrap your call to LocationManager with a try/catch block and grab whatever exception you're getting off the call. Have a look below. This will make the call and catch the exception.. Go from there once you know why it's coming back NULL. You will always have trouble getting location geopoints using the emulator for whatever reason. Also, Google does not always return with geopoints so in the emulator I have looped until it has come back.. Not a good idea
try{
Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
}
catch(IOException e) {
Log.e("IOException", e.getMessage());
//Toaster on high-----------------//
Context context = getApplicationContext();
CharSequence text = "IOException: " + e.getMessage();
int dur = Toast.LENGTH_LONG;
Toast.makeText(context, text, dur).show();

I actually got it working and here is the code I used,
final double latitude = 45.894404;
final double longitude = -112.0660386;
LocationManager lManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
String towers = lManager.getBestProvider(crit, false);
Location userCurrentLocation = lManager.getLastKnownLocation(towers);
if(userCurrentLocation != null){
double lat = userCurrentLocation.getLatitude();
double longi = userCurrentLocation.getLongitude();
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr="+lat+","+longi+"&daddr="+latitude+","+longitude));
startActivity(intent);
}else{
Toast.makeText(contactus.this, "Couldn't locate a provider to find your location", Toast.LENGTH_LONG).show();
}
Don't forget to add the premission to find the user location to you manifest, include it above ,
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Related

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: GPS Location not working

I am trying to retrieve Location as follows:
LocationManager locationManager = (LocationManager)MyApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
String provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// NOTE: the location below is null !!
Location location = locationManager.getLastKnownLocation(provider);
String lat = location.getLatitude();
String lng = location.getLongitude();
}
The 'location' above is null. Why?
But when i open the (Google) Maps app - it shows location correctly, and even a notification icon (looks like a exclamation mark) shows up.
And there is a GPS Coordinates app - which also shows up blank.
I have turned on Settings > 'Location' on the phone. If it matters this is Android 4.4.4 Sony Experia phone.
Well, it seems that you're not checking properly if the GPS is working or not. The way you should do it:
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
//GPS is not enabled !!
}
You can also create an AlertDialog so the user is aware that the GPS is not enabled and you can send him to the GPS settings by doing this:
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
After this, I'd implement a location listener and get coordinates, here is an example, check it out
How do I get the current GPS location programmatically in Android?
UPDATE: They might be getting coordinates through other provider (usually the one which is working better at that moment). So if the GPS it not working, just try other provider, here is an example:
Location lastKnownLocation = null;
List<String> providers = null;
if(locationManager != null) providers = locationManager.getAllProviders();
if(providers != null)
{
for(int i=0; i<providers.size(); i++)
{
if(locationManager != null) lastKnownLocation = locationManager.getLastKnownLocation(providers.get(i));
if(lastKnownLocation != null)
{
position = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
break;
}
}
}

What is the simplest way to get the user's longitude and latitude in Android ? Even without using listener?

My app just need to know user's country, and my app doesn't care where user moves.
All I want to know is :
When user start app, app will send user's approximately location(latitude and longitude) to server.
Here is my code with error. I try to send a string to getlocation function, and I hope it can return original string with adding latitude and longitude information.
private String getlocation (String url){
LocationManager status = (LocationManager) (this.getSystemService(Context.LOCATION_SERVICE));
if (status.isProviderEnabled(LocationManager.GPS_PROVIDER) || status.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.v("print","enable to locate");
} else {
Log.v("print","fail to locate");
}
Location location = status.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
Log.v("print","succed!!!##");
Double longitude = location.getLongitude();
String loc=Double.toString(longitude);
url=url+loc;
}
else{
Log.v("print","location return null");
}
return url;
}
I use network_provider, and it always print "enable to locate", then print "location return null"
So what's wrong with my code that my location always return null.
I use AVD manerger, and I also try GPS_PROVIDER. I use Emulator control to send Decimal on location control. It doesn't work ,too.
By the way, I set network and GPS permission,too.
So much thanks for help!
I am getting location by below code but enable " use wireless networks " in settings i.e ( through settings - Location services - use wireless networks)
public void getCurrentLocation() {
LocationManager locationManager;
String bestProvider;
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
Log.e(TAG, "Latitude: "+location.getLatitude()+" , Longitude: "+location.getLongitude());
}

Android LocationManager.getLastKnownLocation() returns null on Android 4.1.1

I am working on android application. I am stuck in problem.
getLastKnownLocation(provider) returns null for Android version 4.1.1, while for other versions it is fine. Provider is enabled and the rest is ok. I don't know where is the problem. Here is the code.
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.clear();
System.out.println("Current Location = "+latLng);
locationManager.getLastKnownLocation will return null if the provider is disabled, and here is the documentation
http://developer.android.com/reference/android/location/LocationManager.html#getLastKnownLocation(java.lang.String)
try this its working for me...
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
return false;
}
});

Showing User's Location in Android

I have a problem in getting the user's location (my location). My code is
double lat;
double lng;
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
if(!locationManager.isProviderEnabled(provider)){
locationManager.setTestProviderEnabled(provider, true);
}
boolean enabled = locationManager.isProviderEnabled(provider);
if(enabled){
Toast.makeText(LoginActivity.this,"provider enabled",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(LoginActivity.this,"provider disabled",Toast.LENGTH_LONG).show();
}
if(location!=null){
lat = location.getLatitude();
lng = location.getLongitude();
AlertDialog.Builder ab=new AlertDialog.Builder(LoginActivity.this);
ab.setMessage(Html.fromHtml("<b><font color=#ff0000>Location" +"</font></b><br>"
+location.toString()+"<br>Latitude: "+lat
+"<br>Longitude "+lng));
ab.setPositiveButton("ok",null );
Toast.makeText(LoginActivity.this,"You are at "+location.toString(),Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(LoginActivity.this,"Location not found",Toast.LENGTH_LONG).show();
}
My problem is I am getting the location as null while the application message provider is enabled. I have not found any problem in this code. I have also tested it on a device, it shows the provider is enabled and the location isn't found.
I have not implemented the location listener in the class.
Is it necessary to implement location listener in my class?
You are only getting the last known location from the phone. If this is null, which it is if no last known location is available, you are not trying to receive locations in any other way.
You should implement a LocationListener an register it to receive location updates according to this guide: http://developer.android.com/guide/topics/location/obtaining-user-location.html This will cause the phone to try to get the users location and hand it over to your application in the form of a Location object.

Categories

Resources