I need to find the estimate drive time from one place to another. I've got latitudes and longitudes for both places but I have no idea how to do that. Is there is any API for that.
help thanks.
yes you get the time and distance value as well as many like direction details in driving, walking etc mode. all you got from the google direction api service
check our this links
http://code.google.com/apis/maps/documentation/directions/
Location location1 = new Location("");
location1.setLatitude(lat);
location1.setLongitude(long);
Location location2 = new Location("");
location2.setLatitude(lat);
location2.setLongitude(long);
float distanceInMeters = location1.distanceTo(location2);
EDIT :
//For example spead is 10 meters per minute.
int speedIs10MetersPerMinute = 10;
float estimatedDriveTimeInMinutes = distanceInMeters / speedIs10MetersPerMinute;
Please also see this, if above not works for you:
Calculate distance between two points in google maps V3
Deprecation note The following described solution is based on Google's Java Client for Google Maps Services which is not intended to be used in an Android App due to the potential for loss of API keys (as noted by PK Gupta in the comments). Hence, I would no longer recommened it to use for production purposes.
As already described by Praktik, you can use Google's directions API to estimate the time needed to get from one place to another taking directions and traffic into account. But you don't have to use the web API and build your own wrapper, instead use the Java implementation provided by Google itself, which is available through the Maven/gradle repository.
Add the google-maps-services to your app's build.gradle:
dependencies {
compile 'com.google.maps:google-maps-services:0.2.5'
}
Perform the request and extract the duration:
// - Put your api key (https://developers.google.com/maps/documentation/directions/get-api-key) here:
private static final String API_KEY = "AZ.."
/**
Use Google's directions api to calculate the estimated time needed to
drive from origin to destination by car.
#param origin The address/coordinates of the origin (see {#link DirectionsApiRequest#origin(String)} for more information on how to format the input)
#param destination The address/coordinates of the destination (see {#link DirectionsApiRequest#destination(String)} for more information on how to format the input)
#return The estimated time needed to travel human-friendly formatted
*/
public String getDurationForRoute(String origin, String destination)
// - We need a context to access the API
GeoApiContext geoApiContext = new GeoApiContext.Builder()
.apiKey(apiKey)
.build();
// - Perform the actual request
DirectionsResult directionsResult = DirectionsApi.newRequest(geoApiContext)
.mode(TravelMode.DRIVING)
.origin(origin)
.destination(destination)
.await();
// - Parse the result
DirectionsRoute route = directionsResult.routes[0];
DirectionsLeg leg = route.legs[0];
Duration duration = leg.duration;
return duration.humanReadable;
}
For simplicity, this code does not handle exceptions, error cases (e.g. no route found -> routes.length == 0), nor does it bother with more than one route or leg. Origin and destination could also be set directly as LatLng instances (see DirectionsApiRequest#origin(LatLng) and DirectionsApiRequest#destination(LatLng).
Further reading: android.jlelse.eu - Google Maps Directions API
You can also use
http://maps.google.com/maps?saddr={start_address}&daddr={destination_address}
it will give in direction detail along with distance and time in between two locations
http://maps.google.com/maps?saddr=79.7189,72.3414&daddr=66.45,74.6333&ie=UTF8&0&om=0&output=kml
Calculate Distance:-
float distance;
Location locationA=new Location("A");
locationA.setLatitude(lat);
locationA.setLongitude(lng);
Location locationB = new Location("B");
locationB.setLatitude(lat);
locationB.setLongitude(lng);
distance = locationA.distanceTo(locationB)/1000;
LatLng From = new LatLng(lat,lng);
LatLng To = new LatLng(lat,lng);
Calculate Time:-
int speedIs1KmMinute = 100;
float estimatedDriveTimeInMinutes = distance / speedIs1KmMinute;
Toast.makeText(this,String.valueOf(distance+
"Km"),Toast.LENGTH_SHORT).show();
Toast.makeText(this,String.valueOf(estimatedDriveTimeInMinutes+" Time"),Toast.LENGTH_SHORT).show();
Related
I'm a beginner in android studio and I'm currently create cycling apps for my final project. in these apps I need to implement Maps and Direction API. I search for tutorials, but they all set the destination. and in my apps the destination is unknown.
it's possible if I display the current location (automatic) and draw a line in Maps while the user is riding, please give a tutorial too? And it's possible if I use a Free API Key for this project?
thank you ...
First, This direction API is not free.
2nd you need to provide start and endpoint for direction API routes.
You can use the current location as your start point and if you have no destination then where do you want to draw a line? Means from your current location to where?
or If you want to draw a tracking line from your starting position to your current position then you don't need Direction API, you just need Live location tracking and can draw Polylines on your map using current location. Following is the code for your help.
To get this library into our app, we need to add the following to our build.gradle file.
implement 'com.google.maps:google-maps-services:0.1.20'
// Initialize Geo Context First
private GeoApiContext getGeoContext() {
GeoApiContext geoApiContext = new GeoApiContext();
return geoApiContext.setQueryRateLimit(3)
.setApiKey(getString(R.string.directionsApiKey))
.setConnectTimeout(1, TimeUnit.SECONDS)
.setReadTimeout(1, TimeUnit.SECONDS)
.setWriteTimeout(1, TimeUnit.SECONDS);
}
// This code will fetch the result from Google direction api from origin to destination
DateTime now = new DateTime();
DirectionsResult result = DirectionsApi.newRequest(getGeoContext()).mode(TravelMode.DRIVING).origin(origin)
.destination(destination)
.departureTime(now).await();
// You can use this method to add marker on the map
private void addMarkersToMap(DirectionsResult results, GoogleMap mMap) {
mMap.addMarker(new MarkerOptions().position(new LatLng(results.routes[0].legs[0].startLocation.lat, results.routes[0].legs[0].startLocation.lng)).title(results.routes[0].legs[0].startAddress));
mMap.addMarker(new MarkerOptions().position(new LatLng(results.routes[0].legs[0].endLocation.lat, results.routes[0].legs[0].endLocation.lng)).title(results.routes[0].legs[0].startAddress).snippet(getEndLocationTitle(results)));
}
// Use this method to draw polyline/routes on your map
private void addPolyline(DirectionsResult results, GoogleMap mMap) {
List<LatLng> decodedPath = PolyUtil.decode(results.routes[0].overviewPolyline.getEncodedPath());
mMap.addPolyline(new PolylineOptions().addAll(decodedPath));
}
I'm trying to make a request to my Geoserver to retrieve the features near the tap of a user on the map.
The map takes all the space. Therefore I computed the BBOX in this way:
region = mMap.getProjection().getVisibleRegion().latLngBounds;
double left = region.southwest.longitude;
double top = region.northeast.latitude;
double right = region.northeast.longitude;
double bottom = region.southwest.latitude;
and the width and height are taken as belows:
mMapFragment.getView().getWidth();
mMapFragment.getView().getHeight();
while the X and Y parameter are calculated in the following way:
Point click = mMap.getProjection().toScreenLocation(latLng);
where latLng is the point that came from the event onMapClick(LatLng) (reference here: https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.OnMapClickListener).
The resulting URL that I obtain is:
http://localhost/geoserver/sindot/wms?service=WMS&request=GetFeatureInfo&info_format=application%2Fjson&version=1.1.1&srs=EPSG%3A3857&bbox=1222173.74033,5056403.44084,1222174.11356,5056403.7028&query_layers=sindot:verticale&layers=sindot:verticale&feature_count=3&styles=tabletb3lab&width=2048&height=1262&x=1441&y=503
The problem is that the server returns always an empty response even if I know that there are features there because I can see the spots on the map. What could it be?
Thanks in advance.
It onlytook to add &buffer=10 (or another number according to your needs) to the request.
How to calculate the walking distance between two points in Android?
For example:
static final LatLng Point_One = new LatLng(41.995908, 21.431491);
static final LatLng Point_Two = new LatLng(41.996097, 21.422419);
Now, the distance between these points on maps.google.com is 950 meters. And the Location.distanceBetween is returning the air line distance between these two points, I need the Walking distane. Thanks in advance.
PS: I am using google maps Api v2
Just request the maps API as documented in The Google Distance Matrix API
So, your request to Maps API is :
http://maps.googleapis.com/maps/api/distancematrix/json?origins=41.995908,%2021.431491&destinations=41.996097,%2021.422419&mode=walking&sensor=false
You just have to query this url from your application.
I don't think you can get a walking distance between two points (other than as a straight line). You could plot a track of the walk (GPX) and then calculate distance. You can do this with an App as you walk or on a map.
I am trying to create a maps app for a certain city that have some stored latitude and longitude for certain landmarks in the city. In the map,
you can only zoom in and zoom out within the boundaries of the city
While the app is open, when you reach a certain range of lat and long coordinates within a certain radius around the landmark, it will trigger and activity that will display details about the landmark and also a voice recording about the landmark
also, the map must also have the "directions" functionality in it, where it can show several possible ways for you to get to a certain location (like landmark) from your present location and also display the distance between two points
I've already tried a GPS program from androidhive that detects your lat and long coordinates. I'm also trying to understand how to acquire and use the google maps api. I would like to know the possible approaches in doing it since I'm still new to android.
Thanks in Advance!
you can zoom with specific mile or kmeter by this code:this is for two mile:
Display display = getWindowManager().getDefaultDisplay();
// double equatorLength = 3218; // in meters
double equatorLength = 40075004; // in meters
double widthInPixels = display.getWidth();
double metersPerPixel = equatorLength / 256;
int zoomLevel = 1;
// 2 mile=3218 mtr
while ((metersPerPixel * widthInPixels) > 3218) {
metersPerPixel /= 2;
++zoomLevel;
}
return zoomLevel;
hope this is helpfull for "you can only zoom in and zoom out within the boundaries of the city"
I have a location with latitude and longitude and want to get a new location that has a distance of x meters from that location at an angle of d degrees. This would be the reverse of Location.distanceBetween(). Is there any Android API to do that. I know that I could program such a function myself, but I wonder if there is an API for it already.
There are some formulae and sample code (JavaScript) for this here: Movable Type Scripts. Look for 'Destination point given distance and bearing from start point'.
Here's an excerpt of the JavaScript from the site:
var lat2 = Math.asin( Math.sin(lat1)*Math.cos(d/R) +
Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng) );
var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(lat1),
Math.cos(d/R)-Math.sin(lat1)*Math.sin(lat2));
In the above code, d is the distance, brng is the bearing in degrees, and R is the Earth's radius.
Porting this to Java should be trivial.
This is called the "first geodesic" (or sometimes "principal geodesic") problem, which will probably help you in finding an algorithm on Google if you need to implement this yourself.
Implement this yourself for now, but do expect this function to show up at some point, so code accordingly - create your own function, add a few unit tests.
In the future add the following to you function:
def myFunc(args):
res = # compute stuff
#if(debug):
res2 = # make api call
assert(res = res2)
return res
And some time later:
def myFunc(args):
return # make api call
And some time later remove the function altogether.
Here is the reverse of it:
SphericalUtil.computeOffsetOrigin(loc1, dist, angle);
It also has the distanceBetween function:
SphericalUtil.computeDistanceBetween(...);
Lib:
SphericalUtil