Android Google Maps v2路由显示路由不工作

Android Google Maps v2路由显示路由不工作,android,google-maps,httprequest,google-maps-api-2,polyline,Android,Google Maps,Httprequest,Google Maps Api 2,Polyline,我试图使用谷歌API v2在我的应用程序中设置路线方向,但我遇到了一个错误,我找不到导致问题的原因 D/Exception while reading url﹕ java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/directions/json?waypoints=optimize:true|-23.3246,-51.1489|-23.3206,-51.1459|-23.2975,-51.2007&sen

我试图使用谷歌API v2在我的应用程序中设置路线方向,但我遇到了一个错误,我找不到导致问题的原因

D/Exception while reading url﹕ java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/directions/json?waypoints=optimize:true|-23.3246,-51.1489|-23.3206,-51.1459|-23.2975,-51.2007&sensor=false
当我在Chrome上复制并粘贴该链接时,我得到以下信息:

“错误消息”:“请求无效。缺少'origin'参数。”

这是我的地图课:

public class MapaViagem extends FragmentActivity {

    private GoogleMap googleMap;
    private String IdViagem;
    private List<EnderecoModel> mEnderecoModel = new ArrayList<EnderecoModel>();
    private ArrayList<LatLng> coordList = new ArrayList<LatLng>();
    private ProgressDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        setContentView(R.layout.maps);

        // Loading map
        initilizeMap();

        // Changing map type
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        // googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        // googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        // googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        // googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

        // Showing / hiding your current location
        googleMap.setMyLocationEnabled(true);

        // Enable / Disable zooming controls
        googleMap.getUiSettings().setZoomControlsEnabled(true);

        // Enable / Disable my location button
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);

        // Enable / Disable Compass icon
        googleMap.getUiSettings().setCompassEnabled(true);

        // Enable / Disable Rotate gesture
        googleMap.getUiSettings().setRotateGesturesEnabled(true);

        // Enable / Disable zooming functionality
        googleMap.getUiSettings().setZoomGesturesEnabled(true);

        try {

            Bundle parametros = getIntent().getExtras();
            IdViagem = parametros.getString("id_viagem");


            Repositorio mRepositorio = new Repositorio(this);

            String waypoints = "waypoints=optimize:true";
            String coordenadas = "";

            mEnderecoModel = mRepositorio.getListaEnderecosDaViagem(Integer.valueOf(IdViagem));


            for (int j = 0; j < mEnderecoModel.size(); j++) {


                float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
                float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());

                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 10));

                coordenadas += "|" + latitude + "," + longitude;

                coordList.add(new LatLng(latitude, longitude));


                // Creating MarkerOptions
                MarkerOptions options = new MarkerOptions();

                // Setting the position of the marker

                options.position(new LatLng(latitude, longitude));


                if (j == mEnderecoModel.size() - 1) {

                    options.icon(BitmapDescriptorFactory.fromBitmap(writeTextOnDrawable(R.drawable.vermelho, String.valueOf(mEnderecoModel.size()))));


                } else {
                    options.icon(BitmapDescriptorFactory.fromBitmap(writeTextOnDrawable(R.drawable.verde, String.valueOf(j + 1))));
                }

                // Add new marker to the Google Map Android API V2
                googleMap.addMarker(options);


            }


            String sensor = "sensor=false";
            String params = waypoints + coordenadas + "&" + sensor;
            String url = "https://maps.googleapis.com/maps/api/directions/json?" + params;
            ReadTask downloadTask = new ReadTask();
            downloadTask.execute(url);


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


    private class ReadTask extends AsyncTask<String, String, String> {


        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(MapaViagem.this);
            // setup your dialog here
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setTitle("Traçando Rotas");
            dialog.setMessage("Aguarde...");
            dialog.setCancelable(false);
            dialog.show();

        }


        @Override
        protected String doInBackground(String... url) {

            String data = "";
            try {
                HttpConnection http = new HttpConnection();
                data = http.readUrl(url[0]);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return data;
        }


        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            new ParserTask().execute(result);


        }


    }

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

        @Override
        protected List<List<HashMap<String, String>>> doInBackground(
                String... jsonData) {


            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jObject = new JSONObject(jsonData[0]);
                PathJSONParser parser = new PathJSONParser();
                routes = parser.parse(jObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return routes;
        }

        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
            ArrayList<LatLng> points = null;
            PolylineOptions polyLineOptions = null;


            if(routes != null){
                for (int i = 0; i < routes.size(); i++) {
                    points = new ArrayList<LatLng>();
                    polyLineOptions = new PolylineOptions();
                    List<HashMap<String, String>> path = routes.get(i);

                    for (int j = 0; j < path.size(); j++) {
                        HashMap<String, String> point = path.get(j);

                        double lat = Double.parseDouble(point.get("lat"));
                        double lng = Double.parseDouble(point.get("lng"));
                        LatLng position = new LatLng(lat, lng);

                        points.add(position);
                    }

                    polyLineOptions.addAll(points);
                    polyLineOptions.width(4);
                    polyLineOptions.color(Color.BLUE);
                }
                googleMap.addPolyline(polyLineOptions);
            }

            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }


    private Bitmap writeTextOnDrawable(int drawableId, String text) {

        Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId)
                .copy(Bitmap.Config.ARGB_8888, true);

        Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);

        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.WHITE);
        paint.setTypeface(tf);
        paint.setTextAlign(Paint.Align.CENTER);
        paint.setTextSize(convertToPixels(MapaViagem.this, 11));

        Rect textRect = new Rect();
        paint.getTextBounds(text, 0, text.length(), textRect);

        Canvas canvas = new Canvas(bm);

        //If the text is bigger than the canvas , reduce the font size
        if (textRect.width() >= (canvas.getWidth() - 4))     //the padding on either sides is considered as 4, so as to appropriately fit in the text
            paint.setTextSize(convertToPixels(MapaViagem.this, 7));        //Scaling needs to be used for different dpi's

        //Calculate the positions
        int xPos = (canvas.getWidth() / 2) - 1;     //-2 is for regulating the x position offset

        //"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
        int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 8f));

        canvas.drawText(text, xPos, yPos, paint);

        return bm;
    }


    public static int convertToPixels(Context context, int nDP) {
        final float conversionScale = context.getResources().getDisplayMetrics().density;

        return (int) ((nDP * conversionScale) + 0.5f);

    }


    private void initilizeMap() {

        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onBackPressed() {

        super.onBackPressed();
        overridePendingTransition(R.anim.animation_back, R.anim.animation_back_leave);
        finish();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_mapa, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public boolean onOptionsItemSelected(MenuItem item) {


        switch (item.getItemId()) {

            case android.R.id.home:
                super.onBackPressed();
                overridePendingTransition(R.anim.animation_back, R.anim.animation_back_leave);
                finish();

                return true;

            case R.id.menu_atualizar_mapa:
                 /* dispara os repositorios a sincronizar */

                new Sincronizar(MapaViagem.this, MapaViagem.this).execute(0);


        }

        return true;

    }

    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();
    }


}
公共类映射策略扩展了碎片活动{
私人谷歌地图谷歌地图;
私有字符串IdViagem;
private List mEnderecoModel=new ArrayList();
私有ArrayList coordList=新ArrayList();
私人对话;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.maps);
//装载图
initilizeMap();
//更改地图类型
googleMap.setMapType(googleMap.MAP\u TYPE\u NORMAL);
//setMapType(googleMap.MAP\u TYPE\u HYBRID);
//googleMap.setMapType(googleMap.MAP类型卫星);
//googleMap.setMapType(googleMap.MAP\u TYPE\u地形);
//googleMap.setMapType(googleMap.MAP\u TYPE\u NONE);
//显示/隐藏当前位置
googleMap.setMyLocationEnabled(true);
//启用/禁用缩放控件
googleMap.getUiSettings().setZoomControlsEnabled(true);
//启用/禁用我的位置按钮
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
//启用/禁用指南针图标
googleMap.getUiSettings().setCompassEnabled(true);
//启用/禁用旋转手势
googleMap.getUiSettings().setRotategestureEnabled(true);
//启用/禁用缩放功能
googleMap.getUiSettings().SetZoomGetUreSEnabled(true);
试一试{
Bundle parametros=getIntent().getExtras();
IdViagem=parametros.getString(“id_viagem”);
Repositorio mRepositorio=新的Repositorio(本);
String waypoints=“waypoints=optimize:true”;
字符串coordenadas=“”;
mEnderecoModel=mRepositorio.getListaEnderecosDaViagem(Integer.valueOf(IdViagem));
对于(int j=0;j  private String getMapsApiDirectionsUrl(LatLng Office, LatLng home) {
       String waypoints = "waypoints=optimize:true|"
            + Office.latitude + "," + Office.longitude
            + "|" + "|" +  home.latitude + ","
            + home.longitude;
    String OriDest = "origin="+Office.latitude+","+Office.longitude+"&destination="+home.latitude+","+home.longitude;

    String sensor = "sensor=false";
    String params = OriDest+"&%20"+waypoints + "&" + sensor;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/"
            + output + "?" + params;
    return url;
}