Drawing a route on Google Maps API v2 - android

I have a set of points in a text file that I want to plot on a map (API v2) and draw a line through. Each of the points is a <Lat, Lng> and there are a total of 7253 such points in the text file. The code is as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_my_route_mock);
//Step 0. Get google map instance.
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if(map == null) {
Toast.makeText(getApplicationContext(), "Map is not available.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Map is available.", Toast.LENGTH_LONG).show();
}
//Step 0.a. Load a type of map.
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
//Step 0.b. Load your current location on the map.
map.setMyLocationEnabled(true);
if(po == null) {
po = new PolylineOptions();
}
//Toast.makeText(getApplicationContext(), "Location lat = " + loc.getLatitude() + " and longitude = " + loc.getLongitude(), Toast.LENGTH_LONG).show();
//Step 1. Set GPS to service provider.
locMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mocLocProvider = locMgr.GPS_PROVIDER;
locMgr.addTestProvider(mocLocProvider, false, false, true, false, true, false, false, 0, 5);
locMgr.setTestProviderEnabled(mocLocProvider, true);
//locMgr.requestLocationUpdates(mocLocProvider, 0, 0, locLstnr);
//Step 2. Open file for reading from.
try {
is = getAssets().open("locationLogs.txt");
br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
line = br.readLine();
while(line != null) {
//while((line = br.readLine()) != null) {
//there is still a line in the file. parse for gps coordinates etc.
Location l = new Location(LocationManager.GPS_PROVIDER);
String[] details = line.split(","); //the array will contain date, time, lat, long, speed, altitude and accuracy.
l.setTime(System.currentTimeMillis());
l.setLatitude(Double.parseDouble(details[2]));
l.setLongitude(Double.parseDouble(details[3]));
l.setSpeed((float) Double.parseDouble(details[4]));
l.setAltitude(Double.parseDouble(details[5]));
l.setAccuracy((float) Double.parseDouble(details[6]));
//Toast.makeText(getApplicationContext(), l.getLatitude() + "," + l.getLongitude() + "," + l.getSpeed() + "," + l.getAltitude() + "," + l.getAccuracy() + "\n", Toast.LENGTH_SHORT).show();
locMgr.setTestProviderLocation(mocLocProvider, l);
po.add(new LatLng(l.getLatitude(), l.getLongitude()));
Log.v(this.toString(), "Number of po objects = " + po.getPoints().size());
//pl = map.addPolyline(po);
//Log.v(this.toString(), "number of polyline objects added = " + pl.getPoints().size());
line = br.readLine();
}
} catch(FileNotFoundException e) {
Log.v(this.toString(), "File not found.");
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v(this.toString(), "Cannot open file for reading from.");
}
}
After reading about 1300 points, the application collapses with an OutOfMemory exception. Though there are a whole host of threads dealing with memory leakage on Google Maps API v2, closer analysis with MAT reveals that the line: pl = map.addPolyline(po) is the culprit, hogging most of the memory. This turns out to be true, since after that line is commented out, the memory footprint of the above code is very small ~8MB for about 7k points read.
My question(s):
1. Is there anything wrong with the way Polylines object is being used to draw on the map? Once for every update?
2. If so, how can a line be drawn such that it does not take up too much memory? With Canvas and the like or drawing a line only after a certain number of points (say, 10 or so)?
3. Some developers who have used Maps API v2 in their application can maybe shed some light on the proper way to do this?

Call pl = map.addPolyline(po); after the loop to create one polyline and not to try to create 7000 polylines each one "one point longer" than the one before.

Related

Google Direction API cannot find my API Key

I am developing an android app where a customer requests a worker for pickuplocation, so i am using google direction library to show routes between the customer and worker but direction API keeps throwing error saying that you must use an API key to make requests to google cloud platform, already i have created a project in google cloud console and generated my key.
Here is what i have done;
First of all i started my project without a billing account, then in the process of my project i was required to create a billing account in order to make direction request so i linked my project what
What i did;
i added my API key to manifest
i have already enabled places API and direction API
in the direction part i am using google direction library, this one
i added it to app build-gradle
compile 'com.github.jd-alexander:library:1.1.0'
and here is a sample of code in my activity for direction request since i am using the above library i dont know whether it is because i created the project then billing account, what might be the problem?
Even places API does not function properly
private void getRouteToMarker(LatLng customerpickuplocation) {
Routing routing = new Routing.Builder()
.travelMode(AbstractRouting.TravelMode.DRIVING)
.withListener(this)
.alternativeRoutes(false)
.waypoints(new LatLng(lat, lng), customerpickuplocation)
.build();
routing.execute();
}
#Override
public void onRoutingFailure(RouteException e) {
if (e != null) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Something went wrong, Try again", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) {
if (polylines.size() > 0) {
for (Polyline poly : polylines) {
poly.remove();
}
}
polylines = new ArrayList<>();
//add route(s) to the map.
for (int i = 0; i < route.size(); i++) {
//In case of more than 5 alternative routes
int colorIndex = i % COLORS.length;
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(getResources().getColor(COLORS[colorIndex]));
polyOptions.width(10 + i * 3);
polyOptions.addAll(route.get(i).getPoints());
Polyline polyline = mMap.addPolyline(polyOptions);
polylines.add(polyline);
Toast.makeText(getApplicationContext(), "Route " + (i + 1) + ": distance - " + route.get(i).getDistanceValue() + ": duration - " + route.get(i).getDurationValue(), Toast.LENGTH_SHORT).show();
}
}
i have come up with a solution but not a good security measure, by adding key to getRouteToMarker() method
private void getRouteToMarker(LatLng customerpickuplocation) {
Routing routing = new Routing.Builder()
.travelMode(AbstractRouting.TravelMode.DRIVING)
.withListener(this)
.alternativeRoutes(false)
.waypoints(new LatLng(lat, lng), customerpickuplocation)
.key("your api key")
.build();
routing.execute();
}

LatLng value is not being stored persistently in text file on device

In my application, the user has two options to place a marker: 1) via the onMapLongClick method, and 2) by using a voice command. Both of them work properly, but I noticed a bug that showed up only after several hours of the app being closed via the Home button.
If I wait a few hours and come back to the app, the marker is still there; however, I waited approximately 5-6 hours two separate times and the marker was gone.
What am I doing wrong here? This will be very bad for my users because the app is designed to remember a location, even after hours (or days potentially) of closing the app. It's only one marker at a time, not multiple markers.
Here is where the LatLng objects are stored or retrieved:
onMapReady:
//Get Lat and Lng of marker and place on map if marker is there && if app has already been launched
if (prefs.getBoolean("firstrun", false)) {
try {
FileInputStream input = openFileInput("latlngpoints.txt");
DataInputStream din = new DataInputStream(input);
int sz = din.readInt();
for (int i = 0; i < sz; i++) {
String str = din.readUTF();
String[] stringArray = str.split(",");
double lat = Double.parseDouble(stringArray[0]);
double lon = Double.parseDouble(stringArray[1]);
LatLng newLatLng = new LatLng(lat, lon);
m = mMap.addMarker(new MarkerOptions()
.position(newLatLng)
.title("My Ride")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker30x48)));
markerDeleted = false;
}
} catch (IOException e) {}
onActivityResult for voice recognition button:
ArrayList<LatLng> markerLoc = new ArrayList<>();
markerLoc.add(new LatLng(latLng.latitude, latLng.longitude));
try {
FileOutputStream output = openFileOutput("latlngpoints.txt", Context.MODE_PRIVATE);
DataOutputStream dout = new DataOutputStream(output);
dout.writeInt(markerLoc.size());
for (LatLng point : markerLoc) {
dout.writeUTF(point.latitude + "," + point.longitude);
}
dout.flush();
dout.close();
} catch (IOException e) {
//Log.d(TAG, "onActivityResult: " + e.getMessage());
}
onMapLongClick:
ArrayList<LatLng> markerLoc = new ArrayList<>();
markerLoc.add(new LatLng(latLng.latitude, latLng.longitude));
try {
FileOutputStream output = openFileOutput("latlngpoints.txt", Context.MODE_PRIVATE);
DataOutputStream dout = new DataOutputStream(output);
dout.writeInt(markerLoc.size());
for (LatLng point : markerLoc) {
dout.writeUTF(point.latitude + "," + point.longitude);
//Log.d(TAG, "onMapLongClick: " + String.valueOf(point.latitude) + "," + String.valueOf(point.longitude));
}
dout.flush();
dout.close();
} catch (IOException e) {
//Log.d(TAG, "onMapLongClick: " + e.getMessage());
}
Am I supposed to do something in my onPause and onResume methods as well? They are pretty much empty except for stopping a sensor listener for a compass, and checking if location services is enabled.
/*
Stop sensor listeners
Also check for no Network/GPS
*/
#Override
protected void onPause() {
super.onPause();
stopSensorListeners();
}
#Override
protected void onResume() {
super.onResume();
startSensorListeners();
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
//AlertDialog to inform user GPS is off and take them to their Settings activity
buildAlertMessageNoGps();
}
}
I will gladly create a database instead if that is a better way to keep persistent storage.
Ok, it took me a couple of days to get this to work, but I'm going to post what I came up with in case someone else needs help with this.
First, in my onMapReady() I did the following:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
if (prefs.contains("lat") || prefs.contains("lng")) {
double lat = prefs.getFloat("lat", 0.0f);
double lng = prefs.getFloat("lng", 0.0f);
LatLng resumeLatLng = new LatLng(lat, lng);
m = mMap.addMarker(new MarkerOptions()
.position(resumeLatLng)
.title("My Ride")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker30x48)));
markerDeleted = false;
}
In my onMapLongClick() method, I did:
SharedPreferences.Editor locationEditor = getPreferences(MODE_PRIVATE).edit();
locationEditor.clear();
locationEditor.putFloat("lat", (float) m.getPosition().latitude).apply();
locationEditor.putFloat("lng", (float) m.getPosition().longitude).apply();
I have a clear button that removes the marker, so we gotta take care of that puppy as well. So:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.remove("lat");
editor.remove("lng");
editor.apply();
Alright, all good there. Well, what if the user calls the onPause() method? Got it:
if (!markerDeleted) {
SharedPreferences.Editor locationEditor = getPreferences(MODE_PRIVATE).edit();
locationEditor.clear();
locationEditor.putFloat("lat", (float) m.getPosition().latitude).apply();
locationEditor.putFloat("lng", (float) m.getPosition().longitude).apply();
}
And finally, in my onResume() method:
if(!markerDeleted) {
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
double lat = prefs.getFloat("lat", (float) m.getPosition().latitude);
double lng = prefs.getFloat("lng", (float) m.getPosition().longitude);
LatLng resumeLatLng = new LatLng(lat, lng);
m = mMap.addMarker(new MarkerOptions()
.position(resumeLatLng)
.title("My Ride")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker30x48)));
markerDeleted = false;
}
Now, I can add a marker, completely close out the app, come back, and my marker is still there.
If I clear the marker, exit the app, and come back, it is not there.
I successfully created Marker persistence using shared preferences, and no databases. :-)

Drawing a polyline from my location to a marker

I am using Mapbox (4.2.1) to draw a line from my position to a target position. I have the intention of using the straight line as an extremely basic navigation aid. As such I am re-drawing the guide line OnMyLocationChanged(). However it appears that as my location changes it will draw the line to my new location but MyLocationView (User icon) does not update in accordance (See image below).
They will eventually end up meeting again but it takes some time. It seems that the line is getting drawn inside the accuracy radius, however I would prefer if it could draw the line straight from the user icon.
Is there a simple way to draw a line between the user (The actual icon on the map) and a location which updates as the user moves?
My OnMyLocationChanged is:
MapboxMap.OnMyLocationChangeListener listner = new MapboxMap.OnMyLocationChangeListener(){
#Override
public void onMyLocationChange(final #Nullable Location locationChanged) {
//If we are not targeting anything or we are not tracking location
if(target == null || !map.isMyLocationEnabled()) return;
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
//Log.i("LOC-MAPLINE", "Drawing from mapLoc call");
//Error if we don't have a location
if(!mapboxMap.isMyLocationEnabled() || locationChanged == null) return;
LatLng[] points = new LatLng[2];
final Location myLoc = locationChanged;
LatLng loc = new LatLng(myLoc.getLatitude(), myLoc.getLongitude());
LatLng dest = new LatLng(target.getLatitude(), target.getLongitude());
points[0] = loc;
points[1] = dest;
mapboxMap.removeAnnotations();
loadMarker(target);
PolylineOptions poly = new PolylineOptions()
.add(points)
.color(Color.parseColor("#3887be"))
.width(5);
line = mapboxMap.addPolyline(poly);
}
});
}
};
Any assistance is greatly appreciated, thank you!
EDIT (In regards to possible duplicate question - Google direction route from current location to known location)
I believe my question is different for a few reasons.
I am more concerned on getting the location of the user icon overlay rather than actual location (Accuracy issue)
I am not interested in getting turn for turn directions (Like those from a directions API)
I am using Mapbox rather than google maps (Not too sure but there could be some differences).
Nevertheless that question does not seem to answer my question
According to documentation you need only implement this method passing your currentLocation (origin) and destination
private void getRoute(Position origin, Position destination) throws ServicesException {
MapboxDirections client = new MapboxDirections.Builder()
.setOrigin(origin)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_CYCLING)
.setAccessToken(MapboxAccountManager.getInstance().getAccessToken())
.build();
client.enqueueCall(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().getRoutes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
// Print some info about the route
currentRoute = response.body().getRoutes().get(0);
Log.d(TAG, "Distance: " + currentRoute.getDistance());
Toast.makeText(
DirectionsActivity.this,
"Route is " + currentRoute.getDistance() + " meters long.",
Toast.LENGTH_SHORT).show();
// Draw the route on the map
drawRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
Toast.makeText(DirectionsActivity.this, "Error: " + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void drawRoute(DirectionsRoute route) {
// Convert LineString coordinates into LatLng[]
LineString lineString = LineString.fromPolyline(route.getGeometry(), Constants.OSRM_PRECISION_V5);
List<Position> coordinates = lineString.getCoordinates();
LatLng[] points = new LatLng[coordinates.size()];
for (int i = 0; i < coordinates.size(); i++) {
points[i] = new LatLng(
coordinates.get(i).getLatitude(),
coordinates.get(i).getLongitude());
}
// Draw Points on MapView
map.addPolyline(new PolylineOptions()
.add(points)
.color(Color.parseColor("#009688"))
.width(5));
}
reference https://www.mapbox.com/android-sdk/examples/directions/

Dead code using android eclipse

I am working on android application in which i am using a logic to find the direction of a person from coordinated. Everything is working fine but i got error at console: : "Dead Code". My code is given below, please explain me this thing.
private void direction() {
String userLocation = mLatitude + ","
+ mLongitude ;
if(userLocation!=null){
String distLocation = Constants.sMY_LOCATION.getLatitude() + ","
+ Constants.sMY_LOCATION.getLongitude();
String url = "https://maps.google.com/maps?f=d&saddr=" + userLocation
+ "&daddr=" + distLocation;
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}else{ // Getting Dead Code Yellow error here
finish();
Toast.makeText(getBaseContext(), "Please check your internet and try again!", Toast.LENGTH_SHORT).show();
}
}
It's because your else can't be reached
String userLocation = mLatitude + ","
+ mLongitude ;
if(userLocation!=null){
...
}else{
...
}
userLocation will never be null
The code in your else{} will never be reached because your string userLocation is initialized before the if statement, meaning it will never be null.
So the code in you else is effectively dead code.
You should check mLatitude and mLongitude for being null instead of whole String.
Example:
if (mLatitude != null && mLongitude != null) {
// String userLocation = ...
}
else {
// Your else code
}

RoadManager for osmdroid error

I am following a tutorial here https://code.google.com/p/osmbonuspack/wiki/Tutorial_1 but I have encountered an error that it doesn't show the correct route correctly. It just shows a straight line from Point A to Point B.
What I want to achieve is to show the correct route from these points. I'm guessing the error is that it doesn't recognize any nodes to go through.
A similar question has been also asked and I am assuming I have the same problem if I haven't explained my question well.
Similar question can be found here: OSMDroid Routing problems when following a tutorial
Here is a part of my code using RoadManager
Here is a part of the code.
try {
//get current longlat
gpsLocator.getLocation();
cur_loc_lat =gpsLocator.getLatitude();
cur_loc_long =gpsLocator.getLongitude();
} catch (Exception e) {
// TODO: handle exception
}
//--- Create Another Overlay for multi marker
anotherOverlayItemArray = new ArrayList<OverlayItem>();
anotherOverlayItemArray.add(new OverlayItem(
"UST", "UST", new GeoPoint( testlat, testlong)));
//--- Create Another Overlay for multi marker
anotherOverlayItemArray.add(new OverlayItem(
locDefine[0], "UST", new GeoPoint( sel_latitude, sel_longitude)));
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay
= new ItemizedIconOverlay<OverlayItem>(
TomWalks.this, anotherOverlayItemArray, myOnItemGestureListener);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
//---
//Add Scale Bar
ScaleBarOverlay myScaleBarOverlay = new ScaleBarOverlay(TomWalks.this);
myOpenMapView.getOverlays().add(myScaleBarOverlay);
try {
//1 Routing via road manager
RoadManager roadManager = new MapQuestRoadManager();
roadManager.addRequestOption("routeType=pedestrian");
/*
roadManager.addRequestOption("units=m");
roadManager.addRequestOption("narrativeType=text");
roadManager.addRequestOption("shapeFormat=raw");
roadManager.addRequestOption("direction=0");
*/
//Then, retrieve the road between your start and end point:
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
waypoints.add(new GeoPoint(testlat, testlong));
waypoints.add(new GeoPoint(sel_latitude,sel_longitude)); //end point
Road road = roadManager.getRoad(waypoints);
// then, build an overlay with the route shape:
PathOverlay roadOverlay = RoadManager.buildRoadOverlay(road, myOpenMapView.getContext());
roadOverlay.setColor(Color.GREEN);
//Add Route Overlays into map
myOpenMapView.getOverlays().add(roadOverlay);
myOpenMapView.invalidate();//refesh map
final ArrayList<ExtendedOverlayItem> roadItems =
new ArrayList<ExtendedOverlayItem>();
ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes =
new ItemizedOverlayWithBubble<ExtendedOverlayItem>(TomWalks.this, roadItems, myOpenMapView);
myOpenMapView.getOverlays().add(roadNodes);
myOpenMapView.invalidate();//refesh map
int nodesize=road.mNodes.size();
double length = road.mLength;
Drawable marker = getResources().getDrawable(R.drawable.marker_node);
Toast.makeText(TomWalks.this, " Distance : " + length + " Nodes : "+nodesize ,Toast.LENGTH_SHORT).show();
for (int i=0; i<road.mNodes.size(); i++)
{
RoadNode node = road.mNodes.get(i);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem("Step "+i, "", node.mLocation, TomWalks.this);
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
roadNodes.addItem(nodeMarker);
nodeMarker.setDescription(node.mInstructions);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
Drawable icon = getResources().getDrawable(R.drawable.marker_node);
nodeMarker.setImage(icon);
}//end for
myOpenMapView.getOverlays().add(roadNodes);
myOpenMapView.invalidate();//refesh map
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(TomWalks.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
myMapController.setCenter(new GeoPoint( sel_latitude, sel_longitude));
} catch (Exception e) {
// TODO: handle exception
}
}
}
}//===================================================================================================
Let's try to provide a complete answer to this quite frequent question.
Basically, when you get the "straight line", it means that the RoadManager got an error.
So, first of all, in your code, you should check the result of getRoad, this way:
if (road.mStatus != Road.STATUS_OK){
//handle error... warn the user, etc.
}
Now, where this error is coming from?
=> You must search in the logcat. You should find the full url that has been sent, and probably a stacktrace about the error.
I strongly recommend that you copy/paste this full url in a browser , and check the result.
Here are the typical errors, by decreasing probability:
1) You didnt' read carefully the "Important note" at the beginning of the Tutorial_0, and you are trying to do a Network call in the main thread, with an SDK >= 3.0.
=> Read this "Important note".
2) You asked for a route that is not possible (really not possible, or because of weird positions, or because of setting unsupported options).
=> This is easy to check by copy/pasting the full url in a web browser, and looking at the answer.
3) Your device has no network connectivity.
4) The routing service changed its API (this happened, more than once...).
=> Could be checked by copy/pasting the full url in a browser.
In this case, raise an Issue in OSMBonusPack project, so that we can take it into account ASAP.
5) The routing service is down.
=> Easy to check by copy/pasting the full url in a browser.
I think it is better to use AsyncTasks in this case:
/**
* Async task to get the road in a separate thread.
*/
private class UpdateRoadTask extends AsyncTask<Object, Void, Road> {
protected Road doInBackground(Object... params) {
#SuppressWarnings("unchecked")
ArrayList<GeoPoint> waypoints = (ArrayList<GeoPoint>)params[0];
RoadManager roadManager = new OSRMRoadManager();
return roadManager.getRoad(waypoints);
}
#Override
protected void onPostExecute(Road result) {
road = result;
// showing distance and duration of the road
Toast.makeText(getActivity(), "distance="+road.mLength, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), "durée="+road.mDuration, Toast.LENGTH_LONG).show();
if(road.mStatus != Road.STATUS_OK)
Toast.makeText(getActivity(), "Error when loading the road - status="+road.mStatus, Toast.LENGTH_SHORT).show();
Polyline roadOverlay = RoadManager.buildRoadOverlay(road,getActivity());
map.getOverlays().add(roadOverlay);
map.invalidate();
//updateUIWithRoad(result);
}
}
then call it new UpdateRoadTask().execute(waypoints);
new Thread(new Runnable()
{
public void run()
{
RoadManager roadManager = new OSRMRoadManager();
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
GeoPoint startPoint = new GeoPoint(source_lat, source_longi);
waypoints.add(startPoint);
GeoPoint endPoint = new GeoPoint(desti_lat,desti_longi);
waypoints.add(endPoint);
try
{
road = roadManager.getRoad(waypoints);
}
catch (Exception e)
{
e.printStackTrace();
}
runOnUiThread(new Runnable()
{
public void run()
{
if (road.mStatus != Road.STATUS_OK)
{
//handle error... warn the user, etc.
}
Polyline roadOverlay = RoadManager.buildRoadOverlay(road, Color.RED, 8, context);
map.getOverlays().add(roadOverlay);
}
});
}
}).start();
And i am use two jar files 1)slf4j-android-1.5.8.jar and 2)osmdroid-android-4.2.jar and osmbonuspack library.
A strange error I found regarding this is as follows:
Firstly I mention following line of code for taking directions for the vehicle "BIKE"
((OSRMRoadManager) roadManager).setMean(OSRMRoadManager.MEAN_BY_BIKE);
Now when it was first called it follows the following URL:
https://routing.openstreetmap.de/routed-car/route/v1/driving/68.8889678000,23.2151582000;73.1808008000,22.3110728000?alternatives=false&overview=full&steps=true
Now when calling the second time{same MEAN_BY_BIKE}, it is following this URL:
:https://routing.openstreetmap.de/routed-bike/route/v1/driving/68.8889678000,23.2151582000;73.1808008000,22.3110728000?alternatives=false&overview=full&steps=true
So the issue is that no response is for the "routed-bike" and it is calling automatically itself when called for second time.
So as a solution I changed my code to the following:
((OSRMRoadManager) roadManager).setMean(OSRMRoadManager.MEAN_BY_CAR);
You can check your LogCat for the same.

Categories

Resources