Google Map driving directions between two locations in my own application - java

I was working on Google maps, I need Google map driving direction between two locations(my current location and destination location) in my own application I don't want to open any google maps application. so please suggest me how to do this. up to now i have completed integrating google maps, zoom to my current location, placing a marker in destination lat-long.
my java file:
public class GoogleMapActivity extends FragmentActivity implements
OnMapReadyCallback, GoogleMap.OnMarkerClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
Location mLastLocation;
GoogleApiClient mGoogleApiClient;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_map);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Log.d("Tag", "in onc control in try");
buildGoogleApiClient();
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
Log.d("TAG","lat"+mLastLocation.getLatitude());
Log.d("TAG","lng"+mLastLocation.getLongitude());
ToastHelper.blueToast(getApplicationContext(), "location is " + mLastLocation.getLatitude() + " " + mLastLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()), 12.0f));
LatLng destination = new LatLng(14.880499, 79.988847);
mMap.addMarker(new MarkerOptions().position(destination).title("Destination"));
}
else {
Log.d("TAG","mLastLocation is null");
}
}
#Override
public void onConnectionSuspended(int i) {
}
/**
* Called when the map is ready.
*/
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
}
/**
* Called when the user clicks a marker.
*/
#Override
public boolean onMarkerClick(final Marker marker) {
// Retrieve the data from the marker.
// Return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}

There is a webservice public API for directions by google. It is not bundled with android API as far as I know.
Here you go with the link which will get you started

Check out this Awesome and easy to use Library:
https://github.com/jd-alexander/Google-Directions-Android
This library allows you to calculate the route between two locations
and displays it on a map.
It provides you a list of routing point which you can plot in Google Map to show routes and directions.

I don't know the end goal of your project. But if your intention is to get directions from point A to point B. Google's Roads Api can provide you with the data you need to draw the directions on a map or whatever you want.
It provides you the raw points even the speed in that particular road segment. It takes care of the redundant data that might lead you to draw directions through buildings for instance.

Finally got the result:
use this API link:
http://maps.googleapis.com/maps/api/directions/json?origin=(origin)&destination=(destination)
where it will return JSON as a response which contains latitudes and longitudes,
and store them in an array and draw polylines using those lat-long points in google maps

Related

How I may avoid making spaghetti code while trying to ask user for permissions?

Could you explain me, how I should do this right way? I've find this nonsense at all. So I'm trying to make an "welcome screen" where user will be asked for grant some location permissions. Before I've deleted everything and started once again, and faced same problem again - When user already grant the permission, the code from FusedLocationProviderClient still want to check if the permissions are granted(!) Is there something I doing wrong? Look at some example:
String[] mPermissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
FusedLocationProviderClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_screen);
mClient = LocationServices.getFusedLocationProviderClient(this);
checkPermissions();
}
private void checkPermissions() {
if (EasyPermissions.hasPermissions(this, mPermissions)) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
mClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
//TODO
}
}
);
}
}
#Override
public void onPermissionsGranted(int requestCode, #NonNull List<String> perms) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
mClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
}
}
);
}
#Override
public void onPermissionsDenied(int requestCode, #NonNull List<String> perms) {}
How I may make it work without multiple asking for permissions at once?
I'm not sure if I understood the question correctly, but from what I understood:
If you don't want it to check for permissions after they have been granted, you could make a boolean hasPermission and before calling the method to check, add an if statement.
if(!hasPermission)
checkPermissions();
Inside the checkPermissions method, if it detects that the permissions have been granted, you just set hasPermission = true and it will not check again because the if condition will no longer be true.

how do i find the high speed from a speedometer application?

I have created a speedometer application, I want it to display the max speed the user has achieved. How do I find the highest speed the user has achieved?
I have already tried to contain the speeds in an array so that I can find the highest speed using the math.max function but the speeds in a variable keep changing how do I store the past speeds to compare and find the highest speed.
my main3activity:
public class Main3Activity extends AppCompatActivity implements android.location.LocationListener {
int arr[];
public int borat;
public float boo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
LocationManager lm =(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
this.onLocationChanged(null);
final TextView mTextField=(TextView)this.findViewById(R.id.textView);
new CountDownTimer(11000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
Intent myIntent = new Intent(Main3Activity.this,
aftergame.class);
startActivity(myIntent);
}
}.start();
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public boolean checkLocationPermission()
{
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = this.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
#Override
public void onLocationChanged(Location location) {
int cpeeda;
int cpeedb;
final int speed;
TextView txt=(TextView)this.findViewById(R.id.st);
if(location==null){
txt.setText("0 m/s");
}else{
float cpeed=location.getSpeed();
float cpeed1=location.getSpeed();
cpeeda=(int)cpeed;
cpeeda=arr[0];
borat= Math.max(0,arr[0]);
txt.setText(cpeeda + " m/s");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
my activity which displays the high speed:
public class aftergame extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aftergame);
button = (Button) findViewById(R.id.button2) ;
Main3Activity m=new Main3Activity();
TextView tm=(TextView)this.findViewById(R.id.textView3);
tm.setText(""+m.borat);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(aftergame.this,
MainActivity.class);
startActivity(myIntent);
}
});
}
}
Here:
cpeeda=arr[0];
borat= Math.max(0,arr[0]);
That is non-sensical. I guess you meant to assign
arr[0] = cpeeda;
But even that doesn't make much sense. The idea of arrays is that they provide multiple data points. When you only assign a value into the first slot, all the other array slots stay at their initial value (which would be 0 if done right). Btw: your code does not create an array, so arr is null first of all.
In the end, the real answer is two-fold:
you are absolutely overburdening yourself here. Your code implies that you lack a lot of knowledge about basic java. You should spend some days, weeks, to learn Java first, before going for the even more complicated "Java Android"
you don't need an array to just find a max speed!
Simply do something like:
double maxSpeed = 0; // some field of your class, similar to your array
... wherever you determine the current speed:
if (maxSpeed > currentSpeed) {
maxSpeed = currentSpeed;
Yet, when you want to store multiple datapoints, you either should create an array of a fixed size (where you start overwriting older values once you got to that fixed size), or you could use an ArrayList. That one grows dynamically, thus you could just keep adding values to it. (of course, at some point you better stop doing so, otherwise you will run out of memory sooner or later)

How to pass information to a string outside a method?

I'm new to the Java language and have become a little stuck, I'm trying to pass a location to the String Bob. I need to pass a string from onLocationChanged method, to the String url which outside of the method. I have created a global variable, but the String bob does not hold any data.
Any help would be much appreciated.
public class MainActivity extends AppCompatActivity {
String bob = "";
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);}
}
}
TextView tempTextView;
TextView dateTextView;
TextView weatherDescTextView;
TextView cityTextView;
ImageView weatherImageView;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempTextView = (TextView) findViewById(R.id.tempTextView);
dateTextView = (TextView) findViewById(R.id.dateTextView);
weatherDescTextView = (TextView) findViewById(R.id.weatherDescTextView);
cityTextView = (TextView) findViewById(R.id.cityTextView);
weatherImageView = (ImageView) findViewById(R.id.weatherImageView);
dateTextView.setText(getCurrentDate());
// location
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Log.i("Location", location.toString());
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (listAddresses != null && listAddresses.size() > 0) {
//Log.i("PlaceInfo", listAddresses.get(0).toString());
if (listAddresses.get(0).getLocality() != null)
{
bob += listAddresses.get(0).getLocality() + " ";
}
Log.i("hello", bob.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider ) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
String url = "http://api.openweathermap.org/data/2.5/weather?q=" +bob+ "&units=metric&appid=xxxx";
i'm new to the Java language
My best piece of advice to you right now is to stop, put Android down, and go learn Java (or hell, get started with Kotlin) before trying to learn Android as well as you go. Android is complicated enough as is without trying to learn the language as well.
Anyway, as to your actual problem:
I'm trying to pass a location to the String 'Bob'. I need to pass a string from 'onLocationChanged' method, to the String 'url' which outside of the method... I have created a 'global' variable, but the String 'bob' does not hold any data.
You're problem is that that onLocationChanged method is a callback that actually doesn't get invoked until much later than the point at which you are trying to set the URL variable (assuming you actually register the callback, which your code does not show).
In other words, you are providing a hook in to the system that says, "when you have the location, let me know", meanwhile your code continues. When system lets you know the location is back (your callback is invoked) it's up to you to use the new value do something with it (in your case, I assume, make a network request).
So you would move your logic to right after the line where you update bob.
Hope that helps.
onLocationChanged is evaluated after you compute String url.
Once you have an understanding of multithreading, you will understand this.
At the moment, your code would be no different if you move String url to the very top of onCreate.
If you want the URL to be properly assigned, move it after Log.i("hello", and even check your logs to make sure it's correct
Personally, I don't suggest Android as the platform from which you learn Java

Android - getting current location through Google Map

I am developing an app related to Google map. I have done following steps successfully.
Created API key to access Google Map
Added Google Play Services Library in my app
Added required permissions
Added map in my activity with SupportMapFragment
Added a separate class MyMap.java to manipulate the map
Passed tow parameters to this class - Context of main activity and object of GoogleMap
Turned Wi-Fi and GPS on and ran the app
After this I am getting map with nice look and controls.
MyMap.java
public class MyMap implements ConnectionCallbacks, OnConnectionFailedListener {
private Context context;
private GoogleMap map;
private GoogleApiClient client = null;
public MyMap(Context context, GoogleMap map) {
this.context = context;
this.map = map;
client = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
Toast.makeText(context, "Connected", 1).show();
Location mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(client);
if (mLastLocation != null) {
Toast.makeText(
context,
String.valueOf(mLastLocation.getLatitude()) + ","
+ String.valueOf(mLastLocation.getLongitude()), 1)
.show();
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
Problem
In the above class I want to toast the current location. But it is not toasting anything. At least I need to see a toast saying "connected" on onConnected
event. Is there something wrong in my implementation?
Thanks in advance.
You seemingly never connect your client so it would be a real suprise if onConnected was called :)
You create your client with
client = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
but for the client to do something you have to add:
client.connect();
getLastLocation() is going to give location only once. To get periodic location updates, you need to override onLocationChanged() method. You can get this Link
Best way that I found is simple implement you activity like so:
public class MapActivity extends Activity implements GoogleMap.OnMyLocationChangeListener
and override method
#Override
public void onMyLocationChange(Location location) {
mMap.addMarker(new MarkerOptions().position(location).icon(
BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
And don't forget about mMap.setMyLocationEnabled(true); and mMap.setOnMyLocationChangeListener(this); in map init method
That's all!
Also, you can check is map available like here:
public boolean checkMapsAvailable() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, 9001);
dialog.show();
} else {
Constants.showToast(Constants.ALERT_GOOGLEPLAY_CONNECTION);
}
return false;
}
Hope this helps.

How can I check wether a (Google maps API) map has loaded?

I have started building an android application that focuses on a map from google-play-services-libs. When I start the app, it takes a while for the map to load from the gray grid to showing the map image.
I'd like to move/play around a bit with the map when it has fully loaded the part that is currently on screen. I have however been unable to find a way to programmatically check whether the map has loaded.
How can I achieve this?
In short:
From a instance of GoogleMap, how do I determine if it is actually showing something?
You can try using a OnCameraChangeListener on your map. The onCameraChange call will be called when the map's tiles are initially loaded.
this.map.setOnCameraChangeListener(new OnCameraChangeListener() {
public void onCameraChange(CameraPosition arg0) {
isMapReady = true;
map.setOnCameraChangeListener(null);
}
});
chckReady() function checks whether the map is ready or not
public class MapView extends android.support.v4.app.FragmentActivity {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ui_settings_demo);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
}
}
private boolean checkReady() {
if (mMap == null) {
return false;
}
}
}

Categories

Resources