android find distance and duration between two points on google map - android

i followed the tut in this here https://inducesmile.com/android/android-find-distance-and-duration-between-two-points-on-android-map/
everything seems to be working , only 2 error that i got and everyone who followed the tut
first in MapsActivity
private List<LatLng> getDirectionPolylines(List<RouteObject> routes){
List<LatLng> directionList = new ArrayList<LatLng>();
for(RouteObject route : routes){
List<LegsObject> legs = route.getLegs();
for(LegsObject leg : legs){
String routeDistance = leg.getDistance().getText(); HERE
String routeDuration = leg.getDuration().getText(); HERE
setRouteDistanceAndDuration(routeDistance, routeDuration); // here we will send the route Duration and distent
List<StepsObject> steps = leg.getSteps();
for(StepsObject step : steps){
PolylineObject polyline = step.getPolyline();
String points = polyline.getPoints();
List<LatLng> singlePolyline = decodePoly(points);
for (LatLng direction : singlePolyline){
directionList.add(direction);
}
}
}
}
return directionList;
}
error
Cannot resolve method 'getText()
second error is in LegsObject class
import java.util.List;
public class LegsObject {
private List<StepsObject> steps;
private DistanceObject distance;
private DurationObject duration;
public LegsObject(DurationObject duration, DistanceObject distance, List<StepsObject> steps) {
this.duration = duration;
this.distance = distance;
this.steps = steps;
}
public List<StepsObject> getSteps() {
return steps;
}
public DistanceObject getDistance() {
return distance;
}
public DurationObject getDuration() {
return duration;
}
}
error
Cannot resolve symbol 'DistanceObject'
Cannot resolve symbol 'DurationObject'
i believe if the second error in LegsObject.class fixed the first error will be fixed as well

You can use a third party library for this. It's easy and efficient:
Gradle Dependancy:
compile 'com.akexorcist:googledirectionlibrary:1.0.4' // Custom Google Direction API \\
Code:
Below method will take the latLng of your destination, also inside method you should have latlng object containing your origin. Server key is your api key and you should also enable Google Directions API to make this work.
/**
* Draw polyline on map, get distance and duration of the route
*
* #param latLngDestination LatLng of the destination
*/
private void getDestinationInfo(LatLng latLngDestination) {
progressDialog();
String serverKey = getResources().getString(R.string.google_direction_api_key); // Api Key For Google Direction API \\
final LatLng origin = new LatLng(latitude, longitude);
final LatLng destination = latLngDestination;
//-------------Using AK Exorcist Google Direction Library---------------\\
GoogleDirection.withServerKey(serverKey)
.from(origin)
.to(destination)
.transportMode(TransportMode.DRIVING)
.execute(new DirectionCallback() {
#Override
public void onDirectionSuccess(Direction direction, String rawBody) {
dismissDialog();
String status = direction.getStatus();
if (status.equals(RequestResult.OK)) {
Route route = direction.getRouteList().get(0);
Leg leg = route.getLegList().get(0);
Info distanceInfo = leg.getDistance();
Info durationInfo = leg.getDuration();
String distance = distanceInfo.getText();
String duration = durationInfo.getText();
//------------Displaying Distance and Time-----------------\\
showingDistanceTime(distance, duration); // Showing distance and time to the user in the UI \\
// String message = "Total Distance is " + distance + " and Estimated Time is " + duration;
// StaticMethods.customSnackBar(consumerHomeActivity.parentLayout, message,
// getResources().getColor(R.color.colorPrimary),
// getResources().getColor(R.color.colorWhite), 3000);
//--------------Drawing Path-----------------\\
ArrayList<LatLng> directionPositionList = leg.getDirectionPoint();
PolylineOptions polylineOptions = DirectionConverter.createPolyline(getActivity(),
directionPositionList, 5, getResources().getColor(R.color.colorPrimary));
googleMap.addPolyline(polylineOptions);
//--------------------------------------------\\
//-----------Zooming the map according to marker bounds-------------\\
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(origin);
builder.include(destination);
LatLngBounds bounds = builder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.20); // offset from edges of the map 10% of screen
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
googleMap.animateCamera(cu);
//------------------------------------------------------------------\\
} else if (status.equals(RequestResult.NOT_FOUND)) {
Toast.makeText(context, "No routes exist", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDirectionFailure(Throwable t) {
// Do something here
}
});
//-------------------------------------------------------------------------------\\
}

there is no implementation of :
1) DistanceObject class
2) DurationObject class
public class DistanceObject{
private Integer value;
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
same class for duration
public class DurationObject {
private String text;
private Integer value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
to get distance
Integer disInMeters=routeA.getLegs().get(0).getDistance().getValue();
int kilometers = (int) (disInMeters * 0.001); //convert in KM
to get duration
Integer duration=routeA.getLegs().get(0).getDuration().getValue();
for more help follow this link

Related

Changing marker direction to a specific point

I built an android app with a map and I added some custom markers, let me show you.
I want to rotate that picture to points to an another point. I saved the coordinations for the other point too.
This is what is saved by now in the database about this marker.
Latitude and Longitude are the actual marker's position, and del_lat, del_lng is the delivery address which I want to point to. How can I rotate the image in that position?
Here's my ClusterManagerRenderer
public class ClusterManagerRenderer extends DefaultClusterRenderer<FinalMarkerCluster> {
private final IconGenerator iconGenerator;
private ImageView imageView;
private final int markerWidth;
private final int markerHeight;
public ClusterManagerRenderer(Context context, GoogleMap map, ClusterManager<FinalMarkerCluster> clusterManager) {
super(context, map, clusterManager);
iconGenerator = new IconGenerator(context.getApplicationContext());
imageView = new ImageView(context.getApplicationContext());
markerWidth = (int) context.getResources().getDimension(R.dimen.custom_marker_image);
markerHeight = (int) context.getResources().getDimension(R.dimen.custom_marker_image);
imageView.setLayoutParams(new ViewGroup.LayoutParams(markerWidth,markerHeight));
int padding = (int) context.getResources().getDimension(R.dimen.custom_marker_padding);
imageView.setPadding(padding, padding,padding,padding);
iconGenerator.setContentView(imageView);
}
#Override
protected void onBeforeClusterItemRendered(FinalMarkerCluster item, MarkerOptions markerOptions) {
imageView.setImageResource(item.getIconPicture());
Bitmap icon = iconGenerator.makeIcon();
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(item.getTitle());
}
#Override
protected boolean shouldRenderAsCluster(Cluster<FinalMarkerCluster> cluster) {
return false;
}
}
And here I'm creating the Marker
private void setRendering(List<MarkerCluster> markerClusters) {
for(int i = 0 ;i < markerClusters.size() ;i++) {
LatLng latLng = new LatLng(markerClusters.get(i).getLatitude(), markerClusters.get(i).getLongitude());
String title = markerClusters.get(i).getTitle();
String snippet = markerClusters.get(i).getSnippet();
LatLng delLatLng = new LatLng(markerClusters.get(i).getDel_lat(), markerClusters.get(i).getDel_lng());
int pic = markerClusters.get(i).getIconPicture();
String offerid = markerClusters.get(i).getOfferid();
FinalMarkerCluster finalMarkerCluster = new FinalMarkerCluster(
latLng,
title,
snippet,
pic,
offerid,
delLatLng
);
finalMarkerClusters.add(finalMarkerCluster);
}
if(mGoogleMap != null) {
if(mClusterManager == null) {
mClusterManager = new ClusterManager<FinalMarkerCluster>(getApplicationContext(),mGoogleMap);
}
if(mClusterManagerRender == null) {
mClusterManagerRender = new ClusterManagerRenderer(getApplicationContext(),mGoogleMap,mClusterManager);
mClusterManager.setRenderer(mClusterManagerRender);
}
for(int j = 0; j< finalMarkerClusters.size();j++) {
mClusterManager.addItem(finalMarkerClusters.get(j));
}
mClusterManager.cluster();
}
}
And here's the MarkerCluster object
public class FinalMarkerCluster implements ClusterItem {
private LatLng position;
private String title;
private String snippet;
private int iconPicture;
private String offerId;
private LatLng deliveryPosition;
public FinalMarkerCluster(LatLng position, String title, String snippet, int iconPicture, String offerId, LatLng deliveryPosition) {
this.position = position;
this.title = title;
this.snippet = snippet;
this.iconPicture = iconPicture;
this.offerId = offerId;
this.deliveryPosition = deliveryPosition;
}
WITH GETTERS AND SETTERS
I just want to rotate the image in that point, Thank you in advance!
This doesn't address clustering but for simple marker rotation two things come in handy:
To determine bearing from point A (the lower-right marker on sample screen) to point B use SphericalUtil.computeHeading:
// add two markers
LatLng m1 = new LatLng(40.763807, -80.362280);
LatLng m2 = new LatLng(40.821666, -80.636242);
MarkerOptions m1o = new MarkerOptions().position(m1).title("m1").flat(true);
MarkerOptions m2o = new MarkerOptions().position(m2).title("m2").flat(true);
double hdg = SphericalUtil.computeHeading(m1,m2);
And to rotate the first marker (A, lower-right) in the direction of the second marker apply the bearing to marker to rotate:
m1o.rotation((float)hdg);
And add markers
mMap.addMarker(m1o);
mMap.addMarker(m2o);
Note the use of flat which maintains north-alignment on screen rotation. If that is not desired then remove the flat for the non-rotated- markers.
Note also the rotation is about the anchor point which may need further consideration.
In this image the screen has been rotated so "screen-up" is ~NNW for demo purposes.

Get lat/lng of points along the route after every 100m in android

Using Map Api V2 I have drawn a route on the map. Now i wish to save this route in my database.
So I need to get the lat/lng of points on the route say after each 100 meters which i will save as a polygon. How can i do it in Google Map V2 in android.
i am stuck on it from last 10 days but not getting a solution.
any help will be appriciable :)
public class NavigationActivity extends FragmentActivity {
public static final String TAG_SLAT = "sourcelat";
public static final String TAG_SLONG = "sourcelong";
public static final String TAG_DLAT = "destinationlat";
public static final String TAG_DLONG = "destinationg";
private static LatLng Source = null;
private static LatLng Destination = null;
private GoogleMap map;
private SupportMapFragment fragment;
private LatLngBounds latlngBounds;
private Button bNavigation;
private Polyline newPolyline;
private Marker smarker;
private Marker dmarker;
Geocoder geocoder;
private boolean isTraveling = false;
private int width, height;
private String sourcelat;
private String sourcelong;
private String destinationg;
private String destinationlat;
double slat;
double slong;
double dlat;
double dlong;
double d;
double tempDistance;
String distance;
ConnectionDetector cd;
Boolean isConnectingToInternet = false;
String ts;
LatLng latLng;
GPSTracker gps;
List<Address> addresses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_navigation);
cd = new ConnectionDetector(getApplicationContext());
isConnectingToInternet = cd.isConnectingToInternet();
if (isConnectingToInternet) {
Intent in = getIntent();
sourcelat = in.getStringExtra(TAG_SLAT);
destinationlat = in.getStringExtra(TAG_DLAT);
destinationg = in.getStringExtra(TAG_DLONG);
sourcelong = in.getStringExtra(TAG_SLONG);
slat = Double.parseDouble(sourcelat);
slong = Double.parseDouble(sourcelong);
dlat = Double.parseDouble(destinationlat);
dlong = Double.parseDouble(destinationg);
Source = new LatLng(slat, slong);
Destination = new LatLng(dlat, dlong);
getSreenDimanstions();
fragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
map = fragment.getMap();
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
map.setTrafficEnabled(true);
ImageButton cureent_location = (ImageButton) findViewById(R.id.clocation);
cureent_location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onLocationChanged();
}
});
if (!isTraveling) {
isTraveling = true;
findDirections(Source.latitude, Source.longitude, Destination.latitude, Destination.longitude, GMapV2Direction.MODE_DRIVING);
} else {
isTraveling = false;
}
}else {
AlertUtils.showAlertDialog(NavigationActivity.this, "No Internet Detected", "Please check your internet connection.", false);
}
}
public double calculateDistance(double fromLatitude,double fromLongitude,double toLatitude,double toLongitude)
{
float results[] = new float[1];
try {
Location.distanceBetween(fromLatitude, fromLongitude, toLatitude, toLongitude, results);
} catch (Exception e) {
if (e != null)
e.printStackTrace();
}
if (Source.equals(Destination)){
distance="0";
}
else {
int dist = (int) results[0];
if (dist <= 0)
return 0D;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
results[0] /= 1000D;
distance = decimalFormat.format(results[0]);
double d = Double.parseDouble(distance);
double speed = 40;
double time = d / speed;
ts = manual(time);
Log.v("fdf", String.valueOf(ts));
}
return d;
}
private static String manual(double eta) {
int hour = (int) eta;
eta = (eta - hour) * 60;
int minutes = (int) eta;
eta = (eta - minutes) * 60;
int seconds = (int) eta;
eta = (eta - seconds) * 1000;
int ms = (int) eta;
//Log.d("ffgfh", String.valueOf(eta));
return String.format("%dHr %dMin ", hour, minutes);
}
#Override
protected void onResume() {
super.onResume();
latlngBounds = createLatLngBoundsObject(Source, Destination);
map.moveCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 100));
}
public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.RED);
//MarkerOptions marker = new MarkerOptions().position(Source).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
MarkerOptions marker1 = new MarkerOptions().position(Destination).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
for(int i = 0 ; i < directionPoints.size() ; i++)
{
rectLine.add(directionPoints.get(i));
}
if (newPolyline != null)
{
newPolyline.remove();
}
newPolyline = map.addPolyline(rectLine);
//smarker = map.addMarker(marker);
dmarker = map.addMarker(marker1);
if (isTraveling) {
latlngBounds = createLatLngBoundsObject(Source, Destination);
map.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 100));
Dialog dialog_help = new Dialog(this);
dialog_help .requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog_help.setContentView(R.layout.title_multi_selectitems_dialog);
calculateDistance(slat, slong, dlat, dlong);
TextView dis = (TextView) dialog_help.findViewById(R.id.distance);
dis.setText("Distance " + distance + "Km ");
TextView tim = (TextView) dialog_help.findViewById(R.id.time);
tim.setText("Time " + ts);
dialog_help.setCancelable(true);
dialog_help.setTitle("Distance & Time" );
dialog_help.setCanceledOnTouchOutside(true);
dialog_help.show();
dialog_help.getWindow().setGravity(Gravity.CENTER);
dialog_help.getWindow().setBackgroundDrawable(new ColorDrawable(Color.LTGRAY));
dialog_help.getWindow().setLayout(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
}
else {
map.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 100));
}
}
private void getSreenDimanstions()
{
Display display = getWindowManager().getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
}
private LatLngBounds createLatLngBoundsObject(LatLng firstLocation, LatLng secondLocation)
{
if (firstLocation != null && secondLocation != null)
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(firstLocation).include(secondLocation);
return builder.build();
}
return null;
}
public void findDirections(double fromPositionDoubleLat, double fromPositionDoubleLong, double toPositionDoubleLat, double toPositionDoubleLong, String mode)
{
Map<String, String> map = new HashMap<String, String>();
map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT, String.valueOf(fromPositionDoubleLat));
map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG, String.valueOf(fromPositionDoubleLong));
map.put(GetDirectionsAsyncTask.DESTINATION_LAT, String.valueOf(toPositionDoubleLat));
map.put(GetDirectionsAsyncTask.DESTINATION_LONG, String.valueOf(toPositionDoubleLong));
map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode);
GetDirectionsAsyncTask asyncTask = new GetDirectionsAsyncTask(this);
try {
asyncTask.execute(map);
}catch (Exception e){
Toast.makeText(getBaseContext(), "Something went Wrong", Toast.LENGTH_SHORT).show();
}
}
public void onLocationChanged( ){
TextView cl = (TextView) findViewById(R.id.latlongLocation);
cd = new ConnectionDetector(getApplicationContext());
isConnectingToInternet = cd.isConnectingToInternet();
if (isConnectingToInternet) {
gps = new GPSTracker(NavigationActivity.this);
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
latLng = new LatLng(latitude, longitude);
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0);
String prmises = addresses.get(0).getAddressLine(1);
String city = addresses.get(0).getAddressLine(2);
String country = addresses.get(0).getAddressLine(3);
cl.setText(address + " " + prmises + " " + city + " " + country);
}else {
AlertUtils.showAlertDialog(NavigationActivity.this, "No Internet Detected", "Please check your internet connection.", false);
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}
You can try it with this map application: http://maps.cloudmade.com/.
At first you create your route with waypoints. Click on the button "Get directions" (upper left corner) and create your route (clicking on the map). After that you can export (there is a button on the upper right corner) your route (include waypoints) to a gpx-or a json-file. You can load both files to a GIS.

How to track path on google map?

I want to create an navigation app. I am able to create a polyline path from my current location to destination. I want to create it like google navigation app, means an arrrow navigate the user to the path continously while destination point doesn't arrived. But I don't know how can I do it.
I tried alot for finding it, but unable to find it. Please help me guys.
My code for map is as follow.
public class NavigationActivity extends FragmentActivity implements LocationListener {
public static final String TAG_SLAT = "sourcelat";
public static final String TAG_SLONG = "sourcelong";
public static final String TAG_DLAT = "destinationlat";
public static final String TAG_DLONG = "destinationg";
private static LatLng Source = null;
private static LatLng Destination = null;
private GoogleMap map;
private SupportMapFragment fragment;
private LatLngBounds latlngBounds;
private Button bNavigation;
private Polyline newPolyline;
private Marker smarker;
private Marker dmarker;
Geocoder geocoder;
private boolean isTraveling = false;
private int width, height;
private String sourcelat;
private String sourcelong;
private String destinationg;
private String destinationlat;
double slat;
double slong;
double dlat;
double dlong;
double d;
double tempDistance;
String distance;
String ts;
List<Address> addresses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_navigation);
Intent in = getIntent();
sourcelat = in.getStringExtra(TAG_SLAT);
destinationlat = in.getStringExtra(TAG_DLAT);
destinationg = in.getStringExtra(TAG_DLONG);
sourcelong = in.getStringExtra(TAG_SLONG);
slat=Double.parseDouble(sourcelat);
slong=Double.parseDouble(sourcelong);
dlat=Double.parseDouble(destinationlat);
dlong=Double.parseDouble(destinationg);
Source = new LatLng(slat,slong);
Destination = new LatLng(dlat,dlong);
getSreenDimanstions();
fragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
map = fragment.getMap();
map.setMyLocationEnabled(true);
ImageButton cureent_location = (ImageButton)findViewById(R.id.clocation);
cureent_location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LocationShow();
}
});
if (!isTraveling) {
isTraveling = true;
findDirections(Source.latitude, Source.longitude, Destination.latitude, Destination.longitude, GMapV2Direction.MODE_DRIVING);
} else {
isTraveling = false;
}
}
public double calculateDistance(double fromLatitude,double fromLongitude,double toLatitude,double toLongitude)
{
float results[] = new float[1];
try {
Location.distanceBetween(fromLatitude, fromLongitude, toLatitude, toLongitude, results);
} catch (Exception e) {
if (e != null)
e.printStackTrace();
}
if (Source.equals(Destination)){
distance="0";
}
else {
int dist = (int) results[0];
if (dist <= 0)
return 0D;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
results[0] /= 1000D;
distance = decimalFormat.format(results[0]);
double d = Double.parseDouble(distance);
double speed = 40;
double time = d / speed;
ts = manual(time);
Log.v("fdf", String.valueOf(ts));
}
return d;
}
private static String manual(double eta) {
int hour = (int) eta;
eta = (eta - hour) * 60;
int minutes = (int) eta;
eta = (eta - minutes) * 60;
int seconds = (int) eta;
eta = (eta - seconds) * 1000;
int ms = (int) eta;
//Log.d("ffgfh", String.valueOf(eta));
return String.format("%dHr %dMin ", hour, minutes);
}
#Override
protected void onResume() {
super.onResume();
latlngBounds = createLatLngBoundsObject(Source, Destination);
map.moveCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 150));
}
public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.RED);
MarkerOptions marker = new MarkerOptions().position(Source).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
MarkerOptions marker1 = new MarkerOptions().position(Destination).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
for(int i = 0 ; i < directionPoints.size() ; i++)
{
rectLine.add(directionPoints.get(i));
}
if (newPolyline != null)
{
newPolyline.remove();
}
newPolyline = map.addPolyline(rectLine);
//smarker = map.addMarker(marker);
dmarker = map.addMarker(marker1);
if (isTraveling) {
latlngBounds = createLatLngBoundsObject(Source, Destination);
map.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 150));
Dialog dialog_help = new Dialog(this);
dialog_help .requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog_help.setContentView(R.layout.title_multi_selectitems_dialog);
calculateDistance(slat, slong, dlat, dlong);
TextView dis = (TextView) dialog_help.findViewById(R.id.distance);
dis.setText("Distance " + distance + "Km ");
TextView tim = (TextView) dialog_help.findViewById(R.id.time);
tim.setText("Time " + ts);
dialog_help.setCancelable(true);
dialog_help.setTitle("Distance & Time" );
dialog_help.setCanceledOnTouchOutside(true);
dialog_help.show();
dialog_help.getWindow().setGravity(Gravity.CENTER);
dialog_help.getWindow().setBackgroundDrawable(new ColorDrawable(Color.LTGRAY));
dialog_help.getWindow().setLayout(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
}
else
{
map.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 150));
}
}
private void getSreenDimanstions()
{
Display display = getWindowManager().getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
}
private LatLngBounds createLatLngBoundsObject(LatLng firstLocation, LatLng secondLocation)
{
if (firstLocation != null && secondLocation != null)
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(firstLocation).include(secondLocation);
return builder.build();
}
return null;
}
public void findDirections(double fromPositionDoubleLat, double fromPositionDoubleLong, double toPositionDoubleLat, double toPositionDoubleLong, String mode)
{
Map<String, String> map = new HashMap<String, String>();
map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT, String.valueOf(fromPositionDoubleLat));
map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG, String.valueOf(fromPositionDoubleLong));
map.put(GetDirectionsAsyncTask.DESTINATION_LAT, String.valueOf(toPositionDoubleLat));
map.put(GetDirectionsAsyncTask.DESTINATION_LONG, String.valueOf(toPositionDoubleLong));
map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode);
GetDirectionsAsyncTask asyncTask = new GetDirectionsAsyncTask(this);
asyncTask.execute(map);
}
#Override
public void onLocationChanged(Location location) {
TextView cl = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(latLng));
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(5));
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0);
String prmises = addresses.get(0).getAddressLine(1);
String city = addresses.get(0).getAddressLine(2);
String country = addresses.get(0).getAddressLine(3);
cl.setText(address+" "+prmises+" "+city+" " +country);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
public void LocationShow() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}
Maybe you want create a Polyline with a Line with multiple points, which represents each position of the user:
provide a global variable:
PolylineOptions pathOptions;
#Override
public View onCreate(Bundle savedInstanceState) {
...
pathOptions = new PolylineOptions();
...
}
#Override
public void onLocationChanged(Location location) {
...
pathOptions.add(new LatLng(42.255, 10.142));
}
And after creating an Object of PolylineOptions and the Map call:
Polyline userPath = map.addPolyline(pathOptions);

how to draw Bitmaps with specific ArrayList of coordinates on google maps api 2 using asynctask?

The idea of the application is to get ArrayList<LatLng> from the database then draw these coordinates as markers using bitmaps on the map
I'm getting:
NullPointerException at android.graphics.Canvas.drawBitmap(Canvas.java:1195) in onPostExecute
There's two questions in here:
Is it normal to draw bitmaps in onPostExecute method..??
Why I get NullPointerException at android.graphics.Canvas.drawBitmap(Canvas.java:1195) in onPostExecute...??
Asynctask Class:
public class BitmapAsyncTask extends
AsyncTask<ArrayList<Obstacle>, Void, ArrayList<LatLng>> {
static Canvas canvas1;
static BitmapFactory.Options o;
private Bitmap bmp;
MarkerOptions balloonmarker;
private double latitude;
private double longitude;
GoogleMap gm;
LatLng ll;
LatLng latlong;
private int len;
private static int resID = 1;
static ArrayList<Obstacle> obs;
static ArrayList<LatLng> coordinates;
static ArrayList<LatLng> sendingCoord;
private static double mydirection = 45;
static Context context;
public BitmapAsyncTask(Context contextx) {
context = contextx;
}
#Override
protected ArrayList<LatLng> doInBackground(ArrayList<Obstacle>... params) {
int i;
ArrayList<Obstacle> obstacleArray = params[0];
coordinates = new ArrayList<LatLng>();
len = obstacleArray.size();
for (i = 0; i < len; i++) {
Obstacle obstacle = obstacleArray.get(i);
latitude = obstacle.getLatitude();
longitude = obstacle.getLongitude();
mydirection = obstacle.getDirection();
}
for (int x = 0; x < 1; x++) {
ll = new LatLng(latitude, longitude);
coordinates.add(ll);
}
}
return coordinates;
}
#Override
protected void onPostExecute(ArrayList<LatLng> result) {
int i;
int size = result.size();
bmp = BitmapFactory.decodeResource(context.getResources(),
R.drawable.map_pin, null);
bmp=Bitmap.createBitmap(50, 50, Config.ARGB_4444);
for (i = 0; i < size; i++) {
latlong = result.get(i);
canvas1=new Canvas();
//the exception happens here
canvas1.drawBitmap(bmp, null, null);
balloonmarker = new MarkerOptions().title("MyLocation")
.snippet("This Is Me").position(latlong).anchor(0, 1)
.icon(BitmapDescriptorFactory.fromBitmap(bmp));
gm.addMarker(balloonmarker);
}
if (bmp != null) {
bmp.recycle();
bmp = null;
System.gc();
}
}
Obstacle class:
public class Obstacle {
long id;
double longitude;
double latitude;
double direction;
public Obstacle(double longitude, double latitude, double direction) {
super();
this.longitude = longitude;
this.latitude = latitude;
this.direction = direction;
}
public Obstacle() {
// TODO Auto-generated constructor stub
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getDirection() {
return direction;
}
public void setDirection(double direction) {
this.direction = direction;
}
public Location getLocation() {
Location myLocation = new Location(MatabbatManager.PROVIDER_STRING);
myLocation.setLongitude(longitude);
myLocation.setLatitude(latitude);
return myLocation;
}
}
DataBase Class:
public class LocalCachedObstacles extends SQLiteOpenHelper {
static String DATABASE_NAME="localobstaclesdb";
private static final int DATABASE_VERSION = 1;
static String OBSTACLES_TABLE ="obstacles";
private static final String OBSTACLES_TABLE_CREATE ="" +
"CREATE Table " + OBSTACLES_TABLE +
"(" +
"long REAL," +
"lat REAL," +
"direction REAL, " +
"type REAL, " +
"address VARCHAR(500)," +
"time VARCHAR(100)," +
"submitterName VARCHAR(200) " +
")";
public ArrayList<Obstacle> getCachedObstacles() {
try {
SQLiteDatabase dblocs=this.getReadableDatabase();
Cursor cur=dblocs.rawQuery("SELECT * FROM "+OBSTACLES_TABLE,new String [] {});
ArrayList<Obstacle> obstacles = new ArrayList<Obstacle>();
while (cur.moveToNext()) {
Obstacle obstacle = new Obstacle
(cur.getDouble(0),
cur.getDouble(1),cur.getDouble(2),
cur.getDouble(3),cur.getString(4),
cur.getString(5),cur.getString(6));
obstacles.add(obstacle);
}
cur.close();
dblocs.close();
return obstacles;
}
catch (Exception locex){
Log.e(MatabbatManager.TAG," Get Local cache" + locex.getMessage());
return null;
}
}
Excecution class:
public class AnonymousUser extends FragmentActivity{
LocalCachedObstacles lo = new LocalCachedObstacles(
MyApplication.getAppContext());
ArrayList<Obstacle> localObstacles = lo.getCachedObstacles();
DrawTypes(localObstacles);
public void DrawTypes(ArrayList<Obstacle> obs) {
len = obs.size();
BitmapAsyncTask async = new BitmapAsyncTask(MyApplication.getAppContext());
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
async.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, obs);
}
}
You can not use Canvas as in your code , we can get canvas object by overriding onDraw method.
In my opinion you should use overlays to draw bitmaps on map.
I solved it finally after 2 weeks of trying everything related to threads threadpool,asynctaskloader.....
Solution:
Making aservice instead of AsyncTask because i need it to keep running in the background.

Google Maps Android V2 and Direction API

I'm developing an app where i need to know the path between the current user posistion and a point of interest.
I'm using android 2.3.3, google maps android v2 and direction api.
My problem is that all the code i have found is for the old version of the maps, and I also tried to adapt the code but i failed. I try to change GeoPoint (not supported in this new versione) in LatLng.
the problem is that i can't display the path, to do it i create a new polyline and i add it to the map.
i post my code:
Parser:
public interface Parser {
public Route parse();
}
XMLParser
public class XMLParser {
// names of the XML tags
protected static final String MARKERS = "markers";
protected static final String MARKER = "marker";
protected URL feedUrl;
protected XMLParser(final String feedUrl) {
try {
this.feedUrl = new URL(feedUrl);
} catch (MalformedURLException e) {
Log.e(e.getMessage(), "XML parser - " + feedUrl);
}
}
protected InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
Log.e(e.getMessage(), "XML parser - " + feedUrl);
return null;
}
}
}
JsonParser (parse the google direction json)
public class JsonParser extends XMLParser implements Parser {
/** Distance covered. **/
private int distance;
public JsonParser(String feedUrl) {
super(feedUrl);
}
/**
* Parses a url pointing to a Google JSON object to a Route object.
* #return a Route object based on the JSON object.
*/
public Route parse() {
// turn the stream into a string
final String result = convertStreamToString(this.getInputStream());
//Create an empty route
final Route route = new Route();
//Create an empty segment
final Segment segment = new Segment();
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
//Get the route object
final JSONObject jsonRoute = json.getJSONArray("routes").getJSONObject(0);
//Get the leg, only one leg as we don't support waypoints
final JSONObject leg = jsonRoute.getJSONArray("legs").getJSONObject(0);
//Get the steps for this leg
final JSONArray steps = leg.getJSONArray("steps");
//Number of steps for use in for loop
final int numSteps = steps.length();
//Set the name of this route using the start & end addresses
route.setName(leg.getString("start_address") + " to " + leg.getString("end_address"));
//Get google's copyright notice (tos requirement)
route.setCopyright(jsonRoute.getString("copyrights"));
//Get the total length of the route.
route.setLength(leg.getJSONObject("distance").getInt("value"));
//Get any warnings provided (tos requirement)
if (!jsonRoute.getJSONArray("warnings").isNull(0)) {
route.setWarning(jsonRoute.getJSONArray("warnings").getString(0));
}
/* Loop through the steps, creating a segment for each one and
* decoding any polylines found as we go to add to the route object's
* map array. Using an explicit for loop because it is faster!
*/
for (int i = 0; i < numSteps; i++) {
//Get the individual step
final JSONObject step = steps.getJSONObject(i);
//Get the start position for this step and set it on the segment
final JSONObject start = step.getJSONObject("start_location");
final LatLng position = new LatLng(start.getDouble("lat"), start.getDouble("lng"));
segment.setPoint(position);
//Set the length of this segment in metres
final int length = step.getJSONObject("distance").getInt("value");
distance += length;
segment.setLength(length);
segment.setDistance(distance/1000);
//Strip html from google directions and set as turn instruction
segment.setInstruction(step.getString("html_instructions").replaceAll("<(.*?)*>", ""));
//Retrieve & decode this segment's polyline and add it to the route.
route.addPoints(decodePolyLine(step.getJSONObject("polyline").getString("points")));
//Push a copy of the segment to the route
route.addSegment(segment.copy());
}
} catch (JSONException e) {
Log.e(e.getMessage(), "Google JSON Parser - " + feedUrl);
}
return route;
}
/**
* Convert an inputstream to a string.
* #param input inputstream to convert.
* #return a String of the inputstream.
*/
private static String convertStreamToString(final InputStream input) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
final StringBuilder sBuf = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sBuf.append(line);
}
} catch (IOException e) {
Log.e(e.getMessage(), "Google parser, stream2string");
} finally {
try {
input.close();
} catch (IOException e) {
Log.e(e.getMessage(), "Google parser, stream2string");
}
}
return sBuf.toString();
}
/**
* Decode a polyline string into a list of LatLng.
* #param poly polyline encoded string to decode.
* #return the list of GeoPoints represented by this polystring.
*/
private List<LatLng> decodePolyLine(final String poly) {
int len = poly.length();
int index = 0;
List<LatLng> decoded = new LinkedList<LatLng>();
int lat = 0;
int lng = 0;
while (index < len) {
int b;
int shift = 0;
int result = 0;
do {
b = poly.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 = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
decoded.add(new LatLng((lat / 1E5),(lng / 1E5)));
}
return decoded;
}
}
Route (to save json info)
public class Route {
private String name;
private final List<LatLng> points;
private List<Segment> segments;
private String copyright;
private String warning;
private String country;
private int length;
private String polyline;
public Route() {
points = new LinkedList<LatLng>();
segments = new LinkedList<Segment>();
}
public void addPoint(final LatLng p) {
points.add(p);
}
public void addPoints(final List<LatLng> points) {
this.points.addAll(points);
}
public List<LatLng> getPoints() {
return points;
}
public void addSegment(final Segment s) {
segments.add(s);
}
public List<Segment> getSegments() {
return segments;
}
/**
* #param name the name to set
*/
public void setName(final String name) {
this.name = name;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param copyright the copyright to set
*/
public void setCopyright(String copyright) {
this.copyright = copyright;
}
/**
* #return the copyright
*/
public String getCopyright() {
return copyright;
}
/**
* #param warning the warning to set
*/
public void setWarning(String warning) {
this.warning = warning;
}
/**
* #return the warning
*/
public String getWarning() {
return warning;
}
/**
* #param country the country to set
*/
public void setCountry(String country) {
this.country = country;
}
/**
* #return the country
*/
public String getCountry() {
return country;
}
/**
* #param length the length to set
*/
public void setLength(int length) {
this.length = length;
}
/**
* #return the length
*/
public int getLength() {
return length;
}
/**
* #param polyline the polyline to set
*/
public void setPolyline(String polyline) {
this.polyline = polyline;
}
/**
* #return the polyline
*/
public String getPolyline() {
return polyline;
}
}
Segment:
public class Segment {
/** Points in this segment. **/
private LatLng start;
/** Turn instruction to reach next segment. **/
private String instruction;
/** Length of segment. **/
private int length;
/** Distance covered. **/
private double distance;
/**
* Create an empty segment.
*/
public Segment() {
}
/**
* Set the turn instruction.
* #param turn Turn instruction string.
*/
public void setInstruction(final String turn) {
this.instruction = turn;
}
/**
* Get the turn instruction to reach next segment.
* #return a String of the turn instruction.
*/
public String getInstruction() {
return instruction;
}
/**
* Add a point to this segment.
* #param point LatLng to add.
*/
public void setPoint(LatLng point) {
start = point;
}
/** Get the starting point of this
* segment.
* #return a LatLng
*/
public LatLng startPoint() {
return start;
}
/** Creates a segment which is a copy of this one.
* #return a Segment that is a copy of this one.
*/
public Segment copy() {
final Segment copy = new Segment();
copy.start = start;
copy.instruction = instruction;
copy.length = length;
copy.distance = distance;
return copy;
}
/**
* #param length the length to set
*/
public void setLength(final int length) {
this.length = length;
}
/**
* #return the length
*/
public int getLength() {
return length;
}
/**
* #param distance the distance to set
*/
public void setDistance(double distance) {
this.distance = distance;
}
/**
* #return the distance
*/
public double getDistance() {
return distance;
}
}
My MainActivity (there are 326 code line because of user localization, you can find it on google developer site, so we can just suppose to have two static point A and B and I want to go from A to B):
public class MainActivity extends FragmentActivity{
private GoogleMap map;
private Marker currentLocation;
private PolylineOptions pathLine;
private LatLng imhere = new LatLng(41.8549038,12.4618208);
private LatLng poi = new LatLng(41.89000,12.49324);
private LocationManager mLocationManager;
private Handler mHandler;
private boolean mUseBoth;
private Context context;
// Keys for maintaining UI states after rotation.
private static final String KEY_BOTH = "use_both";
// UI handler codes.
private static final int UPDATE_LATLNG = 2;
private static final int FIVE_SECONDS = 5000;
private static final int THREE_METERS = 3;
private static final int TWO_MINUTES = 1000 * 60 * 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
Marker colosseoMarker = map.addMarker(new MarkerOptions()
.position(colosseo)
.title("Start")
.snippet("poi")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
Marker current pos = map.addMarker(new MarkerOptions()
.position(imhere)
.title("i'm here")
.snippet("here!")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
context =this ;
map.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
final String[] options = {"Calcola il Percorso"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Ottieni Informazioni aggiuntive");
builder.setPositiveButton("Calcola Percorso",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
LatLng start = new LatLng(imhere.latitude,imhere.longitude);
LatLng dest = new LatLng(poi.latitude, poi.longitude);
Route route = drawPath(start, dest);
List<LatLng> list= route.getPoints();
if(pathLine!= null) pathline =null;
pathLine = new PolylineOptions();
pathLine.addAll(list);
pathLine.color(Color.rgb(0,191,255));
map.addPolyline(pathLine);
}
});
AlertDialog alert = builder.create();
alert.show();
Toast.makeText(MainActivity.this, marker.getSnippet(),Toast.LENGTH_SHORT).show();
return true;
}
});
map.animateCamera(CameraUpdateFactory.newLatLngZoom(imhere, 12));
}
}
};
// Get a reference to the LocationManager object.
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
private Route drawPath(LatLng start, LatLng dest) {
Parser parser;
String jsonURL = "http://maps.google.com/maps/api/directions/json?";
final StringBuffer sBuf = new StringBuffer(jsonURL);
sBuf.append("origin=");
sBuf.append(start.latitude);
sBuf.append(',');
sBuf.append(start.longitude);
sBuf.append("&destination=");
sBuf.append(dest.latitude);
sBuf.append(',');
sBuf.append(dest.longitude);
sBuf.append("&sensor=true&mode=walking");
parser = new JsonParser(sBuf.toString());
Route r = parser.parse();
return r;
}
}
every suggestion is well accepted
If you don't need custom code try this lib https://github.com/jd-alexander/Google-Directions-Android only a few lines of code to do what you need.
I am doing like the following. I think this will help you.
Marker interestedMarker;
private void plot_direction(){
if (currentSelectedPin !=null) {
LatLng origin = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
new GoogleMapDirection(getActivity(), origin, interestedMarker.getPosition(), new DirectionListener() {
#Override
public void onDirectionPointsReceived(ArrayList<RouteModel> routeList, String distance, String duration) {
PolylineOptions lineOptions = null;
for (RouteModel route : routeList) {
lineOptions = new PolylineOptions();
lineOptions.addAll(route.getSteps());
lineOptions.width(20);
lineOptions.color(ContextCompat.getColor(getContext(), R.color.map_route));
}
//For removing existing line
if (routeMap!=null){
routeMap.remove();
}
if(lineOptions != null) {
routeMap = mMap.addPolyline(lineOptions);
}
}
});
}
}
GoogleMapDirection class is as follows
public class GoogleMapDirection {
private DirectionListener listener;
public GoogleMapDirection(final Activity activity, LatLng source, LatLng destination, DirectionListener listener){
this.listener=listener;
String url = null;
try {
url = "https://maps.googleapis.com/maps/api/directions/json?origin="+ URLEncoder.encode(Double.toString(source.latitude) + "," + Double.toString(source.longitude), "UTF-8") + "&destination=" + URLEncoder.encode(Double.toString(destination.latitude) + "," + Double.toString(destination.longitude), "UTF-8") + "&mode=driving&sensor=false&key=" + Config.GOOGLE_API_BROWSER_KEY;
Print.d(url);
} catch (UnsupportedEncodingException e) {
Print.exception(e);
}
JSONObject parameters = new JSONObject();
VolleyJsonBodyRequest.execute(activity, url, parameters, new VolleyResponseListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("OK")) {
String distance = "NA";
String duration = "NA";
if (response.has("routes")){
JSONArray routesJArray = response.getJSONArray("routes");
if (routesJArray.length()>0){
if (routesJArray.getJSONObject(0).has("legs")){
JSONArray legsJArray = routesJArray.getJSONObject(0).getJSONArray("legs");
if (legsJArray.length()>0){
JSONObject firstLegsJObj = legsJArray.getJSONObject(0);
if (firstLegsJObj.has("distance")){
distance = firstLegsJObj.getJSONObject("distance").getString("text");
}
if (firstLegsJObj.has("duration")){
duration = firstLegsJObj.getJSONObject("duration").getString("text");
}
}
}
}
}
GoogleResponseParserTask task = new GoogleResponseParserTask(distance,duration);
task.execute(response);
}
} catch (JSONException e) {
Print.exception(e);
DialogWindow.showOK(activity, Config.MESSAGE_INVALID_RESPONSE_FORMAT, new DialogListenerOK() {
#Override
public void onOK() {
}
});
}
}
#Override
public void onErrorResponse(VolleyResponseError error) {
Print.e(error.getDetails());
DialogWindow.showOK(activity, error.getMessage(), new DialogListenerOK() {
#Override
public void onOK() {
}
});
}
});
}
/**
* A class to parse the Google Places in JSON format
*/
private class GoogleResponseParserTask extends AsyncTask<JSONObject, Integer, ArrayList<RouteModel>> {
String distance;
String duration;
private GoogleResponseParserTask(String distance, String duration){
this.distance=distance;
this.duration=duration;
}
#Override
protected ArrayList<RouteModel> doInBackground(JSONObject... jsonResponse) {
ArrayList<RouteModel> routes = null;
try {
routes = parse(jsonResponse[0]);
} catch (Exception e) {
Print.exception(e);
}
return routes;
}
#Override
protected void onPostExecute(ArrayList<RouteModel> result) {
listener.onDirectionPointsReceived(result,distance,duration);
}
}
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public ArrayList<RouteModel> parse(JSONObject jObject){
ArrayList<RouteModel> routeList = new ArrayList<>() ;
JSONArray jRoutes;
JSONArray jLegs;
JSONArray jSteps;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
ArrayList<LatLng> pointList = new ArrayList<>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ((JSONObject)jLegs.get(j)).getJSONArray("steps");
JSONObject jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
JSONObject jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
String distance = jDistance.getString("text");
String duration = jDuration.getString("text");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
ArrayList<LatLng> stepList = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<stepList.size();l++){
LatLng point = new LatLng((stepList.get(l)).latitude, (stepList.get(l)).longitude);
pointList.add(point);
}
}
RouteModel routeModel = new RouteModel();
routeModel.setSteps(pointList);
routeModel.setDistance(distance);
routeModel.setDuration(duration);
routeList.add(routeModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routeList;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private ArrayList<LatLng> decodePoly(String encoded) {
ArrayList<LatLng> poly = new ArrayList<>();
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;
}

Categories

Resources