Remove previous route in graphhopper android? - android

I am using graphhopper and mapsforge to show the route in my android app.The route is shown in my mapView from the polyline but when I change the location of second point the new route is shown above the previous route.So I need to delete this previous route when a new route is calculated. The code is as follows:
GraphHopper localGraphHopper = new GraphHopper().forMobile();
localGraphHopper.setCHShortcuts(true, true);
localGraphHopper.load(getFolderPath());
GHRequest localGHRequest = new GHRequest(paramDouble1, paramDouble2, paramDouble3, paramDouble4);
GHRequest a = localGHRequest.setAlgorithm("dijkstrabi");
GHResponse localGHResponse = localGraphHopper.route(localGHRequest);
int i = localGHResponse.getPoints().getSize();
PointList localPointList = localGHResponse.getPoints();
Polyline localPolyline = new Polyline(createPaint(AndroidGraphicFactory.INSTANCE.createColor(Color.RED), 4, Style.STROKE), AndroidGraphicFactory.INSTANCE);
this.latLongs_track = localPolyline.getLatLongs();
for (int j = 0;; j++)
{
if (j >= i)
{
this.mapView.getLayerManager().getLayers().add(localPolyline);
LatLong localLatLong = new LatLong((paramDouble1 + paramDouble3) / 2.0D, (paramDouble2 + paramDouble4) / 2.0D);
this.mapView.getModel().mapViewPosition.setCenter(localLatLong);
return;
}
this.latLongs_track.add(new LatLong(localPointList.getLatitude(j), localPointList.getLongitude(j)));
}

Use this function:
public void calcPath( final double fromLat, final double fromLon,
final double toLat, final double toLon ) {
log("calculating path ...");
new AsyncTask<Void, Void, GHResponse>(){
float time;
protected GHResponse doInBackground( Void... v ){
StopWatch sw = new StopWatch().start();
GHRequest req = new GHRequest(fromLat, fromLon, toLat, toLon).
setAlgorithm(AlgorithmOptions.DIJKSTRA_BI);
req.getHints().
put("instructions", "false");
GHResponse resp = hopper.route(req);
time = sw.stop().getSeconds();
return resp;
}
protected void onPostExecute( GHResponse resp ){
if (!resp.hasErrors()){
log("from:" + fromLat + "," + fromLon + " to:" + toLat + ","
+ toLon + " found path with distance:" + resp.getDistance()
/ 1000f + ", nodes:" + resp.getPoints().getSize() + ", time:"
+ time + " " + resp.getDebugInfo());
logUser("the route is " + (int) (resp.getDistance() / 100) / 10f
+ "km long, time:" + resp.getMillis() / 60000f + "min, debug:" + time);
mapView.getLayerManager().getLayers().add(createPolyline(resp));
//mapView.redraw();
} else{
logUser("Error:" + resp.getErrors());
}
shortestPathRunning = false;
}
}.execute();
}
All source you can find at https://github.com/graphhopper/graphhopper

I have found the answer for my problem and am posting here
Polyline localPolyline;
public void calcPath( final double fromLat, final double fromLon,
final double toLat, final double toLon )
{
log("calculating path ...");
new AsyncTask<Void, Void, GHResponse>()
{
float time;
protected GHResponse doInBackground( Void... v )
{
StopWatch sw = new StopWatch().start();
GHRequest req = new GHRequest(fromLat, fromLon, toLat, toLon).
setAlgorithm(AlgorithmOptions.DIJKSTRA_BI);
req.getHints()
.put("instructions", "false");
GHResponse resp = hopper.route(req);
time = sw.stop().getSeconds();
return resp;
}
protected void onPostExecute( GHResponse resp )
{
if (!resp.hasErrors())
{
if(localPolyline!=null){
mapView.getLayerManager().getLayers().remove(localPolyline);
}
else{
log("here");
}
log("from:" + fromLat + "," + fromLon + " to:" + toLat + ","
+ toLon + " found path with distance:" + resp.getDistance()
/ 1000f + ", nodes:" + resp.getPoints().getSize() + ", time:"
+ time + " " + resp.getDebugInfo());
logUser("the route is " + (int) (resp.getDistance() / 100) / 10f
+ "km long, time:" + resp.getMillis() / 60000f + "min, debug:" + time);
localPolyline=createPolyline(resp);
mapView.getLayerManager().getLayers().add(localPolyline);
} else
{
logUser("Error:" + resp.getErrors());
}
}
}.execute();
}
Thanks to everybody.

Related

How to get the results from multiple servers in a function in Android

I'm installing Hybrid Ranking algorithm for Linked Data Extraction & Context on Android. Documents you can search Google for the keywords above.
And now I'm installing semantic similarity between two uri1 and uri2.
Input: two DBpedia URIs
Output: a value representing their similarity
private float similarity(String uri1, String uri2) {
float wikipedia = wikiS(uri1, uri2);
float abtract = abtractS(uri1, uri2);
float google = engineS(uri1, uri2, google);
float yahoo = engineS(uri1, uri2, yahoo);
float bing = engineS(uri1, uri2, bing);
float dilicious = engineS(uri1, uri2, dilicicous);
return wikipedia + abtract + google + yahoo + bing + dilicious;
}
And with each child function, I have to query data using SPARQL dbpedia, google, yahoo, bing, dilicious using provided API. The results obtained will be calculated to the parser and returns the corresponding float value.
Example for abtractS(uri1, uri2) below:
private float abstractS(String uri1, String uri2, final float wikiS){
String url = createUrlAbstractS(uri1, uri2);
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
float abtractS = 0.0f;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray data = jsonObject.getJSONObject("results").getJSONArray("bindings");
if(data.length() == 0){
showLogAndToast("No result");
}else{
JSONObject element = data.getJSONObject(0);
String label1 = element.getJSONObject("label1").getString("value");
String abtract1 = element.getJSONObject("abtract1").getString("value");
String label2 = element.getJSONObject("label2").getString("value");
String abtract2 = element.getJSONObject("abtract2").getString("value");
abtractS = calWordContained(label1, abtract2) + calWordContained(label2, abtract1) + wikiS;
//TODO: RESULT ABTRACTS HERE. How next?
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(request);
return 0.0f;//HERE: no results
}
private float calWordContained(String label, String abtract){
if(label.length() == 0 || abtract.length() == 0){
return 0.0f;
}
List<String> words = Arrays.asList(label.split(" "));
int count = 0;
float length = words.size();
for(int i = 0; i < length; i++){
if(abtract.toLowerCase().contains(words.get(i).toLowerCase())){
count++;
}
}
return (count/length);
}
public String createUrlAbstractS(String uri1, String uri2){
private String BASE_URL_DBPEDIA = "http://dbpedia.org/sparql?default-graph-uri=&query=";
String query = createQueryAbstractS(uri1, uri2);
String url = "";
try {
url = Config.BASE_URL_DBPEDIA + URLEncoder.encode(query, "UTF-8") + Config.RESULT_JSON_TYPE;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url;
}
private String createQueryAbstractS(String uri1, String uri2){
String query = Config.PREFIX_DBPEDIA + " \n" +
"prefix dbpedia-owl: <http://dbpedia.org/ontology/>\n" +
"\n" +
"\n" +
"select ?label1, ?label2, ?abtract1, ?abtract2 where\n" +
"{\n" +
" {\n" +
" select *\n" +
" where{\n" +
" <" + uri1 + "> rdfs:label ?label1 ;\n" +
" dbpedia-owl:abstract ?abtract1 .\n" +
" FILTER langMatches(lang(?abtract1),'en') . \n" +
" FILTER langMatches(lang(?label1),'en') .\n" +
" }\n" +
" }\n" +
"\n" +
"\n" +
" {\n" +
" select *\n" +
" where{\n" +
" <" + uri2 + "> rdfs:label ?label2 ;\n" +
" dbpedia-owl:abstract ?abtract2 .\n" +
" FILTER langMatches(lang(?label2),'en') . \n" +
" FILTER langMatches(lang(?abtract2),'en') .\n" +
" }\n" +
" }\n" +
"}";
return query;
}
but how to do this on, I could not get the results I wanted in the similarity function (uri1, uri2). Therefore it will affect the results in different functions.
So I'm asking is: how can I get all the results of the function Wikis, abtractS, engine (google), engine (bing), engine (yahoo), engine (dilicious) in a simple way Best. I currently do on Android and data load times is very important.
Thank you very much!

Draw routes path based on my own markers in android Google maps v2

I doing my android project about bus tracker in Uni campus. I need to draw a route from a bus stop to another bus stop and until back to origin bus stop.(There is about 20 bus stop in my Uni, need to draw route to let first user know the route of buses).
I managed to draw a path by following this tutorial here
In another tutorial , I found a blog which teaching draw path on google maps in 3 location. The sample code is
private static final LatLng LOWER_MANHATTAN = new LatLng(40.722543,-73.998585);
private static final LatLng BROOKLYN_BRIDGE = new LatLng(40.7057, -73.9964);
private static final LatLng WALL_STREET = new LatLng(40.7064, -74.0094);
private String getMapsApiDirectionsUrl() {
String waypoints = "waypoints=optimize:true|"
+ LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude
+ "|" + "|" + BROOKLYN_BRIDGE.latitude + ","
+ BROOKLYN_BRIDGE.longitude + "|" + WALL_STREET.latitude + ","
+ WALL_STREET.longitude;
String sensor = "sensor=false";
String params = waypoints + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}
but I got an error which are:
java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/directions/json?waypoints=optimize:true|2.920114,101.775244||2.919726,101.771172|2.92234,101.769628&sensor=false
E/Background Task: java.lang.NullPointerException
E/ParserTask: errororg.json.JSONException: End of input at character 0 of
The tutorial of the blog is same with the link. Just different in
String waypoints = "waypoints=optimize:true|"
+ LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude
+ "|" + "|" + BROOKLYN_BRIDGE.latitude + ","
+ BROOKLYN_BRIDGE.longitude + "|" + WALL_STREET.latitude + ","
+ WALL_STREET.longitude;
and
/ Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
Can anyone give me some tutorial or guidance in draw path in multiple markes? Thank in advance!
First of all you need to fix your method
private static final LatLng LOWER_MANHATTAN = new LatLng(40.722543,-73.998585);
private static final LatLng BROOKLYN_BRIDGE = new LatLng(40.7057, -73.9964);
private static final LatLng WALL_STREET = new LatLng(40.7064, -74.0094);
private String getMapsApiDirectionsUrl() {
String origin = "origin=" + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude;
String waypoints = "waypoints=optimize:true|" + BROOKLYN_BRIDGE.latitude + "," + BROOKLYN_BRIDGE.longitude + "|";
String destination = "destination=" + WALL_STREET.latitude + "," + WALL_STREET.longitude;
String sensor = "sensor=false";
String params = origin + "&" + waypoints + "&" + destination + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}
To get draw path i followed this answer https://stackoverflow.com/a/14702636/2697368
Once you get the JSON, just do it
public void drawPath(String result) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#05b1fb"))//Google maps blue color
.geodesic(true)
);
} catch (JSONException e) {
}
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
Sometimes it happens when wrong url generated Using points..
May this function will help.
It worked for me so I shared..
public static String getMapsApiDirectionsUrl( LatLng start, LatLng End ) {
String waypoints = "waypoints=optimize:true|"
+ start.latitude + "," + start.longitude
+ "|" + "|" + End.latitude + ","
+ End.longitude;
String OriDest = "origin="+start.latitude+","+start.longitude+"&destination="+End.latitude+","+End.longitude;
String sensor = "sensor=false";
String params = OriDest+"&%20"+waypoints + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}
Thanks.

get maximum value of a object

I have a little problem. I get data from more then one Beacon and I put it into an arrayList. Now I want that the nearest one should be returned.
ArrayList<Beacon> arrayList = new ArrayList<Beacon>();
String beaconName;
public void addToBeaconInfo(Beacon beacon) {
boolean beaconAlreadyInList = false;
//arrayList.add(beacon);
beaconName = "" + beacon.getId2() + "" + beacon.getId3();
//Log.i("BeaconInfo","addBeacon_beaconName: "+beaconName + " distance" + beacon.getDistance());
int i;
for(i = 0; i < arrayList.size(); i++){
Beacon tempBeacon = arrayList.get(i);
if(tempBeacon.getId2().equals(beacon.getId2())){
beaconAlreadyInList = true;
arrayList.remove(beacon);
Log.i("BeaconInfo", "addBeacon_tempBeacon: " + beacon.getId3() + " distance: " + beacon.getDistance());
break;
}
}
if(beaconAlreadyInList == false){
arrayList.add(beacon);
Log.i("arrayList","" + beacon.getDistance() + " " + beacon.getBluetoothName());
double maxDistance = beacon.getDistance();
//double a = Collections.max(maxDistance);
//Log.i("maxDistance","" + Math.max());
}
}
Beacon nearest = null;
double distance = Double.MAX_VALUE;
for (Beacon beacon: arrayList){
double maxDistance = beacon.getDistance();
if (maxDistance < distance) {
distance = maxDistance;
nearest = beacon;
}
}

map showing blur when i load the static map

when i load the static map using the URL, the map is displaying but its too much blur....kindly give the solution friends...Thanks in advance..........
Here is my code...
public class UpdateMap extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... value) {
Double latter = Double.parseDouble(value[0]);
Double longer = Double.parseDouble(value[1]);
String address = value[2];
try {
String mapurl = "http://maps.google.com/maps/api/staticmap?center="
+ latter
+ ","
+ longer
+ "&zoom=15&size=100x100&sensor=true&markersize=55&markers=color:red%7Clabel:%7C"
+ latter + "," + longer;
double lat1 = Double.valueOf(latter);
double longt1 = Double.valueOf(longer);
Bitmap mapimage = BitmapConvert.bitmaptobitmap(application
.getGoogleMapThumbnail(lat1, longt1, mapurl));
Bitmap crop = crop(mapimage);
String mapimagestring = BitmapConvert.bitmaptostring(crop);
chatHistoryDB.updatemapimage(latter + "/" + longer + "/"
+ address, mapimagestring);
chatAdapter.doubletick();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

google maps v2 draw polyline depends on speed

i have this database:
and i've tried to make a simple polyline drawing which is depends on the speed this way:
Cursor curTAB = myDataBase.rawQuery("SELECT * FROM GPS_Values;", null);
Integer count = 0;
while (curTAB.moveToNext()) {
String s_latitude = curTAB.getString(1);
String s_longitude = curTAB.getString(2);
String s_speed = curTAB.getString(5);
count++;
double latitude = Double.parseDouble(s_latitude);
double longitude = Double.parseDouble(s_longitude);
int speed = Integer.parseInt(curTAB.getString(5).toString());
if (speed <= 50) {
Log.i("Coordinates",
s_latitude.toString() + " --- " + s_longitude.toString() + " --- " +s_speed.toString());
line.add(new LatLng(latitude, longitude)).color(Color.GREEN);
line.color(Color.GREEN);
map.addPolyline(line);
} else {
Log.e("Coordinates",
s_latitude.toString() + " --- " + s_longitude.toString() + " --- " +s_speed.toString());
line.add(new LatLng(latitude, longitude)).color(Color.BLUE);
line.color(Color.BLUE);
map.addPolyline(line);
}
Log.i("Coordinates",
s_latitude.toString() + " --- " + s_longitude.toString() + " --- " +s_speed.toString());
}
curTAB.close();
myDataBase.close();
double latitude = Double.parseDouble(first_lat);
double longitude = Double.parseDouble(first_long);map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
longitude), 15));
map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
But every line is with the same color.
Please help me what did i wrong!
update:
the working code(at the last point it doesn't work but not a big problem)
Integer count = 0;
while (curTAB.moveToNext()) {
String s_latitude = curTAB.getString(1);
String s_longitude = curTAB.getString(2);
String s_speed = curTAB.getString(5);
double latitude = Double.parseDouble(s_latitude);
double longitude = Double.parseDouble(s_longitude);
int speed = Integer.parseInt(curTAB.getString(5).toString());
int position = curTAB.getPosition();
count++;
System.out.println("Curr " + latitude + " --- " + longitude
+ " --- " + speed);
if (curTAB.moveToNext()) {
String next_speed = curTAB.getString(5);
String ss_latitude = curTAB.getString(1);
String ss_longitude = curTAB.getString(2);
System.out.println("Next " + ss_latitude + " --- "
+ ss_longitude + " --- " + next_speed);
curTAB.moveToPosition(position);
double n_latitude = Double.parseDouble(ss_latitude);
double n_longitude = Double.parseDouble(ss_longitude);
if (speed > 60) {
map.addPolyline(new PolylineOptions()
.add(new LatLng(latitude, longitude),
new LatLng(n_latitude, n_longitude))
.width(10).color(Color.RED));
} else if ((speed < 56) && (speed > 31)) {
map.addPolyline(new PolylineOptions()
.add(new LatLng(latitude, longitude),
new LatLng(n_latitude, n_longitude))
.width(10).color(Color.GREEN));
} else if (speed < 31) {
map.addPolyline(new PolylineOptions()
.add(new LatLng(latitude, longitude),
new LatLng(n_latitude, n_longitude))
.width(10).color(Color.rgb(255, 127, 80)));
}
}else{
System.out.println("VÉGE");
}
line.add(new LatLng(latitude, longitude));
}
I'm not familiar with the maps-android-API, but it looks as if you add a new Polyline for each db-entry which will have the same path as the polyline added before plus the new LatLng from the current entry.
The result will be that you only see the polyline created for the last entry which will cover all the other polylines.
I guess you need to set up a new PolylineOptions-object on each iteration and add as Points the LatLngs of the recent entry and of the current entry to get the desired result.

Categories

Resources