Find distance between two points on map using Google Map API V2
You can use the following method that will give you accurate result
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
int Radius = 6371;// radius of earth in Km
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = Radius * c;
double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value", "" + valueResult + " KM " + kmInDec
+ " Meter " + meterInDec);
return Radius * c;
}
android find distance and duration between two points on google map
You can use a third party library for this. It's easy and efficient:
Gradle Dependancy:
compile 'com.akexorcist:googledirectionlibrary:1.0.4' // Custom Google Direction API \\
Code:
Below method will take the latLng of your destination, also inside method you should have latlng object containing your origin. Server key is your api key and you should also enable Google Directions API to make this work.
/**
* Draw polyline on map, get distance and duration of the route
*
* @param latLngDestination LatLng of the destination
*/
private void getDestinationInfo(LatLng latLngDestination) {
progressDialog();
String serverKey = getResources().getString(R.string.google_direction_api_key); // Api Key For Google Direction API \\
final LatLng origin = new LatLng(latitude, longitude);
final LatLng destination = latLngDestination;
//-------------Using AK Exorcist Google Direction Library---------------\\
GoogleDirection.withServerKey(serverKey)
.from(origin)
.to(destination)
.transportMode(TransportMode.DRIVING)
.execute(new DirectionCallback() {
@Override
public void onDirectionSuccess(Direction direction, String rawBody) {
dismissDialog();
String status = direction.getStatus();
if (status.equals(RequestResult.OK)) {
Route route = direction.getRouteList().get(0);
Leg leg = route.getLegList().get(0);
Info distanceInfo = leg.getDistance();
Info durationInfo = leg.getDuration();
String distance = distanceInfo.getText();
String duration = durationInfo.getText();
//------------Displaying Distance and Time-----------------\\
showingDistanceTime(distance, duration); // Showing distance and time to the user in the UI \\
// String message = "Total Distance is " + distance + " and Estimated Time is " + duration;
// StaticMethods.customSnackBar(consumerHomeActivity.parentLayout, message,
// getResources().getColor(R.color.colorPrimary),
// getResources().getColor(R.color.colorWhite), 3000);
//--------------Drawing Path-----------------\\
ArrayList<LatLng> directionPositionList = leg.getDirectionPoint();
PolylineOptions polylineOptions = DirectionConverter.createPolyline(getActivity(),
directionPositionList, 5, getResources().getColor(R.color.colorPrimary));
googleMap.addPolyline(polylineOptions);
//--------------------------------------------\\
//-----------Zooming the map according to marker bounds-------------\\
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(origin);
builder.include(destination);
LatLngBounds bounds = builder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.20); // offset from edges of the map 10% of screen
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
googleMap.animateCamera(cu);
//------------------------------------------------------------------\\
} else if (status.equals(RequestResult.NOT_FOUND)) {
Toast.makeText(context, "No routes exist", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDirectionFailure(Throwable t) {
// Do something here
}
});
//-------------------------------------------------------------------------------\\
}
How can I get the distance between two gepoints with Google Maps API v2?
You are parsing distance data of step
value. You should look at the xml once again. It shows the correct data
See this
Distance/Time beetween two points in android google maps
you will need to look into this link for distance between 2 locations and time
https://developers.google.com/maps/documentation/directions/
Basically, you will need to make http call to the google map service which returns JSON with everything you mentioned above, sort your JSON into readable text to use in java
Google Map API v2 - Get Driving Distance from Current Location to Known Locations
Here's an update of your existing code:
// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result)
{
if (result.size() < 1)
{
Toast.makeText(getActivity(), "No Points", Toast.LENGTH_SHORT).show();
return;
}
TextView tv1 = (TextView) getActivity().findViewById(R.id.location1);
TextView tv2 = (TextView) getActivity().findViewById(R.id.location2);
TextView tv3 = (TextView) getActivity().findViewById(R.id.location3);
TextView tv4 = (TextView) getActivity().findViewById(R.id.location4);
TextView[] views = {tv1, tv2, tv3, tv4};
// Traversing through all the routes
for (int i = 0; i < result.size(); i++)
{
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
String distance = "No distance";
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++)
{
HashMap<String, String> point = path.get(j);
if (j == 0)
{
distance = point.get("distance");
continue;
}
}
// Set text
views[i].setText(distance);
}
}
This code makes a not-so-good assumption: It assumes that the size of result
is the same size as views
, which in your case should be 4. When you run this code, you may get an IndexOutOfBounds
error if you have more than 4 results (which shouldn't happen). Eventually you will want to verify that the size of result
is 4, or the number of TextView
's you have. If you have any questions or this doesn't work right, just let me know :)
EDIT: To get all distances at once, you can modify your DownloadTask
to take in multiple URL's.
Change class definition:
private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>>
This says that your background operation will return a list of String
's.
Modified doInBackground()
, which now can process multiple URL's:
// Downloading data in non-ui thread
@Override
protected ArrayList<String> doInBackground(String... urlList)
{
try
{
ArrayList<String> returnList = new ArrayList<String>();
for(String url : urlList)
{
// Fetching the data from web service
String data = Locations.this.downloadUrl(url);
returnList.add(data);
}
return returnList;
}
catch (Exception e)
{
Log.d("Background Task", e.toString());
return null; // Failed, return null
}
}
Then you onPostExecute()
becomes
// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(ArrayList<String> results)
{
super.onPostExecute(results);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(results);
}
Now, you will have to modify your ParserTask
code to take in a list of JSON Strings, and not just one JSON String. Just change your ParserTask
input parameters and put everything inside a for
loop to loop through each JSON String. You will also have to modify the parameter of onPostExecute()
to take in a List
of whatever is there already, so that way it doesn't process one result, but a list of results. I can't show you those modifications here because it would be way too long, and then there would be no challenge for you :)
EDIT TWO: In getLastLocation()
you're only calling DownloadTask
with one URL, but you should put four URL's like this downloadTask.execute(url1, url2, url3, url4)
. Also, since ParserTask
still only processes one JSON String, you should take out the four TextView
's and the array looping out of the onPostExecute()
. To tell the ParserTask
which TextView
to populate, add a constructor to ParserTask
which takes in a TextView
as a parameter. Then make an instance variable within ParserTask
that is assigned in the constructor and used in onPostExecute()
to display the distance.
Then, take that TextView
array stuff I gave you before and put it in the onPostExecute()
of DownloadTask
. When you loop through the String results, also loop through the TextView
array and pass in the TextView
in the ParserTask
constructor.
Basically, you're adding a constructor in the ParserTask
to tell it which TextView
to draw on. When your DownloadTask
is finished, you pass it the right TextView
for the URL. For example, R.id.location3
for the third URL.
Related Topics
Android Facebook Sdk 4 in Eclipse
Enabling Proguard in Eclipse for Android
Listview Click to Show Image in Imageview
How to Connect Android App to MySQL Database
Locationclient Getlastlocation() Return Null
Recyclerview Horizontal Scroll Snap in Center
How to Make an Android App Return to the Last Open Activity When Relaunched
How to Get Camera Result as a Uri in Data Folder
How to Show Dependencies Tree in Android Studio
How to Adjust Layout When Soft Keyboard Appears
The Completest Cocos2D-X Tutorial & Guide List
Counting Chars in Edittext Changed Listener
Google Sign in Failed Com.Google.Android.Gms.Common.Api.Apiexception: 10:
Google Play Services Library Update and Missing Symbol @Integer/Google_Play_Services_Version