2013-07-22 6 views
0

Привет, я впервые использую карту в android после изменения в google Map API.Google Google Map routing

Сейчас хочет сделать маршрут на карте между двумя адресами endered мной для API v2. Я не знаю, как это сделать. Я много пробовал для этого. Пожалуйста, помогите мне. Благодарю.

Мой код является:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(R.layout.start_trip_view); 
    try { 
     ArrayList<String> location = new ArrayList<String>(); 
     Intent ii = getIntent(); 

     location2 = (ii.getStringExtra("place")); 
     String location3 = (ii.getStringExtra("start")); 
     gps = new GPSTracker(getApplicationContext()); 
     latitude = gps.getLatitude(); 
     longitude = gps.getLongitude(); 
     Balvinder = new LatLng(latitude, longitude); 
     markerPoints = new ArrayList<LatLng>(); 

     map = ((MapFragment) getFragmentManager() 
       .findFragmentById(R.id.map)).getMap(); 
     map.setMyLocationEnabled(true); 

     // 

     if (location == null || location.equals("")) { 
      Toast.makeText(getBaseContext(), "No Place is entered", 
        Toast.LENGTH_SHORT).show(); 
      return; 
     } 

     String url = "https://maps.googleapis.com/maps/api/geocode/json?"; 
     // for(int i=0; i<location.size();i++) 
     // { 
     try { 
      // encoding special characters like space in the user input 
      // place 

      location2 = URLEncoder.encode(location2, "utf-8"); 
//    location3 = URLEncoder.encode(location3, "utf-8"); 
      String saddress = "address=" + location2; 
      // String Dsaddress = "address=" + location3; 

      String sensor = "sensor=false"; 

      // url , from where the geocoding data is fetched 

      url = url + saddress + "&" + sensor; 

      DownloadTask downloadTask = new DownloadTask(); 

      // Start downloading the geocoding places 
      downloadTask.execute(url); 
      } 


private String downloadUrl(String... strUrl) throws IOException { 
    String data = ""; 
    InputStream iStream = null; 
    HttpURLConnection urlConnection = null; 
    try { 
     for(int i=0;i<strUrl.length;i++) 
     { 
     URL url = new URL(strUrl[i]); 


     // 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) { 
     Log.d("Exception while downloading url", e.toString()); 
    } finally { 
     iStream.close(); 
     urlConnection.disconnect(); 
    } 

    return data; 

} 

// Fetches data from url passed 
private class DownloadTask extends AsyncTask<String, Integer, String> { 

    String data = null; 

    // Invoked by execute() method of this object 
    @Override 
    protected String doInBackground(String... url) { 
     try { 
      for(int i=0;i<url.length;i++) 
      { 
      data = downloadUrl(url[i]); 
     } 
     } catch (Exception e) { 
      Log.d("Background Task", e.toString()); 
     } 
     return data; 
    } 

    // Executed after the complete execution of doInBackground() method 
    @Override 
    protected void onPostExecute(String result) { 

     // Instantiating ParserTask which parses the json data from 
     // Geocoding webservice 
     // in a non-ui thread 



     ParserTask parserTask = new ParserTask(); 
     parserTask.execute(result); 
     } 
     System.out.println("Result"+result); 

    } 

} 

/** A class to parse the Google Places in JSON format */ 
class ParserTask extends 
     AsyncTask<String, Integer, List<HashMap<String, String>>> { 

    JSONObject jObject; 

    // Invoked by execute() method of this object 
    @Override 
    protected List<HashMap<String, String>> doInBackground(
      String... jsonData) { 

     List<HashMap<String, String>> places = null; 
     GeocodeJSONParser parser = new GeocodeJSONParser(); 

     try { 
      jObject = new JSONObject(jsonData[0]); 

      /** Getting the parsed data as a an ArrayList */ 
      places = parser.parse(jObject); 

     } catch (Exception e) { 
      Log.d("Exception", e.toString()); 
     } 
     return places; 
    } 

    // Executed after the complete execution of doInBackground() method 
    @Override 
    protected void onPostExecute(List<HashMap<String, String>> list) { 
     PolylineOptions lineOptions = new PolylineOptions(); 
     ArrayList<LatLng>points=new ArrayList<LatLng>(); 
     // Clears all the existing markers 
     map.clear(); 

     for (int i = 0; i < list.size(); i++) { 

      // Creating a marker 
      MarkerOptions markerOptions = new MarkerOptions(); 

      // Getting a place from the places list 
      HashMap<String, String> hmPlace = list.get(i); 

      // Getting latitude of the place 
      lat = Double.parseDouble(hmPlace.get("lat")); 

      // Getting longitude of the place 
      lng = Double.parseDouble(hmPlace.get("lng")); 

      // Getting name 
      String name = hmPlace.get("formatted_address"); 

      latLng = new LatLng(lat, lng); 

      // Setting the position for the marker 
      markerOptions.position(latLng); 
      // getDirectionsUrl(Balvinder, latLng); 
      // markerOptions.position(Balvinder); 

        .show(); 
    map.addMarker(new MarkerOptions().title("My Location").snippet(
    gps.ConvertPointToLocation(latitude, longitude, 
          StartTripView.this)) 
      .position(Balvinder) 
      .icon(BitmapDescriptorFactory 
        .fromResource(R.drawable.logo_sono))); 
      markerPoints.add(Balvinder); 
      markerPoints.add(latLng); 
      //makeURL(latitude, longitude, lat, lng); 
    System.out.println("Result"+makeURL(latitude, longitude, lat, lng)); 
      // Polyline line = map.addPolyline(new PolylineOptions() 
      // .add(Balvinder, latLng) 
      // .width(5) 
      // .color(Color.RED).geodesic(true)); 




      markerOptions.title(name); 
      // 
      map.addMarker(markerOptions); 

    if (i == 0){ 
      map.animateCamera(CameraUpdateFactory.newLatLng(latLng)); 
      } 

     } 


} 

} 
+0

Что такое проблема с ваш код? Сбой? Сообщение об ошибке? неправильная информация? –

+0

no crash Это показывает два местоположения на карте, но я хочу провести маршрут между ними –

+0

Посмотрите на эту ссылку .... http://stackoverflow.com/questions/14710744/how-to-draw-road-directions -between-two-geocodes-in-android-google-map-v2/16315944 # 16315944 – Lawrance

ответ

0

Документация: https://developers.google.com/maps/documentation/android/shapes?hl=fr#polylines

Чтобы нарисовать маршрут между 2 места, вы должны использовать ломаную линию:

// Instantiates a new Polyline object and adds points to define a rectangle 
PolylineOptions rectOptions = new PolylineOptions() 
     .add(new LatLng(37.35, -122.0)) 
     .add(new LatLng(37.45, -122.0)) // North of the previous point, but at the same longitude 
     .add(new LatLng(37.45, -122.2)) // Same latitude, and 30km to the west 
     .add(new LatLng(37.35, -122.2)) // Same longitude, and 16km to the south 
     .add(new LatLng(37.35, -122.0)); // Closes the polyline. 

// Get back the mutable Polyline 
Polyline polyline = myMap.addPolyline(rectOptions); 

В вашем случае вы выиграли «Мне нужна последняя точка для закрытия полилинии.

+0

Я уже использовал этот код, но он только рисует прямую линию между двумя точками, не отображающими направления движения. –

+0

Он рисует линию между несколькими точками. Это то, что вы можете получить, чтобы проложить маршрут. Что вы ожидаете? –

0

Проверить этот пример Driving Direction

Вы можете использовать обратный Geocoding

 Geocoder geocoder = new Geocoder(context); 
    address = geocoder.getFromLocationName("your address"); 

получить LAT/LNG из адреса и передать, что в приведенном выше примере.

+0

предлагаемая ссылка показывает маршрут при касании карты. но iam передавая адреса в текстовом поле и отправляя на mapFragment, теперь я пытаюсь провести маршрут между этими двумя адресами. –

+0

да, а не то, что вы меняете в соответствии с вашими потребностями. После того, как у вас будет вызов вызова lat/lngURl и передайте значения. // Получение URL-адреса API Google Directions Строка url = getDirectionsUrl (origin, dest); DownloadTask downloadTask = new DownloadTask(); downloadTask.execute (url); –

0

Пожалуйста, сначала проверьте ур ответ апи ваш ключ действителен использование мой код ниже AsyncTask

 private class DownloadTask extends AsyncTask { 

    ProgressDialog asyncDialog = new ProgressDialog(NearGoogleMap.this); 




    String StatusOK="", url; 

    String data = ""; 
    JSONArray routeArray=null,LegsArray=null,StepsArray=null; 

    public DownloadTask(String url) { 
     this.url=url; 

    } 



    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     asyncDialog.setMessage("Please wait...!!!"); 
     //show dialog 
     asyncDialog.setCancelable(false); 
     asyncDialog.show(); 
    } 

    @Override 
    protected Object doInBackground(Object[] params) { 


     try { 
      data = downloadUrl(url); 
      Log.d("Background data Task", data.toString()); 



      if (data.isEmpty()) 
      { 

      }else { 
       JSONObject dataJSON =new JSONObject(data); 

       Log.d("data JSON", dataJSON.toString()); 

       StatusOK=dataJSON.getString("status"); 

       if (StatusOK.equals("OK")) 
       { 
        Log.d("Decode JSON","StatusOK"); 

        routeArray=dataJSON.getJSONArray("routes"); 


        for (int i=0;i<routeArray.length();i++) 
        { 
         Log.d("Decode JSON","routes"); 
         JSONObject inputJSON=routeArray.getJSONObject(i); 

         LegsArray=inputJSON.getJSONArray("legs"); 

         for (int j=0;j<LegsArray.length();j++) 
         { 
          Log.d("Decode JSON","legs"); 
          JSONObject inputJSONleg=LegsArray.getJSONObject(j); 

          StepsArray=inputJSONleg.getJSONArray("steps"); 

          for (int k=0;k<StepsArray.length();k++) 
          { 
           Log.d("Decode JSON","steps"); 
           JSONObject inputJSONstep=StepsArray.getJSONObject(k); 

           JSONObject PolylineJSON=inputJSONstep.getJSONObject("polyline"); 
           Log.d("Decode JSON","polyline"); 

           String getPolylineString=PolylineJSON.getString("points"); 
           Log.d("Decode JSON","points"); 

           List<LatLng> getPolypont=decodePolyNew(getPolylineString); 
           Log.d("Decode JSON","decodePolyNew"); 

           for (int z=0;z<getPolypont.size();z++) 
           { 
            Log.d("Decode JSON","DirectionPoint"); 
            DirectionPoint.add(new LatLng(getPolypont.get(z).latitude,getPolypont.get(z).longitude)); 
           } 





          } 




         } 


        } 




       } 




      } 



     } catch (Exception e) { 
      Log.d("Background Task", e.toString()); 
      data=""; 

     } 
     return null; 
    } 


    @Override 
    protected void onPostExecute(Object o) { 
     super.onPostExecute(o); 
     asyncDialog.dismiss(); 
     if (data.isEmpty()) 
     { 
      Toast.makeText(getBaseContext(),"Something went wrong",Toast.LENGTH_SHORT).show(); 

     }else { 
      if (DirectionPoint.size()==0) 
      { 

      }else { 
       PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true); 

       for (int z = 0; z < DirectionPoint.size(); z++) { 
        LatLng point = DirectionPoint.get(z); 
        options.add(point); 
       } 

       mMap.addPolyline(options); 











      } 
     } 
    } 
} 

// Внутри OnCreate() вызов метода AsyncTask следующим

   if (points.size()>=2) 
       { 
        // Getting URL to the Google Directions API 
        String url = getDirectionsUrl(points.get(0), points.get(1)); 

        Log.d("Get URL",url); 


        DownloadTask downloadTask = new DownloadTask(url); 

        // Start downloading json data from Google Directions API 
        downloadTask.execute(); 

       } 

      } 

// binding url getDirectionsUrl() 



     private String getDirectionsUrl(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"; 
     String mode = "mode=driving"; 

     // Building the parameters to the web service 
     String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode; 

     // 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; 
    } 



    // for decode polyline use this method 

     private List decodePolyNew(String encoded) { 

    List 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; 
} 
Смежные вопросы