2015-02-02 2 views
0

Google지도에서 대체 경로를 여러 개 표시하고 싶습니다. 내 코드에서는 내 위치를 소스로, 정적 인 위치를 대상으로 설정했습니다. 나는 this을 사용하여 단일 경로를 성공적으로 그렸습니다.안드로이드를 사용하여 Google지도에서 대체 경로를 표시하려면 어떻게해야합니까?

아무도 말해 줄 수 있습니까? 동일한 목적지에 대한 대체 경로를 표시하려면 어떻게해야합니까?

감사합니다.

답변

0

Google Directions API에는 경로를 그리는 데 4 가지 매개 변수가 있습니다. https://developers.google.com/maps/documentation/directions/#TravelModes

driving, walking, bicycling, transit

그래서 당신은이 매개 변수를 사용하고 다른 경로를 얻기 위해 시도 할 수 있습니다. 서로 가깝게 서로 같은 위치간에 서로 같을 수 있습니다 (예 : walkingbicycling). 그러나 이것을 처리하고 중복 된 부분을 그릴 수는 없습니다.

또한지도상의 2 개 지점 (아마도 직선 일 수도 있음) 사이에서 경로를 그리는 메커니즘 하나를 만들려고 할 수 있습니다. 그러나 당신이 뭔가 복잡한 것을 원한다면, 이것을 스스로 만드는 것은 정말로 어려울 것입니다.

0

난 당신이

LatLng origin = sourcePosition; 
    LatLng dest = destPosition; 

    DownloadTask1 downloadTask = new DownloadTask1(); 
    String url = downloadTask.getDirectionsUrl1(origin, dest);     
    downloadTask.execute(url); 

DownloadTask1 클래스

private class DownloadTask1 extends AsyncTask<String, Void, String> { 

     // Downloading data in non-ui thread 
     @Override 
     protected String doInBackground(String... url) { 

      // For storing data from web service 
      String data = ""; 

      try { 
       // Fetching the data from web service 
       data = downloadUrl(url[0]); 
      } catch (Exception e) { 
       Log.d("Background Task", e.toString()); 
      } 
      return data; 
     } 

     // Executes in UI thread, after the execution of 
     // doInBackground() 
     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 

      ParserTask1 parserTask = new ParserTask1(); 

      // Invokes the thread for parsing the JSON data 
      parserTask.execute(result); 
     } 


     private String getDirectionsUrl1(LatLng origin, LatLng dest) { 

      // Origin of route 
      String str_origin = "origin=" + origin.latitude + "," + origin.longitude; 

      // Destination of route 
      String str_dest = "destination=" + dest.latitude + "," + dest.longitude; 

      // Sensor enabled 
      String sensor = "sensor=false&alternatives=true&units=metric&mode=driving"; 
      //&alternatives=true&units=metric&mode=driving 
      // Building the parameters to the web service 
      String parameters = str_origin + "&" + str_dest + "&" + sensor; 

      // Output format 
      String output = "json"; 

      // Building the url to the web service 
      String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters; 

      return url; 
     } 
    } 

downloadUrl() 메소드

private String downloadUrl(String strUrl) throws IOException { 
     String data = ""; 
     InputStream iStream = null; 
     HttpURLConnection urlConnection = null; 
     try{ 
      URL url = new URL(strUrl); 

      // Creating an http connection to communicate with url 
      urlConnection = (HttpURLConnection) url.openConnection(); 

      // Connecting to url 
      urlConnection.connect(); 

      // Reading data from url 
      iStream = urlConnection.getInputStream(); 

      BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); 

      StringBuffer sb = new StringBuffer(); 

      String line = ""; 
      while((line = br.readLine()) != null){ 
       sb.append(line); 
      } 

      data = sb.toString(); 

      br.close(); 

     }catch(Exception e){ 
      e.printStackTrace(); 
      //Log.d("Exception while downloading url", e.toString()); 
     }finally{ 
      iStream.close(); 
      urlConnection.disconnect(); 
     } 
     return data; 
    } 

ParserTask1 클래스

private class ParserTask1 extends AsyncTask<String, Integer, List<List<List<HashMap<String, String>>>>> { 

     // Parsing the data in non-ui thread 
     @Override 
     protected List<List<List<HashMap<String, String>>>> doInBackground(String... jsonData) { 

      JSONObject jObject; 
      List<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<List<HashMap<String, String>>>> result) { 
      ArrayList<LatLng> points = null; 
      PolylineOptions lineOptions = new PolylineOptions(); 

      PolylineOptions lineOptions1 = null; 
      MarkerOptions markerOptions = new MarkerOptions(); 
      String distance = ""; 
      String duration = ""; 

      Integer size1 = 0; 
      Integer size2 = 0; 
      Integer size3 = 0; 
//   Log.d(SHETTY, "onPostExecute: result set "+result.size()); 


      List<LatLng> aline1 = new ArrayList<LatLng>(); 
      List<LatLng> aline2 = new ArrayList<LatLng>(); 
      List<LatLng> aline3 = new ArrayList<LatLng>(); 


      if (result != null) { 
       int i = 0; 
       Log.d(SHETTY, "onPostExecute: result size " + result.size()); 

       while (i < result.size()) { 

        // for(int i=0;i<result.size();i++){ 
        //result.size() 
        //int g= i-1; 
        points = new ArrayList<LatLng>(); 
        // lineOptions = new PolylineOptions(); 
        // if(i==1){ 

        // }else{ 
        List<List<HashMap<String, String>>> path1 = result.get(i); 

        for (int s = 0; s < path1.size(); s++) { 
         Log.d("pathsize1", path1.size() + ""); 

         // Fetching i-th route 
         List<HashMap<String, String>> path = path1.get(s); 
         Log.d("pathsize", path.size() + ""); 
         // Fetching all the points in i-th route 

         for (int j = 0; j < path.size(); j++) { 
          lineOptions1 = new PolylineOptions(); 
          HashMap<String, String> point = path.get(j); 
          // points = new ArrayList<LatLng>(); 
          //     if(j==0){ // Get distance from the list 
          //      distance = (String)point.get("distance"); 
          //      continue; 
          //     }else if(j==1){ // Get duration from the list 
          //      duration = (String)point.get("duration"); 
          //      continue; 
          //     } 
          double lat = Double.parseDouble(point.get("lat")); 
          double lng = Double.parseDouble(point.get("lng")); 
          LatLng position = new LatLng(lat, lng); 
          // Log.d("latlng", position.toString()); 
          points.add(position); 


         } 
         //    lineOptions.addAll(points); 
         //    lineOptions.width(5); 
         //    lineOptions.color(Color.BLUE); 
         //    map.addPolyline(lineOptions); 

        } 
        // } 
        if (i == 0) { 


//      line1.addAll(points); 
//      mMap.addPolyline(line1); 

         size1 = points.size(); 

         aline1.addAll(points); 
        } else if (i == 1) { 


//      line2.addAll(points); 
//      mMap.addPolyline(line2); 

         aline2.addAll(points); 
         size2 = points.size(); 
        } else if (i == 2) { 


//      line3.addAll(points); 
//      mMap.addPolyline(line3); 

         aline3.addAll(points); 
         size3 = points.size(); 
        } 
        // Adding all the points in the route to LineOptions 
        i++; 


       } 
       // Drawing polyline in the Google Map for the i-th route 
       // map.addPolyline(lineOptions); 
      } 

      if (size3 != 0) 
      { 

       if ((size1 > size2 && size1 > size3)) { 
        if (size2 > size3) { 
         PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 
         PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 
         PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue)); 

         line1.addAll(aline1); 
         line2.addAll(aline2); 
         line3.addAll(aline3); 

         mMap.addPolyline(line1); 
         mMap.addPolyline(line2); 
         mMap.addPolyline(line3); 


         Log.d(SHETTY, "onPostExecute: 3110 "); 
        } else { 

         PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 
         PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue)); 
         PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 

         line1.addAll(aline1); 
         line2.addAll(aline2); 
         line3.addAll(aline3); 

         mMap.addPolyline(line1); 
         mMap.addPolyline(line3); 

         mMap.addPolyline(line2); 


         Log.d(SHETTY, "onPostExecute: 3127 "); 
        } 
       } else if ((size2 > size1 && size2 > size3)) { 
        if (size1 > size3) { 
         PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 
         PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 
         PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue)); 

         line1.addAll(aline1); 
         line2.addAll(aline2); 
         line3.addAll(aline3); 

         mMap.addPolyline(line1); 
         mMap.addPolyline(line2); 

         mMap.addPolyline(line3); 


         Log.d(SHETTY, "onPostExecute: 3147 "); 
        } else { 

         PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue)); 
         PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 
         PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 

         line1.addAll(aline1); 
         line2.addAll(aline2); 
         line3.addAll(aline3); 


         mMap.addPolyline(line2); 
         mMap.addPolyline(line3); 

         mMap.addPolyline(line1); 

         Log.d(SHETTY, "onPostExecute: 3164 "); 
        } 
       } else if ((size3 > size1 && size3 > size2)) { 
        if (size1 > size2) { 
         PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 
         PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue)); 
         PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 

         line1.addAll(aline1); 
         line2.addAll(aline2); 
         line3.addAll(aline3); 


         mMap.addPolyline(line3); 
         mMap.addPolyline(line1); 
         mMap.addPolyline(line2); 

         Log.d(SHETTY, "onPostExecute: 3182 "); 
        } else { 
         PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue)); 
         PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 
         PolylineOptions line3 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 

         line1.addAll(aline1); 
         line2.addAll(aline2); 
         line3.addAll(aline3); 

         mMap.addPolyline(line3); 
         mMap.addPolyline(line2); 

         mMap.addPolyline(line1); 

         Log.d(SHETTY, "onPostExecute: 3196 "); 
        } 
       } else { 
        System.out.println("ERROR!"); 
       } 

     }else if(size2!=0) 
      { 
       if(size1>size2){ 

        PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 
        PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue)); 


        line1.addAll(aline1); 
        line2.addAll(aline2); 

        mMap.addPolyline(line1); 
        mMap.addPolyline(line2); 

       }else 
       { 
        PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue)); 
        PolylineOptions line2 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.grey)); 

        line1.addAll(aline1); 
        line2.addAll(aline2); 

        mMap.addPolyline(line2); 
        mMap.addPolyline(line1); 
       } 



      } 
      else if(size1!=0){ 
       PolylineOptions line1 = new PolylineOptions().width(8).color(getActivity().getResources().getColor(R.color.lightblue)); 
       line1.addAll(aline1); 
       mMap.addPolyline(line1); 
      } 

     } 




     } 
같은 것을 할 수 있다고 생각 17,451,515,

지금 구문 분석 말 DirectionsJSONParser 클래스

public class DirectionsJSONParser { 

    /** 
    * Receives a JSONObject and returns a list of lists containing latitude and 
    * longitude 
    */ 
    public List<List<List<HashMap<String,String>>>> parse(JSONObject jObject){ 

     List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ; 
     List<List<List<HashMap<String,String>>>> routes1 = new ArrayList<List<List<HashMap<String,String>>>>() ; 
     JSONArray jRoutes = null; 
     JSONArray jLegs = null; 
     JSONArray jSteps = null; 

     try { 

      jRoutes = jObject.getJSONArray("routes"); 

      /** Traversing all routes */ 
      for(int i=0;i<jRoutes.length();i++){ 
       jLegs = ((JSONObject)jRoutes.get(i)).getJSONArray("legs"); 
       List path = new ArrayList<HashMap<String, String>>(); 
       List path1 = new ArrayList<ArrayList<HashMap<String,String>>>(); 

       // Log.d("legs",jLegs.toString()); 
       /** Traversing all legs */ 
       for(int j=0;j<jLegs.length();j++){ 
        HashMap<String, String> hm1 = new HashMap<String, String>(); 
        jSteps = ((JSONObject)jLegs.get(j)).getJSONArray("steps"); 
        // Log.d("steps",jSteps.toString()); 
        /** Traversing all steps */ 
        for(int k=0;k<jSteps.length();k++){ 

         String polyline = ""; 
         polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points"); 
         List<LatLng> list = decodePoly(polyline); 
         // Log.d("polyline",polyline.toString()); 
         /** Traversing all points */ 

         for(int l=0;l<list.size();l++){ 
          HashMap<String, String> hm = new HashMap<String, String>(); 
          hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude)); 
          hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude)); 

          path.add(hm); 
          // Log.d("lat", Double.toString(((LatLng)list.get(l)).latitude)); 
          // Log.d("lng", Double.toString(((LatLng)list.get(l)).longitude)); 
         } 

        } 

        path1.add(path); 

       } 
       routes1.add(path1); 
      } 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     }catch (Exception e){ 
     } 

     return routes1; 
    } 
    /** 
    * Method to decode polyline points 
    * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java 
    * */ 
    private List<LatLng> decodePoly(String encoded) { 

     List<LatLng> poly = new ArrayList<LatLng>(); 
     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; 
    } 

} 

를 생성하는 jobject 당신은 파란색과 회색 대안의 주요 경로를해야합니다. 도움이 되길 바랍니다.

관련 문제