Try to search your question here, if you can't find : Ask Any Question Now ?

Want to Show Train Route Journey crossed and remaining on mobile app

HomeCategory: stackoverflowWant to Show Train Route Journey crossed and remaining on mobile app
Avatarrupesh asked 4 weeks ago

1st Issue = Not Working as desired which in second image you can view what exactly I want…1st sample image which is not working on mobile app..On Mobile App does not show crossed stations and remaining journey in different colors. Second color just overlaps first one..Working Fine on website, check sample picture….On Web it is displaying perfectly, same want to implement on mobile app..Want to show train route crossed journey in blue color and remaining in red color. I have used direction url api in android. If conditionally trying to show remaining path red color, it is pasting red color on entire path just over on blue color, also blue color not stopping at conditional point where from red should start… Please go through web based pic which is perfect example which I want mobile app too…

2nd issue = one additional polyline is also appearing…which is not required… Polyline must be visible connecting waypoints markers, no separate line required…

I have successfully implemented on web same, tried couple of codes provided by various developers but couldn’t do what exactly required.

package *********
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Dot;
import com.google.android.gms.maps.model.Gap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PatternItem;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{
//public class MapsActivity extends BaseActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private String TAG = MapsActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
Polyline line;
String JourneyID;
LatLng startLatLng = null;
LatLng endLatLng = null;
private LatLng mOrigin;
private LatLng mDestination;
private Polyline mPolyline;
// Bottom Navigation Click Listner
Intent in;
ArrayList
<LatLng>
mMarkerPoints;
int stations;
private static final int PATTERN_GAP_LENGTH_PX = 10;  // 1
private static final Gap GAP = new Gap(PATTERN_GAP_LENGTH_PX);
private static final Dot DOT = new Dot();
private static final List
<PatternItem>
PATTERN_DOTTED = Arrays.asList(DOT, GAP);  // 2
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
//                    Toast.makeText(MapsActivity.this,"Home Clicked ",Toast.LENGTH_LONG).show();
in = new Intent(MapsActivity.this, TrackingRunning.class);
startActivity(in);
break;
/*                case R.id.navigation_dashboard:
Toast.makeText(MapsActivity.this,"Dashboard Clicked ",Toast.LENGTH_LONG).show();
in = new Intent(MapsActivity.this, LoginActivity.class);
startActivity(in);
break;
case R.id.navigation_notifications:
Toast.makeText(MapsActivity.this,"Dashboard Clicked ",Toast.LENGTH_LONG).show();
in = new Intent(MapsActivity.this, TrackingList.class);
startActivity(in);
break;*/
}
return false;
}
};
// Bottom Navigation Click Listner
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mMarkerPoints = new ArrayList<>();
//Onlick event of bottom navigation
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//Onlick event of bottom navigation
Intent intent = getIntent();
JourneyID = intent.getStringExtra("JourneyID");
//        Toast.makeText(MapsActivity.this,"Fetching Train Tracking of Journey ID !! "+JourneyID,Toast.LENGTH_LONG).show();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
* In this case, we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device.
* This method will only be triggered once the user has installed
* Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
new MapsActivity.GetContacts().execute();
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(22.7196,75.8577)));
mMap.animateCamera(CameraUpdateFactory.zoomTo(5));
new MapsActivity.GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MapsActivity.this, "Wait.. Processing", Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://myjsonurl.."+JourneyID;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + url + " : " + jsonStr);
return jsonStr;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
TextView textView = (TextView) findViewById(R.id.textView);
TextView textView2 = (TextView) findViewById(R.id.textView2);
Log.e(TAG, "Data from url: " + result);
// looping through All Contacts
if (result != null) {
try {
// JSON Parsing of data
//JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonArray = jsonObj.getJSONArray("data");
stations = Integer.parseInt(jsonObj.getString("stations"));
PolylineOptions lineOptions = null;
lineOptions = new PolylineOptions();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject oneObject = jsonArray.getJSONObject(i);
double lat = Double.parseDouble(oneObject.getString("lat"));
double lng = Double.parseDouble(oneObject.getString("lng"));
String title = oneObject.getString("title");
String desc = oneObject.getString("desc");
String latitude = oneObject.getString("lat");
String longitude = oneObject.getString("lng");
LatLng position = new LatLng(lat, lng);
if (i == 0) {
LatLng center = new LatLng(lat, lng);
mOrigin = new LatLng(lat, lng);
//                mMap.addMarker(new MarkerOptions().position(center).title("Marker before data"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(center));
}
else
{
mMarkerPoints.add(position);
}
// create marker
// Marker icon
BitmapDescriptor icon;
if (i<=stations) {
icon= BitmapDescriptorFactory.fromResource(R.drawable.train_green);
}
else
{
icon = BitmapDescriptorFactory.fromResource(R.drawable.train_red);
}
//                            marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lng))
.title(title)
.snippet(desc)
.icon(icon);
// Add marker to map
mMap.addMarker(marker);
endLatLng = new LatLng(lat, lng);
}
mDestination=endLatLng;
drawRoute();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MapsActivity.this, "Data not found", Toast.LENGTH_LONG).show();
}
}
}
public void addMarkerToMap(String latitude, String longitude, String title, String description) {
PolylineOptions options = new PolylineOptions().width(5).color(Color.MAGENTA).geodesic(true);
double lat = Double.parseDouble(latitude);
double lng = Double.parseDouble(longitude);
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lng))
.title(title)
.snippet(description);
// Marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// Add marker to map
mMap.addMarker(marker);
}
private void drawRoute(){
// Getting URL to the Google Directions API
String url = getDirectionsUrl(mOrigin, mDestination);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false&travelMode=transit&vehicle.type=RAIL";
// Waypoints
String waypoints = "";
int markers=mMarkerPoints.size();
for(int i=1;i<markers;i++){//i=1 means next point from origin
LatLng point  = (LatLng) mMarkerPoints.get(i);
if(i==1)
waypoints = "waypoints=";
waypoints += point.latitude + "," + point.longitude + "|";
}
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+waypoints;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?key=AIza***************&"+parameters;
https://www.google.com/maps/dir/?api=1&travelmode=driving
Log.e(TAG, "Map url: " +url );
return url;
}
/** A class to download data from Google Directions URL */
private class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
@Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
Log.d("DownloadTask","DownloadTask : " + data);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb  = new StringBuffer();
String line = "";
while( ( line = br.readLine())  != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception on download", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class to parse the Google Directions in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> > {
// Parsing the data in non-ui thread
@Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList
<LatLng>
points = null;
PolylineOptions lineOptions = null;
PolylineOptions lineOptions2 = null;
Log.e(TAG, "Array Size: " + result.size()+ " stations " + stations);
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList
<LatLng>
();
lineOptions = new PolylineOptions();
lineOptions2 = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
//                    Log.e(TAG, "Each Position: " + position );
}
// Adding all the points in the route to LineOptions
/*                    lineOptions.addAll(points);
lineOptions.width(8);
lineOptions.color(Color.BLUE);
*/
if (i<=stations) {
lineOptions.addAll(points);
lineOptions.width(8);
lineOptions.color(Color.BLUE);
}
else
{
lineOptions.addAll(points);
lineOptions.width(8);
lineOptions.color(Color.RED);
lineOptions.pattern(PATTERN_DOTTED);
}
}
// Drawing polyline in the Google Map for the i-th route
if (lineOptions != null) {
if (mPolyline != null) {
mPolyline.remove();
}
mPolyline = mMap.addPolyline(lineOptions);
//      mPolyline = mMap.addPolyline(lineOptions2);
} else
Toast.makeText(getApplicationContext(), "No route is found", Toast.LENGTH_LONG).show();
}
}
}
1 Answers
Best Answer
AvatarMannu answered 4 weeks ago
Your Answer

18 + 11 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com