Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
845 views
in Technique[技术] by (71.8m points)

json - travel time between two locations in Google Map Android API V2

how to display travel time between two locations in Google Map Android API V2, in my program i using JSONParse to display driving distance, but i'm can't to display the display travel time, This example program I made: DirectionActivity.java

public class DirectionActivity extends FragmentActivity implements OnMyLocationChangeListener{

private LatLng          start;
private LatLng          end;
private String          nama;
private final String    URL = "http://maps.googleapis.com/maps/api/directions/json?";
private GoogleMap       map;
private JSONHelper      json;
private ProgressDialog  pDialog;
private List<LatLng>    listDirections;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_direction);
    json = new JSONHelper();
    setupMapIfNeeded();

    Bundle b = getIntent().getExtras();
    if (b != null)
    {
        start = new LatLng(b.getDouble(MainActivity.KEY_LAT_ASAL), b.getDouble(MainActivity.KEY_LNG_ASAL));
        end = new LatLng(b.getDouble(MainActivity.KEY_LAT_TUJUAN), b.getDouble(MainActivity.KEY_LNG_TUJUAN));
        nama = b.getString(MainActivity.KEY_NAMA);
    }

    new AsyncTaskDirection().execute();
}

private void setupMapIfNeeded()
{
    if (map == null)
    {
        FragmentManager fragmentManager = getSupportFragmentManager();
        SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
                .findFragmentById(R.id.mapsdirections);
        map = supportMapFragment.getMap();

        if (map != null)
        {
            setupMap();
        }
    }

}

private void setupMap()
{
    map.setMyLocationEnabled(true);
    map.setOnMyLocationChangeListener(this);
    moveToMyLocation();
}

private void moveToMyLocation()
{
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
    if (location != null)
    {
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(location.getLatitude(), location.getLongitude()), 13));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
protected void onResume()
{
    // TODO Auto-generated method stub
    super.onResume();
    int resCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
    if (resCode != ConnectionResult.SUCCESS)
    {
        GooglePlayServicesUtil.getErrorDialog(resCode, this, 1);
    }
}

private class AsyncTaskDirection extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... params)
    {
        String uri = URL
                + "origin=" + start.latitude + "," + start.longitude
                + "&destination=" + end.latitude + "," + end.longitude
                + "&sensor=true&units=metric";

        JSONObject jObject = json.getJSONFromURL(uri);
        listDirections = json.getDirection(jObject);

        return null;
    }

    @Override
    protected void onPreExecute()
    {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pDialog = new ProgressDialog(DirectionActivity.this);
        pDialog.setMessage("Loading....");
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected void onPostExecute(Void result)
    {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        pDialog.dismiss();
        gambarDirection();
    }

}

public void gambarDirection()
{
    PolylineOptions line = new PolylineOptions().width(3).color(Color.BLUE);
    for (int i = 0; i < listDirections.size(); i++)
    {
        line.add(listDirections.get(i));
    }
    map.addPolyline(line);

    // tambah marker di posisi end
    map.addMarker(new MarkerOptions()
            .position(end)
            .title(nama));
}

@Override
public void onMyLocationChange(Location location)
{
    Toast.makeText(this, "Lokasi berubah ke " + location.getLatitude() + "," + location.getLongitude(),
            Toast.LENGTH_SHORT).show();

}

}

JSONHelper.java

public class JSONHelper
{
private InputStream     is              = null;
private JSONObject      jsonObject      = null;
private String          json            = "";

private final String    TAG_TEMPATMAKAN = "tempatmakan";
private final String    TAG_ID          = "id";
private final String    TAG_NAMA        = "nama";
private final String    TAG_ALAMAT      = "alamat";
private final String    TAG_LAT         = "lat";
private final String    TAG_LNG         = "lng";
private final String    TAG_ROUTES      = "routes";
private final String    TAG_LEGS        = "legs";
private final String    TAG_STEPS       = "steps";
private final String    TAG_POLYLINE    = "polyline";
private final String    TAG_POINTS      = "points";
private final String    TAG_START       = "start_location";
private final String    TAG_END         = "end_location";

public JSONObject getJSONFromURL(String url)
{
    try
    {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e)
    {
        e.printStackTrace();
    } catch (ClientProtocolException e)
    {
        e.printStackTrace();
    } catch (IOException e)
    {
        e.printStackTrace();
    }

    try
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);

        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "
");
        }

        is.close();
        json = sb.toString();
    } catch (Exception e)
    {
        // TODO: handle exception
    }

    try
    {
        jsonObject = new JSONObject(json);

    } catch (JSONException e)
    {
        // TODO: handle exception
    }

    return jsonObject;
}

public ArrayList<TempatMakan> getTempatMakanAll(JSONObject jobj)
{
    ArrayList<TempatMakan> listTempatMakan = new ArrayList<TempatMakan>();

    try
    {
        JSONArray arrayTempatMakan = jobj.getJSONArray(TAG_TEMPATMAKAN);

        for (int i = 0; i < arrayTempatMakan.length(); i++)
        {
            JSONObject jobject = arrayTempatMakan.getJSONObject(i);

            Log.d("log", "muter ke " + i);
            listTempatMakan.add(new TempatMakan(jobject.getInt(TAG_ID), jobject.getString(TAG_NAMA), jobject
                    .getString(TAG_ALAMAT), jobject
                    .getDouble(TAG_LAT), jobject.getDouble(TAG_LNG)));

        }
    } catch (JSONException e)
    {
        e.printStackTrace();
    }
    return listTempatMakan;
}

/*
 * Untuk decode Polyline
 * 
 * @params String
 * 
 * @return List<LatLng>
 */
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 position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
        poly.add(position);
    }
    return poly;

}

/*
 * Untuk mendapatkan direction
 * 
 * @params JSONObject
 * 
 * @return List<LatLng>
 */
public List<LatLng> getDirection(JSONObject jObj)
{

    List<LatLng> directions = new ArrayList<LatLng>();

    try
    {
        JSONObject objRoute = jObj.getJSONArray(TAG_ROUTES).getJSONObject(0);
        JSONObject objLegs = objRoute.getJSONArray(TAG_LEGS).getJSONObject(0);
        JSONArray arraySteps = objLegs.getJSONArray(TAG_STEPS);
        for (int wi2t = 0; wi2t < arraySteps.length(); wi2t++)
        {
            JSONObject step = arraySteps.getJSONObject(wi2t);
            JSONObject objStart = step.getJSONObject(TAG_START);
            JSONObject objEnd = step.getJSONObject(TAG_END);
            double latStart = objStart.getDouble(TAG_LAT);
            double lngStart = objStart.getDouble(TAG_LNG);

            directions.add(new LatLng(latStart, lngStart));

            JSONObject poly = step.getJSONObject(TAG_POLYLINE);
            String encodedPoly = poly.getString(TAG_POINTS);

            List<LatLng> decodedPoly = decodePoly(encodedPoly);
            for (int eka = 0; eka < decodedPoly.size(); eka++)
            {
                directions.add(new LatLng(decodedPoly.get(eka).latitude, decodedPoly.get(eka).longitude));
            }

            double latEnd = objEnd.getDouble(TAG_LAT);
            double lngEnd = objEnd.getDouble(TAG_LNG);
            directions.add(new LatLng(latEnd, lngEnd));

        }
    } catch (JSONException e)
    {
        // TODO: handle exception
    }

    return directions;
}
}

MainActivity.java

public class MainActivity extends FragmentActivity implements OnInfoWindowClickListener
{
private GoogleMap           map;
private JSONHelper          json;
private ProgressDialog      pDialog;
private Button      btnGetDirection;

private List<TempatMakan>   listTempatMakan;
private final String        URL_API     = "http://lhocation1203.hostzi.com/dataapi/tempatmakan.php";

public static final String  KEY_NAMA    = "nama";
public static final String  KEY_ALAMAT  = "alamat";
public static final String  KEY_LAT_TUJUAN  = "lat_tujuan";
public static final String  KEY_LNG_TUJUAN  = "lng_tujuan";
public static final String  KEY_LAT_ASAL    = "lat_asal";
public static final String  KEY_LNG_ASAL    = "lng_asal";

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    json = new JSONHelper();

    new AsynTaskMain().execute();

    setupMapIfNeeded();
}

private void setupMapIfNeeded()
{
    if (map == null)
    {
        FragmentManager fragmentManager = getSupportFragmentManager();
        SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.maps);
        map = supportMapFragment.getMap();

        if (map != null)
        {
            setupMap();
        }
    }

}

private void setupMap()
{
    map.setMyLocationEnabled(true);
    map.setOnInfoWindowClickListener(this);
    moveToMyLocation();
}

private void moveToMyLocation()
{
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Google Directions JSON Response has an object called Distance and Duration within "LEGS" array, like this :

"legs": [
                {
                    "distance": {
                        "text": "0.3 km", 
                        "value": 263
                    }, 
                    "duration": {
                        "text": "1 min", 
                        "value": 52
                    }, 
                 ....... //omitted value
        ]

Thus you can try parsing the distance and duration (if you need it) into your app. Maybe like this :

JSONArray legs = jobject.getString("legs");
for (int i = 0; i < legs.length(); i++)
    {
        JSONObject legsObject = legs.getJSONObject(i);
        JSONObject distanceObject = legsObject.getString("distance");
        String distanceText = distanceObject.getString("text");
        String distanceValue = String.valueOf(distanceObject.getString("value"));
        //do anything else
    }

oh, and put the legs array parsing inside the ArrayTempatMakan parsing. I can get the distance and duration using Jackson JSON parser, so you should be able to do it with org.JSON parser.

Good luck ^^

EDIT :

In this getDirection (JSONObject jObj) method You successfully retrieve objLegs here, you need to get the Distance and Duration within objLegs

    JSONObject objRoute = jObj.getJSONArray(TAG_ROUTES).getJSONObject(0);
    JSONObject objLegs = objRoute.getJSONArray(TAG_LEGS).getJSONObject(0);
    JSONArray arraySteps = objLegs.getJSONArray(TAG_STEPS);

I think you should add this below objLegs:

JSONObject objDistance = objLegs.getJSONObject("distance");
JSONObject objDuration = objLegs.getJSONObject("duration");
String text_distance = objDistance.getString("text");
Log.d("Distance", text_distance); //adds an entry to the logCat, Check whether the value of Distance is successfully taken.
String text_duration = objDuration.getString("text");
Log.d("Duration", text_duration); //adds an entry to the logCat, Check whether the value of Distance is successfully taken.

There, I believe you should be able to grab the value, after that, you can just add the value into your list result.

If you're still unable to insert distance and duration, please include the TempatMakan class on your post.

EDIT 2 :

Declare distance and duration as string inside your TempatMakan.Java :

private String durasi;
private String jarak;

inside your constructor :

public TempatMakan(int id, String nama, String alamat, String jarak, String durasi, double lat, double lng)
{
    super();
    this.id = id;
    this.nama = nama;
    this.alamat = alamat;
    this.lat = lat;
    this.lng = lng;
    this.jarak = jarak;
    this.durasi = durasi;
}

then declare the respective getters and setters for jarak and durasi.

Inside your JSONHelper.java, the getTempatMakanAll method, add these :

for (int i = 0; i < arrayTempatMakan.length(); i++)
        {
            JSONObject jobject = arrayTempatMakan.getJSONObject(i);
            JSONObject objRoute = jobject.getJSONArray(TAG_ROUTES).getJSONObject(0);
            JSONObject objLegs = objRoute.getJSONArray(TAG_LEGS).getJSONObject(0);
            JSONObject objDistance = objLegs.getJSONObject("distance");
            JSONObject objDuration = objLegs.getJSONObject("duration");

            Log.d("log", "muter ke " + i);
            listTempatMakan.add(
            new TempatMakan(
                    jobject.getInt(TAG_ID),
                    jobject.getString(TAG_NAMA),
                    jobject.getString(TAG_ALAMAT),
                    objDistance.getString("text"),//jarak
                    objDuration.getString("text"),//durasi
                    jobject.getDouble(TAG_LAT),
                    jobject.getDouble(TAG_LNG)));

        }

after that, just modify your listview adapter to display those values.

Good Luck, and Sorry, I can't give you another code or modify your project, you would have to figure out yourself :)

P.S : Skripsi or Tugas Kuliah?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...