Google map change polyline strokeweight when zoom change - android

How can change polyline strokeweight when zoom change like Uber
The Polyline width change when the camera zoom change

You can add listener to listen the onCameraIdle event. This event happens each time the camera finished movement. Inside this listener you can calculate a width of the line according to the camera zoom.
I've created a simple example that executes sample directions request to get a sample polyline and draws this polyline on map. The onCameraIdle listener recalculates the polyline width. Please have a look at sample code:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnCameraIdleListener {
private GoogleMap mMap;
private Polyline mPoly;
private String TAG = MapsActivity.class.getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng pos = new LatLng(41.381087,2.176731);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 16));
mMap.getUiSettings().setZoomControlsEnabled(true);
//Get sample polyline and draw it
List<LatLng> path = this.getSamplePoly();
if (path.size() > 0) {
PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(this.getLineWidth());
mPoly = mMap.addPolyline(opts);
}
//Set listener for camera idle event
mMap.setOnCameraIdleListener(this);
}
#Override
public void onCameraIdle() {
mPoly.setWidth(this.getLineWidth());
}
//Defines a width of polyline as some function of zoom
private int getLineWidth() {
float zoom = mMap.getCameraPosition().zoom;
float a = (zoom-12>0 ? (zoom-12)*(zoom-12) : 1);
return Math.round(a);
}
//Executes directions request to get sample polyline
private List<LatLng> getSamplePoly () {
List<LatLng> path = new ArrayList();
GeoApiContext context = new GeoApiContext.Builder()
.apiKey("YOUR_API_KEY")
.build();
DirectionsApiRequest req = DirectionsApi.getDirections(context, "41.381624,2.176058", "41.380503,2.177116");
try {
DirectionsResult res = req.await();
//Loop through legs and steps to get encoded polylines of each step
if (res.routes != null && res.routes.length > 0) {
DirectionsRoute route = res.routes[0];
if (route.legs !=null) {
for(int i=0; i<route.legs.length; i++) {
DirectionsLeg leg = route.legs[i];
if (leg.steps != null) {
for (int j=0; j<leg.steps.length;j++){
DirectionsStep step = leg.steps[j];
if (step.steps != null && step.steps.length >0) {
for (int k=0; k<step.steps.length;k++){
DirectionsStep step1 = step.steps[k];
EncodedPolyline points1 = step1.polyline;
if (points1 != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
for (com.google.maps.model.LatLng coord1 : coords1) {
path.add(new LatLng(coord1.lat, coord1.lng));
}
}
}
} else {
EncodedPolyline points = step.polyline;
if (points != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords = points.decodePath();
for (com.google.maps.model.LatLng coord : coords) {
path.add(new LatLng(coord.lat, coord.lng));
}
}
}
}
}
}
}
}
} catch(Exception ex) {
Log.e(TAG, ex.getLocalizedMessage());
}
return path;
}
}
You can download this example from the github repository:
https://github.com/xomena-so/so45566330
Don't forget replace API keys with yours.
I hope this helps!

Related

Delete polyline behind Current Location Marker Like Uber android [duplicate]

I have googleMap (v2) with polyline that presents a route between the user current location and the destination point. Now, I want to update the polyline according to the user moving.
I tried to redrawing the whole polyline when location is changed but the polyline is flickering.
I didn't find any appropriate function in the PolylineOptions class (the function add() is only to add a vertex but not to update or remove)
do you have any idea how to update the polyline ???
thank you for giving your time.
The only way as of version 3.1.36:
List<LatLng> points = polyline.getPoints();
points.add(newPoint);
polyline.setPoints(points);
Hopefully the API will be enhanced in later versions.
*I have already done working on updating polyline path without removing the polyline. We can do this by changing the points of that polyline. Check below code.
This is the logic of setting new points to polyline.
/*Here the routes contain the points(latitude and longitude)*/
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
Detail Explanation:
private GoogleMap map_object;
private Marker marker_driver;
private Marker marker_drop_off;
private Polyline polyline_path;
private PolylineOptions polylineOptions_path;
...
...
...
/*HelperDirectionFinder is a class that I create to call google API and I used this
class to get directions routes*/
/*I have created Service, and I'm calling this lines below after 5 sec. to get the
updated routes from google API.*/
HelperDirectionFinder directionFinder = new HelperDirectionFinder(
JobEndScreen.this, source, destinations);
try {
directionFinder.showDirection();
} catch (UnsupportedEncodingException e) {
HelperProgressDialog.closeDialog();
}
...
...
...
#Override
public void onDirectionFinderStart() {
if(polylineOptions_path == null){
HelperProgressDialog.showDialog(getActivity(), "", getString(R.string.text_loading));
}
}
/*This interface method is called after getting routes from google API.*/
/*Here the routes contains the list of path or routes returned by Google Api*/
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
HelperProgressDialog.closeDialog();
/*When polylineOptions_path is null it means the polyline is not drawn.*/
/*If the polylineOptions_path is not null it means the polyline is drawn on map*/
if(polylineOptions_path == null){
for (Route route : routes) {
polylineOptions_path = new PolylineOptions().
geodesic(true).
color(ContextCompat.getColor(getActivity(), R.color.color_bg_gray_dark)).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions_path.add(route.points.get(i));
polyline_path = map_object.addPolyline(polylineOptions_path);
}
}
else {
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
}
}
//Declare on global
PolylineOptions polyOptions, polyOptions2;
Polyline polyline2;
List<LatLng> ltln;
private Double lat_decimal = 0.0,lng_decimal=0.0;
//initialize
ltln = new ArrayList<>();
//if you are using routing library
compile 'com.github.jd-alexander:library:1.0.7'
#Override
public void onRoutingSuccess(ArrayList<Route> arrayList, int i) {
//Add this code snippet on onRoutingSuccess to store latlan list
ltln = new ArrayList<>();
System.out.println("-----arrayList------" + arrayList.get(0).getPoints());
ltln = arrayList.get(0).getPoints();
// NOTE here already we draw polyLine 1
}
//below mentioned how to update polyline
private void UpdatePoliline(){
System.out.println("-------runnablePolyline-------"+ltln.size());
try {
if (ltln.size() > 0) {
for (int i = 0; i < ltln.size(); i++) {
ltln.remove(i);
if (CalculationByDistance(ltln.get(i), new LatLng(lat_decimal, lng_decimal)) >= 10) {
break;
}
}
polyOptions2 = new PolylineOptions();
polyOptions2.color(getResources().getColor(R.color.app_color));
polyOptions2.width(7);
polyOptions2.addAll(ltln);
if (polyline2 == null) {
polyline2 = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline2);
if (polyline != null) {
polyline.remove();
polyline = null;
}
} else {
polyline = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline);
if (polyline2 != null) {
polyline2.remove();
polyline2 = null;
}
}
System.out.println("=====waypoints new===" + ltln);
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
// Calculating distance between 2 points
public float CalculationByDistance(LatLng StartP, LatLng EndP) {
Location locationA = new Location("Source");
locationA.setLatitude(StartP.latitude);
locationA.setLongitude(StartP.longitude);
Location locationB = new Location("Destination");
locationB.setLatitude(EndP.latitude);
locationB.setLongitude(EndP.longitude);
float distance = locationA.distanceTo(locationB);
return distance;
}
//Redraw Polyline vehicle is not in current polyline with particular distance
if (ltln.size() > 0) {
if (PolyUtil.isLocationOnPath(new LatLng(currentlat, currentLon), ltln, false, 60.0f) ){
System.out.println("===tolarance===" + true);
} else {
//Redraw Polyline
}
}
UpdatePoliline();

Adding multiple markers to google map from array list of latitude and longitude coordinates

Currently I have an app that gets the phones GPS location in the background and adds the longitude and latitude coordinates to two separate array lists, I know this part is working fine, however when I do my button click to plot the points to my map it only plots the very first point when I have hundreds in my array list
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0;i<latitude.size();i++)
{
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude.get(i), longitude.get(i))).title("LOCATION " + latitude.get(i) + ", " + longitude.get(i)));
Log.d("LOCATION", latitude.get(i)+ "," + longitude.get(i));
}
Log.d("Count", ""+longitude.size());
}
});
Try this code, I am taking a list of Data class which contains latitude and longitude information which i am setting in Marker options to display on the map. If you want to animate camera you can pass the builder instance to animateCamera and the maps will animate you to all the markers which has been added.
private void insertMarkers(List<Data> list) {
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (int i = 0; i < list.size(); i++) {
final Lat Lng position = new LatLng(list.get(i).getCurrent_lat(), list.get(i).getCurrent_lng());
final MarkerOptions options = new MarkerOptions().position(position);
mMaps.addMarker(options);
builder.include(position);
}
}
I do it like this to show motors positions on the map with markers of different colors:
private void addMarkersToMap() {
mMap.clear();
for (int i = 0; i < Motors.size(); i++) {
LatLng ll = new LatLng(Motors.get(i).getPos().getLat(), Motors.get(i).getPos().getLon());
BitmapDescriptor bitmapMarker;
switch (Motors.get(i).getState()) {
case 0:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
Log.i(TAG, "RED");
break;
case 1:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN);
Log.i(TAG, "GREEN");
break;
case 2:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE);
Log.i(TAG, "ORANGE");
break;
default:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
Log.i(TAG, "DEFAULT");
break;
}
mMarkers.add(mMap.addMarker(new MarkerOptions().position(ll).title(Motors.get(i).getName())
.snippet(getStateString(Motors.get(i).getState())).icon(bitmapMarker)));
Log.i(TAG,"Car number "+i+" was added " +mMarkers.get(mMarkers.size()-1).getId());
}
}
}
Motors is an ArrayList of custom objects and mMarkers is an ArrayList of markers.
Note : You can show map in fragment like this:
private GoogleMap mMap;
....
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
// Hide the zoom controls as the button panel will cover it.
mMap.getUiSettings().setZoomControlsEnabled(false);
// Add lots of markers to the map.
addMarkersToMap();
// Setting an info window adapter allows us to change the both the
// contents and look of the
// info window.
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
// Set listeners for marker events. See the bottom of this class for
// their behavior.
mMap.setOnMarkerClickListener(this);
mMap.setOnInfoWindowClickListener(this);
mMap.setOnMarkerDragListener(this);
// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.
final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressLint("NewApi")
// We check which build version we are using.
#Override
public void onGlobalLayout() {
LatLngBounds.Builder bld = new LatLngBounds.Builder();
for (int i = 0; i < mAvailableCars.size(); i++) {
LatLng ll = new LatLng(Cars.get(i).getPos().getLat(), Cars.get(i).getPos().getLon());
bld.include(ll);
}
LatLngBounds bounds = bld.build();
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 70));
mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
}
}
And just call setUpMapIfNeeded() in onCreate()

Android setOnMarkerClickListener set title for each marker

I've implemented a clustermarker in my app, I have a list of LatLng that comes from my database, now I want to show the name of the clients as title when the user clicks on the marker,but when I click on the marker it shows me nothing, how can I achieve that, this is my code so far:
public class MapaViagem extends FragmentActivity {
private GoogleMap googleMap;
private String rm_IdViagem;
private List<ClienteModel> mClienteModel = new ArrayList<ClienteModel>();
private List<EnderecoModel> mEnderecoModel = new ArrayList<EnderecoModel>();
private ViagemModel mViagemModel = new ViagemModel();
private ClusterManager<MyItem> mClusterManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
ArrayList<LatLng> coordList = new ArrayList<LatLng>();
try {
Bundle parametros = getIntent().getExtras();
rm_IdViagem = parametros.getString("id_viagem");
Repositorio ca = new Repositorio(this);
mViagemModel = ca.getViagemPorId(Integer.valueOf(rm_IdViagem));
Repositorio cl = new Repositorio(this);
mClienteModel = cl.getClientesViagem(Integer.valueOf(rm_IdViagem));
int i;
for ( i = 0; i < mClienteModel.size(); i++) {
Repositorio mRepositorio = new Repositorio(this);
mEnderecoModel = mRepositorio.getListaEnderecosDoCliente(Integer.valueOf(mClienteModel.get(i).getClientes_id()));
System.out.println("NOMES " + mClienteModel.get(i).getNome());
for (int j = 0; j < mEnderecoModel.size(); j++) {
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
final float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
final float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());
coordList.add(new LatLng(latitude, longitude));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 10));
// Initialize the manager with the context and the map.
// (Activity extends context, so we can pass 'this' in the constructor.)
mClusterManager = new ClusterManager<MyItem>(this, googleMap);
// Point the map's listeners at the listeners implemented by the cluster
// manager.
googleMap.setOnCameraChangeListener(mClusterManager);
googleMap.setOnMarkerClickListener(mClusterManager);
addItems(coordList);
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(final Marker marker) {
LatLng pos = marker.getPosition();
int arryListPosition = getArrayListPosition(pos);
return true;
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private int getArrayListPosition(LatLng pos) {
for (int i = 0; i < mEnderecoModel.size(); i++) {
if (pos.latitude == Double.parseDouble(mEnderecoModel.get(i).getLatitude().split(",")[0])) {
if (pos.longitude == Double.parseDouble(mEnderecoModel.get(i).getLongitude().split(",")[1]))
return i;
}
}
return 0;
}
private void addItems(List<LatLng> markers) {
for (int i = 0; i < markers.size(); i++) {
MyItem offsetItem = new MyItem(markers.get(i));
mClusterManager.addItem(offsetItem);
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Not sure how you are initializing your Markers because you don't show that part of the code but put a title on it is done this way:
//You need a reference to a GoogleMap object
GoogleMap map = ... // get a map.
Marker marker = map.addMarker(new MarkerOptions()
.position(new LatLng(37.7750, 122.4183)) //Or whatever coordinate
.title("Your title")
.snippet("Extra info"));
And that's it, when you click it you'll see the info of that marker.
You can find more information here
EDIT
For the ClusterManagerI think you can find this answer helpful

How do I dynamically add location points to a Polyline in Android GoogleMap?

I monitor current location and register GoogleMap.MyLocationChangeListener. I want to draw a polyline (track on the map) that represents my own route. On each location update, I'd like to add new point to the route, so that the track on the map is updated.
Here is my code that doesn't work:
private GoogleMap mMap;
private boolean drawTrack = true;
private Polyline route = null;
private PolylineOptions routeOpts = null;
private void startTracking() {
if (mMap != null) {
routeOpts = new PolylineOptions()
.color(Color.BLUE)
.width(2 /* TODO: respect density! */)
.geodesic(true);
route = mMap.addPolyline(routeOpts);
route.setVisible(drawTrack);
mMap.setOnMyLocationChangeListener(this);
}
}
private void stopTracking() {
if (mMap != null)
mMap.setOnMyLocationChangeListener(null);
if (route != null)
route.remove();
route = null;
}
routeOpts = null;
}
public void onMyLocationChange(Location location) {
if (routeOpts != null) {
LatLng myLatLng = new LatLng(location.getLatitude(), location.getLongitude());
routeOpts.add(myLatLng);
}
}
How to add points to the polyline, so that the changes will be reflected in the UI? Right now the polyline is not rendered.
I am using the latest play-services:6.1.71 (as of this date).
This appears to work for me:
public void onMyLocationChange(Location location) {
if (routeOpts != null) {
LatLng myLatLng = new LatLng(location.getLatitude(), location.getLongitude());
List<LatLng> points = route.getPoints();
points.add(myLatLng);
route.setPoints(points);
}
}
Is there a better way?

update polyline according to the user moving android googleMaps v2

I have googleMap (v2) with polyline that presents a route between the user current location and the destination point. Now, I want to update the polyline according to the user moving.
I tried to redrawing the whole polyline when location is changed but the polyline is flickering.
I didn't find any appropriate function in the PolylineOptions class (the function add() is only to add a vertex but not to update or remove)
do you have any idea how to update the polyline ???
thank you for giving your time.
The only way as of version 3.1.36:
List<LatLng> points = polyline.getPoints();
points.add(newPoint);
polyline.setPoints(points);
Hopefully the API will be enhanced in later versions.
*I have already done working on updating polyline path without removing the polyline. We can do this by changing the points of that polyline. Check below code.
This is the logic of setting new points to polyline.
/*Here the routes contain the points(latitude and longitude)*/
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
Detail Explanation:
private GoogleMap map_object;
private Marker marker_driver;
private Marker marker_drop_off;
private Polyline polyline_path;
private PolylineOptions polylineOptions_path;
...
...
...
/*HelperDirectionFinder is a class that I create to call google API and I used this
class to get directions routes*/
/*I have created Service, and I'm calling this lines below after 5 sec. to get the
updated routes from google API.*/
HelperDirectionFinder directionFinder = new HelperDirectionFinder(
JobEndScreen.this, source, destinations);
try {
directionFinder.showDirection();
} catch (UnsupportedEncodingException e) {
HelperProgressDialog.closeDialog();
}
...
...
...
#Override
public void onDirectionFinderStart() {
if(polylineOptions_path == null){
HelperProgressDialog.showDialog(getActivity(), "", getString(R.string.text_loading));
}
}
/*This interface method is called after getting routes from google API.*/
/*Here the routes contains the list of path or routes returned by Google Api*/
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
HelperProgressDialog.closeDialog();
/*When polylineOptions_path is null it means the polyline is not drawn.*/
/*If the polylineOptions_path is not null it means the polyline is drawn on map*/
if(polylineOptions_path == null){
for (Route route : routes) {
polylineOptions_path = new PolylineOptions().
geodesic(true).
color(ContextCompat.getColor(getActivity(), R.color.color_bg_gray_dark)).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions_path.add(route.points.get(i));
polyline_path = map_object.addPolyline(polylineOptions_path);
}
}
else {
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
}
}
//Declare on global
PolylineOptions polyOptions, polyOptions2;
Polyline polyline2;
List<LatLng> ltln;
private Double lat_decimal = 0.0,lng_decimal=0.0;
//initialize
ltln = new ArrayList<>();
//if you are using routing library
compile 'com.github.jd-alexander:library:1.0.7'
#Override
public void onRoutingSuccess(ArrayList<Route> arrayList, int i) {
//Add this code snippet on onRoutingSuccess to store latlan list
ltln = new ArrayList<>();
System.out.println("-----arrayList------" + arrayList.get(0).getPoints());
ltln = arrayList.get(0).getPoints();
// NOTE here already we draw polyLine 1
}
//below mentioned how to update polyline
private void UpdatePoliline(){
System.out.println("-------runnablePolyline-------"+ltln.size());
try {
if (ltln.size() > 0) {
for (int i = 0; i < ltln.size(); i++) {
ltln.remove(i);
if (CalculationByDistance(ltln.get(i), new LatLng(lat_decimal, lng_decimal)) >= 10) {
break;
}
}
polyOptions2 = new PolylineOptions();
polyOptions2.color(getResources().getColor(R.color.app_color));
polyOptions2.width(7);
polyOptions2.addAll(ltln);
if (polyline2 == null) {
polyline2 = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline2);
if (polyline != null) {
polyline.remove();
polyline = null;
}
} else {
polyline = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline);
if (polyline2 != null) {
polyline2.remove();
polyline2 = null;
}
}
System.out.println("=====waypoints new===" + ltln);
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
// Calculating distance between 2 points
public float CalculationByDistance(LatLng StartP, LatLng EndP) {
Location locationA = new Location("Source");
locationA.setLatitude(StartP.latitude);
locationA.setLongitude(StartP.longitude);
Location locationB = new Location("Destination");
locationB.setLatitude(EndP.latitude);
locationB.setLongitude(EndP.longitude);
float distance = locationA.distanceTo(locationB);
return distance;
}
//Redraw Polyline vehicle is not in current polyline with particular distance
if (ltln.size() > 0) {
if (PolyUtil.isLocationOnPath(new LatLng(currentlat, currentLon), ltln, false, 60.0f) ){
System.out.println("===tolarance===" + true);
} else {
//Redraw Polyline
}
}
UpdatePoliline();

Categories

Resources