I am a newbie in android and here is my code, the problem is this code is not able to draw the path on the map.
This my main activity
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import org.w3c.dom.Document;
import java.util.ArrayList;
public class servicing extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
protected GoogleMap mMap;
String lang = "english";
String test = "test";
protected LocationManager locationManager;
Route route = new Route();
LatLng latLng1 = new LatLng(26.903291,75.792482);
LatLng latLng2 = new LatLng(26.907708,75.806044);
ArrayList<LatLng> points = new ArrayList<>(2);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_servicing);
//GMapV2Direction md = new GMapV2Direction();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
/*Document doc = md.getDocument(latLng1, latLng2,
GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
Polyline polylin = mMap.addPolyline(rectLine);*/
points.add(latLng1);
points.add(latLng2);
route.drawRoute(mMap, this, points, true, lang, false);
Toast.makeText(getApplicationContext(),driverdata.extrastmt,Toast.LENGTH_LONG).show();
//route.drawRoute(mMap,this,latLng1,latLng2,lang);
}
@Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom((latLng1),15);
mMap.animateCamera(cameraUpdate);
//route.drawRoute(mMap, this, points, true, lang, false);
}
@Override
public void onProviderEnabled(String provider) {
(Toast.makeText(getApplication(), "Reconnecting", Toast.LENGTH_LONG)).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplication(),"Connection Failed! Check Network!",Toast.LENGTH_LONG).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude", "status");
}
@Override
public void onLocationChanged(Location location) {
Log.d("Latitude", "status");
}
}
And this my route class
public class Route {
GoogleMap mMap;
Context context;
String lang;
static String LANGUAGE_SPANISH = "es";
static String LANGUAGE_ENGLISH = "en";
static String LANGUAGE_FRENCH = "fr";
static String LANGUAGE_GERMAN = "de";
static String LANGUAGE_CHINESE_SIMPLIFIED = "zh-CN";
static String LANGUAGE_CHINESE_TRADITIONAL = "zh-TW";
static String TRANSPORT_DRIVING = "driving";
static String TRANSPORT_WALKING = "walking";
static String TRANSPORT_BIKE = "bicycling";
static String TRANSPORT_TRANSIT = "transit";
public boolean drawRoute(GoogleMap map, Context c, ArrayList<LatLng> points, boolean withIndications, String language, boolean optimize)
{
mMap = map;
context = c;
lang = language;
if(points.size() == 2)
{
String url = makeURL(points.get(0).latitude,points.get(0).longitude,points.get(1).latitude,points.get(1).longitude,"driving");
new connectAsyncTask(url,withIndications).execute();
return true;
}
else if(points.size() > 2)
{
String url = makeURL(points,"driving",optimize);
new connectAsyncTask(url,withIndications).execute();
return true;
}
return false;
}
private String makeURL (ArrayList<LatLng> points, String mode, boolean optimize){
StringBuilder urlString = new StringBuilder();
if(mode == null)
mode = "driving";
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append( points.get(0).latitude);
urlString.append(',');
urlString.append(points.get(0).longitude);
urlString.append("&destination=");
urlString.append(points.get(points.size()-1).latitude);
urlString.append(',');
urlString.append(points.get(points.size()-1).longitude);
urlString.append("&waypoints=");
if(optimize)
urlString.append("optimize:true|");
urlString.append( points.get(1).latitude);
urlString.append(',');
urlString.append(points.get(1).longitude);
for(int i=2;i<points.size()-1;i++)
{
urlString.append('|');
urlString.append( points.get(i).latitude);
urlString.append(',');
urlString.append(points.get(i).longitude);
}
urlString.append("&sensor=true&mode="+mode);
return urlString.toString();
}
private String makeURL (double sourcelat, double sourcelog, double destlat, double destlog,String mode){
StringBuilder urlString = new StringBuilder();
if(mode == null)
mode = "driving";
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString
.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString
.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode="+mode+"&alternatives=true&language="+lang);
return urlString.toString();
}
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;
}
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
boolean steps;
connectAsyncTask(String urlPass, boolean withSteps){
url = urlPass;
steps = withSteps;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if(result!=null){
driverdata.extrastmt = result;
drawPath(result, steps);
//makeT(result);
}else{
driverdata.extrastmt="null";
}
}
}
private void drawPath(String result, boolean withSteps) {
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);
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(4)
.color(Color.BLUE).geodesic(true));
}
if(withSteps)
{
JSONArray arrayLegs = routes.getJSONArray("legs");
JSONObject legs = arrayLegs.getJSONObject(0);
JSONArray stepsArray = legs.getJSONArray("steps");
//put initial point
for(int i=0;i<stepsArray.length();i++)
{
Step step = new Step(stepsArray.getJSONObject(i));
mMap.addMarker(new MarkerOptions()
.position(step.location)
.title(step.distance)
.snippet(step.instructions)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
}
}
catch (JSONException e) {
}
}
/**
* Class that represent every step of the directions. It store distance, location and instructions
*/
private class Step
{
public String distance;
public LatLng location;
public String instructions;
Step(JSONObject stepJSON)
{
JSONObject startLocation;
try {
distance = stepJSON.getJSONObject("distance").getString("text");
startLocation = stepJSON.getJSONObject("start_location");
location = new LatLng(startLocation.getDouble("lat"),startLocation.getDouble("lng"));
try {
instructions = URLDecoder.decode(Html.fromHtml(stepJSON.getString("html_instructions")).toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and finally JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
URL urlnew = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) urlnew.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.d("JSON_RUTA", json);
return json;
}
}
Please I need assistance, and moreover it fetches the data but on the map activity i.e, servicing activity the toast delivers nothing, once you press back and then again on button to start servicing activity, the toast delivers previous results, but no route can be seen on map.