publicclassDirectionJSONParser{publicstaticfinalStringROUTES="routes";publicstaticfinalStringLEGS="legs";publicstaticfinalStringSTEPS="steps";publicstaticfinalStringPOLYLINE="polyline";publicstaticfinalStringPOINTS="points";/** * Receives a JSONObject and returns a list of lists containing latitude and longitude * @param jObject JSONObject * @return List of routes */publicList<List<HashMap<String,String>>>parse(JSONObjectjObject){List<List<HashMap<String,String>>>routes=newArrayList<>();JSONArrayjRoutes=null;JSONArrayjLegs=null;JSONArrayjSteps=null;try{jRoutes=jObject.getJSONArray(ROUTES);intjRoutesLength=jRoutes.length();// Traversing all routesfor(inti=0;i<jRoutesLength;i++){jLegs=((JSONObject)jRoutes.get(i)).getJSONArray(LEGS);Listpath=newArrayList<HashMap<String,String>>();intjLegsLength=jLegs.length();// Traversing all legsfor(intj=0;j<jLegsLength;j++){jSteps=((JSONObject)jLegs.get(j)).getJSONArray(STEPS);intjStepsLength=jSteps.length();// Traversing all stepsfor(intk=0;k<jStepsLength;k++){Stringpolyline="";polyline=(String)((JSONObject)((JSONObject)jSteps.get(k)).get(POLYLINE)).get(POINTS);List<LatLng>list=decodePoly(polyline);for(intl=0;l<list.size();l++){HashMap<String,String>hm=newHashMap<>();hm.put("lat",Double.toString((list.get(l)).latitude));hm.put("lng",Double.toString((list.get(l)).longitude));path.add(hm);}}}routes.add(path);}}catch(JSONExceptionex){ex.printStackTrace();}returnroutes;}/** * Method to decode polyline points * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java * */privateList<LatLng>decodePoly(Stringencoded){List<LatLng>poly=newArrayList<>();intindex=0,len=encoded.length();intlat=0,lng=0;while(index<len){intb,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);}returnpoly;}}
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.