0

嗨,我是在google Map API中更改后第一次在 android中使用地图。

现在我想在我为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));
            }

        }


}

}
4

3 回答 3

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);

在您的情况下,您不需要最后一点来关闭折线。

于 2013-07-22T07:11:05.020 回答
0

检查此示例行驶方向

您可以使用反向地理编码

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

从地址获取 lat/lng 并在上面的示例中传递它。

于 2013-07-22T07:14:50.947 回答
0

请首先检查您的 api 响应是否您的密钥有效使用我下面的 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;
}
于 2017-05-10T08:45:36.317 回答