0

こんにちは、 Google Map APIで変更した後、初めてAndroid でマップを使用しています。

ここで、 API v2用に私が作成した2 つのアドレス間のルートを地図上に描画したいと考えています。これを行う方法がわかりません。私はこれのために多くのことを試みました。私を助けてください。ありがとう。

私のコードは次のとおりです。

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

住所から緯度/経度を取得し、上記の例に渡します。

于 2013-07-22T07:14:50.947 に答える