get arrival/travel time of perticular route in here-api android - android

I am using android Here-sdk. I got total distance of perticular route from MapRoute object. So now i want to get arrival/travel time of perticular route.
Below is the code for distance. what would i do for get time from MapRoute object. Thanks!
for(int i = list_routes.size() ; i > 0 ; i--)
{
MapRoute mapRoute = new MapRoute(list_routes.get(i-1).getRoute());
mapRoute.setColor(color_array.get(i-1));
mapRoute.setTrafficEnabled(true);
// here i got total distance
int distance = mapRoute.getRoute().getLength();
m_map.addMapObject(mapRoute);
}

You can do it like that:
int timeInSeconds = mapRoute.getRoute().getTta(x, y).getDuration();
where x is TrafficPenaltyMode and y is subleg number. You can check the details in the documentation.

The documentaion link change use this instead documentation
the getTTa method is deprecated now, use
Route.getTtaIncludingTraffic(int subleg)
or
Route.getTtaExcludingTraffic(int subleg)
if you want the travel time for the whole route use this value
Route.WHOLE_ROUTE
example:
int timeInSeconds = route.getTtaExcludingTraffic(Route.WHOLE_ROUTE).getDuration();

Related

Charts - using Mp Chart

I need to draw graph like the image i have uploaded , i am using MP chart library and develop a graph but want to customize it according to my requirement but not able to find solution for my requirements my basic requirement is for x axis i want to show custom values at axis like 5-11 12-18 but i am passing value to x axis like this
private ArrayList<String> setXAxisValues() {
ArrayList<String> xVals = new ArrayList<String>();
xVals.add("10");
xVals.add("20");
xVals.add("30");
xVals.add("30.5");
xVals.add("40");
return xVals;
}
So it is showing x values like this 10 20 30 so on so i want my graph to be built upon using these x value which is happening right now but want to show custom value at bottom like 5-11 etc and this value is dynamic coming from Api response so please help me about this , Waiting for positive and early response Thanks in Advance
To format the x-axis values, you should use the setValueFormatter method which takes a callback interface were you have to implement the getFormattedValue method which is called before drawing the x-axis value.
xAxis.setValueFormatter((value, axis) -> {
String res = "";
try {
// get current position of x-axis
int currentPosition = (int) value;
// check if position between array bounds
if (currentPosition > -1 && currentPosition < maxSize) {
// get value from formatted values array
res = xVals.get(currentPosition);
}
} catch (Exception e) {
// handle exception
}
return res;
});

ArrayList.add() causing OutOfMemory error?

For the first time today, I've met an OutOfMemory Error. I'm trying to calculate moving averages out of some data into an ArrayList, and had a crash at the first .add() step. The method is shown below
public ArrayList<Long> getNdaySMA(List<HistoricalQuote> history, int range){
long sum =0;
long SMA = 0;
ArrayList<Long> SMAs = new ArrayList<Long>();
//realRange is made due to the differences in defining "range in calculation vs speech
//a 10 day range for day 9 is actually from prices of day0 to day9, inclusive
int realRange =range-1;
//First step, add in placeholder 0s for the days within the range that have no value
//so if 10 day range, we have 0-> 9
for (int i=0;i<i+realRange;i++){
SMAs.add(i,0L);
}
//Next, actually calculate the SMAs for i.e. day 10
for (int i =0;i<history.size();i++){
//should be k<10, 0......9 = 10 days
for(int k=i+realRange;k==i;k--){
//Sum first from k=i+range-1 , go down to i.
//This should give us a value of RANGE
sum +=history.get(k).getClose().longValue();
}
//after summing up, we add calculate SMA and add it to list of SMAs
SMA = sum/range;
//we add the corresponding SMA to index i+range, made up of values calculated from before it
//to excel
SMAs.add(i+realRange,SMA);
sum =0;
}
return SMAs;
}
The stacktrace is as follows
java.lang.OutOfMemoryError
at java.util.ArrayList.add(ArrayList.java:154)
at com.xu.investo.MethodDatabase.getNdaySMA(MethodDatabase.java:46)
Where Line 46 refers to
SMAs.add(i,0L);
Is this error occuring due to the use of the Long number format? Any suggestions are welcome.
looks like infinite loop:
for (int i=0;i<i+realRange;i++)
i will always be less then i+realRange for realRange greater then zero:
I think I've identified the problem.
I may have created an infinite loop at this line
for (int i=0;i<i+realRange;i++){
SMAs.add(i,0L);
}

Query between distances in Parse

I would like to search places between two given distances, using GeoPoints. Using the currently api, I think I could make something like this pseudo algorithm:
query.whereWithinKilometers("directions", GlobalData.ownerGeoPoint, MAXIMUM distance);
MINUS
query.whereWithinKilometers("directions", GlobalData.ownerGeoPoint, MINIMUM distance);
How can I translate to real code?
Finally I found a way to do it with a parse query.
// Do not want locations further than maxDistance
ParseQuery query = ParseQuery.getQuery("MyData");
query.whereWithinKilometers("location", userGeoPoint, maxDistance);
// Do not want locations closer than minDistance
ParseQuery<ParseObject> innerQuery = ParseQuery.getQuery("MyData");
innerQuery.whereWithinKilometers("location", userGeoPoint, minDistance);
query.whereDoesNotMatchKeyInQuery("objectId", "objectId", innerQuery);
Likely you'll have to pull in everything within the maximum distance from Parse to your app, then inside your app filter out anything that is closer than the minimum.
Thankfully Parse includes some distance measuring as part of PFGeoPoint. Check out the three methods here.
distanceInRadiansTo:
distanceInMilesTo:
distanceInKilometersTo:
So your pseudocode is:
(After you get back everything within the outer radius)
Make a new array (var) called finalList
For i = 0; i < objects.count; i++ {
var gp: PFGeoPoint = objects[i]
if gp.distanceInMilesTo:originalGeoPoint >= minimumRadiusInMiles {
finalList.push(gp)
}
}

Is language conditional in some operations?

I'm developing an app where I use the Geocoder to get a place's coordinates.
The operative is this:
The user defines an address.
The geocoder finds that address and I get the coordinates from that address.
This coordinates are in decimal format and I need them in degrees-minutos so I format them.
To format the coordinates from decimal to degrees-minutes I use:
String frmtLatitude = Location.convert(Double.parseDouble(lat), Location.FORMAT_MINUTES);
So, if I have for example this latitude 43.249591 in decimal value, it returns it like this 43:14.97546.
After this, I have to make some operations to finally get the latitude with this appearance: 4314.975
When I do this operations, one of them is to split the value using the ".". I split 14.97546 to get in one hand the 14 and in the other 97546.
Until here, everything ok. It works fine when I have my phone's language selected to be in english. But if I select to be in spanish, the app crashes. I have followed the stacktrace and it points there. Is like that in english when using the first commented function to convert from decimal to degrees-minutes it separates the decimals with a "." but if I have it in spanish, it separates them with a ",".
Can this really happen or the cause could be another thing?
We can look at the source code of the convert method
public static String convert(double coordinate, int outputType) {
if (coordinate < -180.0 || coordinate > 180.0 ||
Double.isNaN(coordinate)) {
throw new IllegalArgumentException("coordinate=" + coordinate);
}
if ((outputType != FORMAT_DEGREES) &&
(outputType != FORMAT_MINUTES) &&
(outputType != FORMAT_SECONDS)) {
throw new IllegalArgumentException("outputType=" + outputType);
}
StringBuilder sb = new StringBuilder();
// Handle negative values
if (coordinate < 0) {
sb.append('-');
coordinate = -coordinate;
}
DecimalFormat df = new DecimalFormat("###.#####");
if (outputType == FORMAT_MINUTES || outputType == FORMAT_SECONDS) {
int degrees = (int) Math.floor(coordinate);
sb.append(degrees);
sb.append(':');
coordinate -= degrees;
coordinate *= 60.0;
if (outputType == FORMAT_SECONDS) {
int minutes = (int) Math.floor(coordinate);
sb.append(minutes);
sb.append(':');
coordinate -= minutes;
coordinate *= 60.0;
}
}
sb.append(df.format(coordinate));
return sb.toString();
}
We can see that it uses a DecimalFormat with a given pattern. So, if we look to the DecimalFormat constructor :
public DecimalFormat(String pattern) {
// Always applyPattern after the symbols are set
this.symbols = new DecimalFormatSymbols(Locale.getDefault());
applyPattern(pattern, false);
}
We can see here that even if we give a pattern, it uses the locale values. The javadoc also said :
Parameters:
pattern A non-localized pattern string.
To finish, we can go here to see the different local variant of numbers representation : http://docs.oracle.com/cd/E19455-01/806-0169/overview-9/index.html
So we can see that US-English use the "dot format" and that Spanish use "comma format".
To answer your question : the proflem you're facing is probably due to the Decimal format of your locale. I advice you to be REALLY CAREFUL when converting types of objects to make manipulation on them. Converting an int to a String should be only to display it.
I think you should seperate decimal part of your number when it stills a float (or any decimal type) and then convert your object to a String to display it. You can take a look at Math class or search SO to get some example on how to this ;)
Also, as #Dmitry said, you can get DecimalSeparator with DecimalFormatSymbols.getDecimalSeparator().
Sources
Location.convert(double,int) source code
DecimalFormat(String) source code
Java "Decimal and thousands separators"
You are right, decimal seperator depends on your locale. You can get it by something like this
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols formatSymbols = df.getDecimalFormatSymbols();
char separator = formatSymbols.getDecimalSeparator();

Distance Travelled

I am creating a Phonegap App (using jQuery and Google Maps API V3) related to travelling and would like to show the user the distance he/she has travelled since starting the app.
Is there any Google function for this? Or can anyone recommend what I can do to get the total distance travelled?
It can be done easily. You have to understand, by using a Google Maps API for jQuery you have all needed tools to do it by yourself.
First, you need to define a time period (lets say 1 minute). We will need it to create a reference point of our movements. Next step is to use phonegap/cordova geolocation API to calculate our position (latitude and longitude):
http://docs.phonegap.com/en/1.0.0/phonegap_geolocation_geolocation.md.html
At this point choose do you want to:
Store a position (latitude and longitude) every 1 minute in some js array
Or do the same thing like in point 1 and also show it on the map with gmap addMarker ability.
At the end you need to calculate a distance. Loop through the position array and use latitude and longitude to calculate a distance between every available point. Here you will find function used for a such calculation (with a js example):
http://www.movable-type.co.uk/scripts/latlong.html
Or you can use Google Maps APi function:
google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);
EDIT:
Here's a working example for you: http://jsfiddle.net/Gajotres/6YpAG/
Code:
$(document).ready(function(){
// Chicago
var coordinateObject= new Object();
coordinateObject.lat = '41.83682786072714';
coordinateObject.lng = '-87.626953125';
geoLocationHandler.addLocation(coordinateObject);
// New York
var coordinateObject= new Object();
coordinateObject.lat = '40.58058466412761';
coordinateObject.lng = '-74.00390625';
geoLocationHandler.addLocation(coordinateObject);
// Toronto
var coordinateObject= new Object();
coordinateObject.lat = '43.70759350405294';
coordinateObject.lng = '-79.365234375';
geoLocationHandler.addLocation(coordinateObject);
var len = geoLocationHandler.arrLocations.length;
for (var i = 0; i < len; i++) {
if(i == 1){
geoLocationHandler.distance += geoLocationHandler.calcDistance(geoLocationHandler.arrLocations[i-1].lat,geoLocationHandler.arrLocations[i-1].lng,geoLocationHandler.arrLocations[i].lat,geoLocationHandler.arrLocations[i].lng);
}
}
alert(geoLocationHandler.distance);
});
var geoLocationHandler = {
arrLocations : [],
distance : 0,
addLocation:function(obj){
geoLocationHandler.arrLocations.push(obj);
},
calcDistance:function(fromLat, fromLng, toLat, toLng) {
return google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(fromLat, fromLng), new google.maps.LatLng(toLat, toLng));
}
};
Final result is a distance expressed in meters.
Every time you have a new coordination use this to create a new object and add it to the array:
var coordinateObject= new Object();
coordinateObject.lat = '41.83682786072714'; // Change with your latitude
coordinateObject.lng = '-87.626953125'; // Change with your longitude
geoLocationHandler.addLocation(coordinateObject);

Categories

Resources