Remove previous route and add new one - android

I have a application containing a map activity which has plenty of markers from my SQLite database and a polyline connecting those markers.
The problem begins when I want to show a route between any clicked marker and my Location.
Problem is it works fine and shows the route for the first time but if any other marker is clicked, a new route is generated without removing previous route.
I know the problem is the following code.
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = new ArrayList<>();
PolylineOptions lineOptions = new PolylineOptions();
for(int i=0;i<result.size();i++){
List<HashMap<String, String>> path = result.get(i);
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);
}
lineOptions.addAll(points);
lineOptions.width(5);
lineOptions.color(Color.WHITE);
}
// googleMap.clear();
//setMarkersPolyLines();
googleMap.addPolyline(lineOptions);
}
My efforts till now:
Googled it and found a way using polyline.remove(); but the problem is if placed after addPolyline then newly created route is also removed and if placed before that then error comes saying polyline might not be initialised.
Tried with if else as
if(flag==0){
polyline = googleMap.addPolyline(lineOptions);
flag++;
}
else if(flag>0)
polyline.remove();
polyline = googleMap.addPolyline(lineOptions);
}
but nothing happened.
Tried these steps but it causes a glitch/fluctuation kind of thing and also some delay.
googleMap.clear();
setMarkersPolyLines(); //setting all my markers again
googleMap.addPolyline(lineOptions);
Atlast, tried initialising points and lineoptions in the for loop but again might not be initialised error and can't set to null as giving nullPointerException as PolylineOptions can't be set to null.
I tried many posts but nothing really was working. Thanks.

I've modified Josef Adamcik's answer and it should work.
boolean isSecond = false;
private Polyline lastPolyline;
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = new ArrayList<>();
PolylineOptions lineOptions = new PolylineOptions();
for(int i=0;i<result.size();i++){
List<HashMap<String, String>> path = result.get(i);
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);
}
lineOptions.addAll(points);
lineOptions.width(5);
lineOptions.color(Color.WHITE);
}
if(isSecond) {
lastPolyline.remove();
lastPolyline = googleMap.addPolyline(lineOptions);
}
else
{
lastPolyline = googleMap.addPolyline(lineOptions);
isSecond=true;
}
}

You should keep a reference to a polyline created in last rendering. This reference should be a field of your class. You should call remove before add but only when lastPolyline is not null.
private Polyline lastPolyline;
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = new ArrayList<>();
PolylineOptions lineOptions = new PolylineOptions();
for(int i=0;i<result.size();i++){
List<HashMap<String, String>> path = result.get(i);
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);
}
lineOptions.addAll(points);
lineOptions.width(5);
lineOptions.color(Color.WHITE);
}
// googleMap.clear();
//setMarkersPolyLines();
if (lastPolyline != null) {
lastPolyline.remove();
}
lastPolyline = googleMap.addPolyline(lineOptions);
}

Related

How to draw polyline on google map in android passing json array?

Hye guys I am working on the project of vehicle tracking system when user can enters the number of vehicle the the draw a poly line on the vehicles route...
I have stored route locations with their latitude and longitude into mysql database I used asynctask method to fetch this data....
now this is my code in getRoute method
getRoute method will be call on the button click when user enters the number in EditText
public void getRoute()
{
final String BusNo = editBusNo.getText().toString().trim();
Log.i(TAG,"value of the Bus No is "+ BusNo);
class GetRoute extends AsyncTask<Void,Void,String>
{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i(TAG,"in pre execute");
loading = ProgressDialog.show(MapsActivity.this, "Fetching...", "Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Log.i(TAG,"post execute");
JSON_STRING = s;
Log.i(TAG,"value of json_string "+ JSON_STRING);
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam("http://192.168.1.35/projects/map.php?name=", BusNo);
Log.i(TAG,"value of s is "+ s);
//Log.i(T,"The value of s is "+ s);
return s;
}
}
GetRoute gr = new GetRoute();
gr.execute();
}
Looking for this type of polyline
Try this,
Polyline polyline;
PolylineOptions polylineOptions = new PolylineOptions();
JSONArray arr = response.getJSONArray("result");
for (int i = 0; i < arr.length(); i++)
{
JSONObject obj = arr.getJSONObject(i);
String latitude = obj.getString("latitude");
String longitude = obj.getString("longitude");
polylineOptions.color(Color.RED);
polylineOptions.width(3);
Double lat = Double.parseDouble(latitude);
Double Longitude = Double.parseDouble(longitude);
polylineOptions.add(new LatLng(lat, Longitude));
}
polyline=map.addPolyline(polylineOptions);
Then when you want to remove it:
polyline.remove();
To plot polyline on google map you need to have List<LatLng> which are stop points between source and destination.
Once you've that List you can plot polyline using below code
// I consider here is list of latlng from database.
List<LatLng> list = getListOfLatLng();
PolylineOptions options = new PolylineOptions().width(10).color(Color.BLUE);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
map.addPolyline(options);
This will plot polylines on map object of GoogleMap.

How to prevent Polyline from overlapping in google maps android?

Hello guys this may be dumb question but am struggling with this so far haven't found any solution. Now let me ask my doubt am using multiple polyline for plotting multiple routes each and every polyline has different colors but when two point intersects last polyline get overridden how to prevent it. How it must look is only first route should get one color and all the other routes must have same color how to do this let me post the code what i have tried so far:
public class GetDistance extends AsyncTask<Double, Void, String> {
private ProgressDialog pd;
private static final int READ_TIMEOUT = 6000;
private static final int CONNECTION_TIMEOUT = 6000;
private int flag;
public GetDistance(int flag) {
this.flag=flag;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(VisitTravel.this);
pd.setMessage("Please wait");
pd.show();
}
#Override
protected String doInBackground(Double... strings) {
URL url;
try {
url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + strings[0] + "," + strings[1] + "&destination=" + strings[2] + "," + strings[3] + "&sensor=false&units=metric&mode=driving&alternatives=true");
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
InputStream in;
in = new BufferedInputStream(conn.getInputStream());
StringBuilder buffer = new StringBuilder();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(in));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine).append("\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
Log.e("empty", "empty");
}
JsonResponse = buffer.toString();
Log.d("response", JsonResponse);
} catch (IOException e1) {
e1.printStackTrace();
}
return JsonResponse;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.dismiss();
if(flag==1) {
new ParserTask().execute(result);
}}
}
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
private ArrayList<LatLng> points;
#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]);
DirectionJSONParser parser = new DirectionJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
PolylineOptions polylineOptionss=null;
// MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
// 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);
if (j == 0) {
duration = point.get("duration");
Log.d("duration", duration);
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polylineOptionss=new PolylineOptions();
// Adding all the points in the route to LineOptions
polylineOptionss.addAll(points);
// polylineOptions.width(7);
// Random rnd = new Random();
// int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
if(i==0) {
polylineOptions0=new PolylineOptions();
polylineOptions0.addAll(points);
// mGoogleMap.setTrafficEnabled(true);
polylineOptions0.width(15);
polylineOptions0.color(Color.parseColor("#9c27b0"));
polylineOptions0.geodesic(true);
Polyline polyline= mGoogleMap.addPolyline(polylineOptions0);
polyline.setTag(duration);
polyline.setClickable(true);
}
//Here only differentiating each and every route.
else if(i==1){
polylineOptions1=new PolylineOptions();
polylineOptions1.addAll(points);
polylineOptions1.geodesic(true);
polylineOptions1.width(15);
// mGoogleMap.setTrafficEnabled(true);
polylineOptions1.color(Color.parseColor("#9e9e9e"));
Polyline polyline= mGoogleMap.addPolyline(polylineOptions1);
polyline.setTag(duration);
polyline.setClickable(true);
///
}
else if(i==2){
polylineOptions2=new PolylineOptions();
polylineOptions2.addAll(points);
polylineOptions2.geodesic(true);
polylineOptions2.width(15);
polylineOptions2.color(Color.parseColor("#9c27b0"));
Polyline polyline= mGoogleMap.addPolyline(polylineOptions2);
polyline.setTag(duration);
polyline.setClickable(true);
// mGoogleMap.setTrafficEnabled(true);
//
}
else {
polylineOptions3=new PolylineOptions();
polylineOptions3.addAll(points);
// mGoogleMap.setTrafficEnabled(true);
polylineOptions3.width(15);
polylineOptions3.geodesic(true);
polylineOptions3.color(Color.parseColor("#9e9e9e"));
Polyline polyline= mGoogleMap.addPolyline(polylineOptions3);
polyline.setTag(duration);
polyline.setClickable(true);
/// polylineOptions3.color(Color.parseColor("#ffffff"));
}
}
setBottomSheet(jsonresponse, edt.getText().toString(),1);
CameraAnimation(polylineOptionss);
// mGoogleMap.addPolyline(polylineOptions);
// Drawing polyline in the Google Map for the i-th route
}
}
How to plot first route with one color from starting to end and then remaining routes with other color. Thanks in advance !!
Use Z-Index variable of Polyline and Use Polylineclick listener to change the z-index of the polylines. Means whenever you click any line, its z-index will be increased and other lines z-index will be decreased so that the line you clicked will always override others. See the attached code for help.
Z-Index
The order in which this tile overlay is drawn with respect to other overlays (including GroundOverlays, TileOverlays, Circles, and Polygons but not Markers). An overlay with a larger z-index is drawn over overlays with smaller z-indices. The order of overlays with the same z-index is arbitrary. The default zIndex is 0.
final List<Polyline> polylines = new ArrayList<>();
for(int i= 0; i<paths.size(); i++ ){
polylines.add(mMap.addPolyline(paths.get(i)));
}
mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
#Override
public void onPolylineClick(Polyline polyline) {
for(int i= 0; i<polylines.size(); i++ ){
polylines.get(i).setColor(Color.argb(255,187,189,191));
polylines.get(i).setZIndex(0);
}
polyline.setColor(Color.argb(255,102,157,246));
polyline.setZIndex(2);
}
});
One possible solution might be to vary the strokeWidth of the overlapping section of the polyline so that the first one drawn is wider and therefore can still be seen under the subsequent ones. Just an idea, not tested.

Null Pointer Exception in AsyncTask class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am getting a NullPointerException int the following code.For the complete program refer http://wptrafficanalyzether.in/blog/showing-nearby-places-using-google-places-api-and-google-map-android-api-v2/.
Logcat
FATAL EXCEPTION: main
Process: com.example.android.googleplaces, PID: 2813
java.lang.NullPointerException
at com.example.android.googleplaces.MainActivity$ParserTask.onPostExecute(MainActivity.java:200)
at com.example.android.googleplaces.MainActivity$ParserTask.onPostExecute(MainActivity.java:169)
and code:
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
if(mGoogleMap!=null)
mGoogleMap.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
if(mGoogleMap!=null)
mGoogleMap.addMarker(markerOptions);
}
}
}
Well If its from mGoogleMap.addMarker(markerOptions); line(and you are sure that markeroptions variable is not null) it means that you are adding the marker while the map is not ready ...
you should call the asyncTask once the map is loaded as the below code :
mGoogleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
//start async task here
}
});
Hope this will help.
Change this line
List<HashMap<String, String>> places = null;
with
List<HashMap<String, String>> places = new ArrayList<HashMap<String, String>>();
Hope it will solve your problem.

google map polyline is not working on android version 5.0(lollipop)

i am trying to draw polyline for googlemap, it is working fine upto android version 4.4(kitkat) but it is not working in android 5.0(lollipop). what to do for working in lollipop also. could you please help me hoe to resolve this issues this is my google map code
public class MapLocation extends FragmentActivity implements OnMarkerClickListener {
GoogleMap map;
ArrayList<LatLng> markerPoints;
LatLng origin,dest1,dest2,dest3;
Marker marker1,marker2,marker3;
PolylineOptions lineOptions = new PolylineOptions();
Polyline line ;
int pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gmap_direction);
markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
map = fm.getMap();
if(map!=null){
// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
pos = getIntent().getIntExtra("pos",0);
try{
switch (pos) {
case 1:
dest2 = new LatLng(18.545981, 73.902132);
marker2 = map.addMarker(new MarkerOptions().position(dest2).title("Vivero International Preschool").snippet("PUNE,KALYANINAGAR").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
break;
case 2:
dest2 = new LatLng(17.429122, 78.412745);
marker2 = map.addMarker(new MarkerOptions().position(dest2).title("Vivero International Preschool").snippet("Jubilee Hills").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
break;
case 3:
dest2 = new LatLng(19.115177, 72.909486);
marker2 = map.addMarker(new MarkerOptions().position(dest2).title("Vivero International Preschool").snippet("MUMBAI, POWAI").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
break;
case 4:
dest2 = new LatLng(18.545981, 73.902132);
marker2 = map.addMarker(new MarkerOptions().position(dest2).title("Vivero International Preschool").snippet("PUNE,MAGARPATTA").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
break;
case 5:
dest2 = new LatLng(12.924438, 77.631537);
marker2 = map.addMarker(new MarkerOptions().position(dest2).title("Vivero International Preschool").snippet("Koramangala").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
break;
case 6:
dest2 = new LatLng(12.9044019,77.6690773);
marker2 = map.addMarker(new MarkerOptions().position(dest2).title("Vivero International Preschool").snippet("Sarjapur").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
break;
case 7:
dest2 = new LatLng(12.972442, 77.639195);
marker2 = map.addMarker(new MarkerOptions().position(dest2).title("Vivero International Preschool").snippet("Indiranagar").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
break;
case 8:
dest2 = new LatLng(12.968719, 77.747883);
marker2 = map.addMarker(new MarkerOptions().position(dest2).title("Vivero International Preschool").snippet("Whitefield").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
break;
// dest1 = new LatLng(19.115177, 72.909486);
}
// Showing the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(dest2));
// Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(15));
marker2.showInfoWindow();
if(location!=null){
onLocationChanged(location);
String url = getDirectionsUrl(origin, dest2);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
catch(Exception e){
}
}
}
/** A class to parse the Google Places 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;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
//lineOptions = 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);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(4);
lineOptions.color(Color.BLUE);
}
// Drawing polyline in the Google Map for the i-th route
//map.addPolyline(lineOptions);
line = map.addPolyline(lineOptions);
}
}
}
Try the modified codes for your onPostExecute:
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
//PolylineOptions lineOptions = null;
//MarkerOptions markerOptions = new MarkerOptions();
points = new ArrayList<LatLng>();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
//points = new ArrayList<LatLng>();
//lineOptions = 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);
}
// Adding all the points in the route to LineOptions
//lineOptions.addAll(points);
//lineOptions.width(4);
//lineOptions.color(Color.BLUE);
}
// Drawing polyline in the Google Map for the i-th route
//map.addPolyline(lineOptions);
lineOptions.addAll(points);
lineOptions.width(4);
lineOptions.color(Color.BLUE);
line = map.addPolyline(lineOptions);
}
I moved your list points instance before for loop, and also lineOptions after for loop.
Hope this help.
Now Again Google has released a new API but they haven't updated the documentation properly.To connect to the API, you need to create an instance of the Google Play services API client.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
Once you have connected to Google Play services and the location services API, you can get the last known location of a user's device. When your app is connected to these you can use the fused location provider's getLastLocation() method to retrieve the device location. To do this you have to implements this interfaces in your Class/Activity
implements
ConnectionCallbacks, OnConnectionFailedListener
Then you can found this implemented methods
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
Here is my complete code into this thread
. Documentation is here

Android Google Maps. Polylines not drawn correctly

I am trying to draw a costume route on a Google map. The route is displayed but I get some extra polylines in it:
As you can see the route is really messed up can anyone tell me how can I fix this issue?
I am drawing the lines using this method:
// Executes in UI thread, after the parsing process
protected void onPostExecute(List<List<HashMap<String, String>>> result)
{
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for(int i=0;i<result.size();i++)
{
points = new ArrayList<LatLng>();
lineOptions = 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);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(7);
lineOptions.color(Color.GREEN);
}
// Drawing polyline in the Google Map for the i-th route
mGoogleMap.addPolyline(lineOptions);
}
and I am putting the coordinates of the segments using this code:
public List<List<HashMap<String,String>>> parse(Variant variant)
{
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>();
try
{
/** Traversing all routes */
for(int i=0;i < variant.route.length; i++)
{
List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j < variant.route[i].segments.length; j++)
{
/** Traversing all points */
for(int l=0;l < variant.route[i].segments[j].coordinate.length; l++)
{
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(variant.route[i].segments[j].coordinate[l].latitude));
hm.put("lng", Double.toString(variant.route[i].segments[j].coordinate[l].longitude));
path.add(hm);
}
}routes.add(path);
}
}catch (Exception e){
}
return routes;
}
}

Categories

Resources