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. M
Solution 1:
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.
Solution 2:
I am doing like the following. I think this will help you.
Marker interestedMarker;
privatevoidplot_direction(){
if (currentSelectedPin !=null) {
LatLng origin = newLatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
newGoogleMapDirection(getActivity(), origin, interestedMarker.getPosition(), newDirectionListener() {
@OverridepublicvoidonDirectionPointsReceived(ArrayList<RouteModel> routeList, String distance, String duration) {
PolylineOptions lineOptions = null;
for (RouteModel route : routeList) {
lineOptions = newPolylineOptions();
lineOptions.addAll(route.getSteps());
lineOptions.width(20);
lineOptions.color(ContextCompat.getColor(getContext(), R.color.map_route));
}
//For removing existing lineif (routeMap!=null){
routeMap.remove();
}
if(lineOptions != null) {
routeMap = mMap.addPolyline(lineOptions);
}
}
});
}
}
GoogleMapDirection class is as follows
publicclassGoogleMapDirection {
private DirectionListener listener;
publicGoogleMapDirection(final Activity activity, LatLng source, LatLng destination, DirectionListener listener){
this.listener=listener;
Stringurl=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);
}
JSONObjectparameters=newJSONObject();
VolleyJsonBodyRequest.execute(activity, url, parameters, newVolleyResponseListener() {
@OverridepublicvoidonResponse(JSONObject response) {
try {
if (response.getString("status").equals("OK")) {
Stringdistance="NA";
Stringduration="NA";
if (response.has("routes")){
JSONArrayroutesJArray= response.getJSONArray("routes");
if (routesJArray.length()>0){
if (routesJArray.getJSONObject(0).has("legs")){
JSONArraylegsJArray= routesJArray.getJSONObject(0).getJSONArray("legs");
if (legsJArray.length()>0){
JSONObjectfirstLegsJObj= legsJArray.getJSONObject(0);
if (firstLegsJObj.has("distance")){
distance = firstLegsJObj.getJSONObject("distance").getString("text");
}
if (firstLegsJObj.has("duration")){
duration = firstLegsJObj.getJSONObject("duration").getString("text");
}
}
}
}
}
GoogleResponseParserTasktask=newGoogleResponseParserTask(distance,duration);
task.execute(response);
}
} catch (JSONException e) {
Print.exception(e);
DialogWindow.showOK(activity, Config.MESSAGE_INVALID_RESPONSE_FORMAT, newDialogListenerOK() {
@OverridepublicvoidonOK() {
}
});
}
}
@OverridepublicvoidonErrorResponse(VolleyResponseError error) {
Print.e(error.getDetails());
DialogWindow.showOK(activity, error.getMessage(), newDialogListenerOK() {
@OverridepublicvoidonOK() {
}
});
}
});
}
/**
* A class to parse the Google Places in JSON format
*/privateclassGoogleResponseParserTaskextendsAsyncTask<JSONObject, Integer, ArrayList<RouteModel>> {
String distance;
String duration;
privateGoogleResponseParserTask(String distance, String duration){
this.distance=distance;
this.duration=duration;
}
@Overrideprotected ArrayList<RouteModel> doInBackground(JSONObject... jsonResponse) {
ArrayList<RouteModel> routes = null;
try {
routes = parse(jsonResponse[0]);
} catch (Exception e) {
Print.exception(e);
}
return routes;
}
@OverrideprotectedvoidonPostExecute(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 = newArrayList<>() ;
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 = newArrayList<>();
/** Traversing all legs */for(int j=0;j<jLegs.length();j++){
jSteps = ((JSONObject)jLegs.get(j)).getJSONArray("steps");
JSONObjectjDistance= ((JSONObject) jLegs.get(j)).getJSONObject("distance");
JSONObjectjDuration= ((JSONObject) jLegs.get(j)).getJSONObject("duration");
Stringdistance= jDistance.getString("text");
Stringduration= jDuration.getString("text");
/** Traversing all steps */for(int k=0;k<jSteps.length();k++){
Stringpolyline= (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++){
LatLngpoint=newLatLng((stepList.get(l)).latitude, (stepList.get(l)).longitude);
pointList.add(point);
}
}
RouteModelrouteModel=newRouteModel();
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 = newArrayList<>();
intindex=0, len = encoded.length();
intlat=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);
intdlat= ((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);
intdlng= ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLngp=newLatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
Post a Comment for "Google Maps Android V2 And Direction Api"