如何获得驱动两个位置之间的距离? [英] How to get driving distance between two locations?

查看:177
本文介绍了如何获得驱动两个位置之间的距离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用GoogleMapv2 API在我的应用程序。我想画一个多边形线从源到目的地。并展示了旅行时间,以及在地图上的活动距离,但我无法找到它。请帮我。 我的code段是在这里:

 公共类NavigationActivity扩展FragmentActivity {
    公共静态最后弦乐TAG_SLAT =sourcelat;
    公共静态最后弦乐TAG_SLONG =sourcelong;
    公共静态最后弦乐TAG_DLAT =destinationlat;
    公共静态最后弦乐TAG_DLONG =destinationg;

    私有静态经纬度源= NULL;
    私有静态经纬度目标= NULL;

    私人GoogleMap的地图;
    私人SupportMapFragment片段;
    私人的LatLngBounds的LatLngBounds;
    私人按钮bNavigation;
    私人折线newPolyline;
    私人标记smarker;
    私人标记dmarker;

    私人布尔isTraveling = FALSE;
    私人诠释的宽度,高度;
    私人字符串sourcelat;
    私人字符串sourcelong;
    私人字符串destinationg;
    私人字符串destinationlat;
    双板条;
    双slong;
    双DLAT;
    双dlong;
    TextView的tvDistanceDuration;


    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_navigation);
        tvDistanceDuration =(TextView中)findViewById(R.id.tv_distance_time);
        意图= getIntent();
        sourcelat = in.getStringExtra(TAG_SLAT);
        destinationlat = in.getStringExtra(TAG_DLAT);
        destinationg = in.getStringExtra(TAG_DLONG);
        sourcelong = in.getStringExtra(TAG_SLONG);


         板条= Double.parseDouble(sourcelat);
         slong = Double.parseDouble(sourcelong);
         DLAT = Double.parseDouble(destinationlat);
         dlong = Double.parseDouble(destinationg);
        来源=新的经纬度(板条,slong);
        目标=新的经纬度(DLAT,dlong);

        getSreenDimanstions();
        片段=((SupportMapFragment)getSupportFragmentManager()findFragmentById(R.id.map));
        地图= fragment.getMap();


                如果(!isTraveling){
                    isTraveling = TRUE;


                    findDirections(Source.latitude,Source.longitude,Destination.latitude,Destination.longitude,GMapV2Direction.MODE_DRIVING);
                    DecimalFormat的DF1 =新的DecimalFormat(#0000);
                    双DLAT = Math.toRadians(DLAT  - 板条);
                    双dLon = Math.toRadians(dlong  -  slong);
                    双A = Math.sin(DLAT / 2)* Math.sin(DLAT / 2)
                            + Math.cos(Math.toRadians(板条))
                            * Math.cos(Math.toRadians(DLAT))* Math.sin(dLon / 2)
                            * Math.sin(dLon / 2);
                    双C = 2 * Math.atan2(的Math.sqrt(一)的Math.sqrt(1  -  a)条);
                    双tempDistance = 6371 * C;
                    Log.v(SDS ...,将String.valueOf(tempDistance));
                } 其他 {
                    isTraveling = FALSE;

                }

    }

    @覆盖
    保护无效onResume(){

        super.onResume();
        的LatLngBounds = createLatLngBoundsObject(源,目的地);
        map.moveCamera(CameraUpdateFactory.newLatLngBounds(的LatLngBounds,宽度,高度,150));

    }

    公共无效handleGetDirectionsResult(ArrayList中<经纬度> directionPoints){
        PolylineOptions rectLine =新PolylineOptions()宽(5)。颜色(Color.RED)。
        MarkerOptions标记=新MarkerOptions().position(Source).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        MarkerOptions MARKER1 =新MarkerOptions().position(Destination).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));


        的for(int i = 0; I< directionPoints.size();我++)
        {
            rectLine.add(directionPoints.get(ⅰ));


        }
        如果(newPolyline!= NULL)
        {
            newPolyline.remove();
        }
        newPolyline = map.addPolyline(rectLine);
        smarker = map.addMarker(标记);
        dmarker = map.addMarker(MARKER1);
        如果(isTraveling)
        {

            的LatLngBounds = createLatLngBoundsObject(源,目的地);
            map.animateCamera(CameraUpdateFactory.newLatLngBounds(的LatLngBounds,宽度,高度,150));
        }
        其他
        {

            map.animateCamera(CameraUpdateFactory.newLatLngBounds(的LatLngBounds,宽度,高度,150));
        }

    }

    私人无效getSreenDimanstions()
    {
        显示显示= getWindowManager()getDefaultDisplay()。
        宽度= display.getWidth();
        身高= display.getHeight();
    }

    私人的LatLngBounds createLatLngBoundsObject(经纬度firstLocation,经纬度secondLocation)
    {
        如果(firstLocation = NULL和放大器;!&安培;!secondLocation = NULL)
        {
            LatLngBounds.Builder建设者=新LatLngBounds.Builder();
            builder.include(firstLocation).INCLUDE(secondLocation);

            返回builder.build();
        }
        返回null;
    }


    公共无效findDirections(双fromPositionDoubleLat,双fromPositionDoubleLong,双toPositionDoubleLat,双toPositionDoubleLong,字符串模式)
    {
        地图<字符串,字符串>图=新的HashMap<字符串,字符串>();
        map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT,将String.valueOf(fromPositionDoubleLat));
        map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG,将String.valueOf(fromPositionDoubleLong));
        map.put(GetDirectionsAsyncTask.DESTINATION_LAT,将String.valueOf(toPositionDoubleLat));
        map.put(GetDirectionsAsyncTask.DESTINATION_LONG,将String.valueOf(toPositionDoubleLong));
        map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE,模式);

        GetDirectionsAsyncTask的AsyncTask =新GetDirectionsAsyncTask(本);
        asyncTask.execute(图)
    }
}
 

的AsyncTask类code如下.........

 公共类GetDirectionsAsyncTask扩展的AsyncTask<地图<字符串,字符串>中对象的ArrayList<经纬度>>
{
    公共静态最后弦乐USER_CURRENT_LAT =user_current_lat;
    公共静态最后弦乐USER_CURRENT_LONG =user_current_long;
    公共静态最后弦乐DESTINATION_LAT =destination_lat;
    公共静态最后弦乐DESTINATION_LONG =destination_long;
    公共静态最后弦乐DIRECTIONS_MODE =directions_mode;
    私人NavigationActivity活动;
    私人例外的例外;
    私人ProgressDialog progressDialog;

    公共GetDirectionsAsyncTask(NavigationActivity活动)
    {
        超();
        this.activity =活动;
    }

    在preExecute公共无效()
    {
        progressDialog =新ProgressDialog(活动);
        progressDialog.setMessage(计算方向);
        progressDialog.show();
    }

    @覆盖
    公共无效onPostExecute(ArrayList的结果)
    {
        progressDialog.dismiss();
        如果(例外== NULL)
        {
            activity.handleGetDirectionsResult(结果);
        }
        其他
        {
            processException();
        }
    }

    @覆盖
    受保护的ArrayList<经纬度> doInBackground(地图<字符串,字符串> ... PARAMS)
    {
        地图<字符串,字符串> paramMap = PARAMS [0];
        尝试
        {
            经纬度fromPosition =新的经纬度(Double.valueOf(paramMap.get(USER_CURRENT_LAT)),Double.valueOf(paramMap.get(USER_CURRENT_LONG)));
            经纬度toPosition =新的经纬度(Double.valueOf(paramMap.get(DESTINATION_LAT)),Double.valueOf(paramMap.get(DESTINATION_LONG)));
            GMapV2Direction MD =新GMapV2Direction();
            文档DOC = md.getDocument(fromPosition,toPosition,paramMap.get(DIRECTIONS_MODE));
            ArrayList的<经纬度> directionPoints = md.getDirection(DOC);
            返回directionPoints;
        }
        赶上(例外五)
        {
            异常= E;
            返回null;
        }
    }

    私人无效processException()
    {
        Toast.makeText(活动,错误检索数据,Toast.LENGTH_SHORT).show();
    }
}
 

和类GET方向如下:

 公共类GMapV2Direction {
    公共最后静态字符串MODE_DRIVING =驾驶;
    公共最后静态字符串MODE_WALKING =行走;

    公共GMapV2Direction(){}

    公开文件getDocument(经纬度开始,经纬度结束,字符串模式){
        字符串URL =htt​​p://maps.googleapis.com/maps/api/directions/xml?
                +原产地=+ start.latitude +,+ start.longitude
                +与&目的地=+ end.latitude +,+ end.longitude
                +&放大器,传感器=假放;单位=指标和放大器;模式=驾驶;

        尝试 {
            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpContext的localContext =新BasicHttpContext();
            HttpPost httpPost =新HttpPost(URL);
            HTT presponse响应= httpClient.execute(httpPost,localContext);
            。InputStream的时间= response.getEntity()的getContent();
            DocumentBuilder的建设者= DocumentBuilderFactory.newInstance()newDocumentBuilder()。
            文档DOC = builder.parse(中);
            返回文档;
        }赶上(例外五){
            e.printStackTrace();
        }
        返回null;
    }

    公共字符串getDurationText(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(期限);
        节点节点1 = nl1.item(0);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,文本));
        Log.i(DurationText,node2.getTextContent());
        返回node2.getTextContent();
    }

    公众诠释getDurationValue(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(期限);
        节点节点1 = nl1.item(0);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,值));
        Log.i(DurationValue,node2.getTextContent());
        返回的Integer.parseInt(node2.getTextContent());
    }

    公共字符串getDistanceText(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(距离);
        INT I;

        //从XML最后一个标签

        对于(i = 0; I< nl1.getLength();我++){

        }

        如果(我== I){
            一世 - ;
        }

        节点节点1 = nl1.item(ⅰ);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,文本));
        Log.i(DistanceText,node2.getTextContent());
        返回node2.getTextContent();
    }

    公众诠释getDistanceValue(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(距离);
        节点节点1 = nl1.item(0);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,值));
        Log.i(DistanceValue,node2.getTextContent());
        返回的Integer.parseInt(node2.getTextContent());
    }

    公共字符串getStartAddress(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(START_ADDRESS);
        节点节点1 = nl1.item(0);
        Log.i(StartAddress开始,node1.getTextContent());
        返回node1.getTextContent();
    }

    公共字符串getEndAddress(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(end_address);
        节点节点1 = nl1.item(0);
        Log.i(StartAddress开始,node1.getTextContent());
        返回node1.getTextContent();
    }

    公共字符串getCop​​yRights(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(著作权);
        节点节点1 = nl1.item(0);
        Log.i(著作权,node1.getTextContent());
        返回node1.getTextContent();
    }

    公众的ArrayList<经纬度> getDirection(DOC文件){
        节点列表NL1,NL2,NL3;
        ArrayList的<经纬度> listGeopoints =新的ArrayList<经纬度>();
        NL1 = doc.getElementsByTagName(步);
        如果(nl1.getLength()大于0){
            的for(int i = 0; I< nl1.getLength();我++){
                节点节点1 = nl1.item(ⅰ);
                NL2 = node1.getChildNodes();

                节点locationNode = nl2.item(getNodeIndex(NL2的start_location));
                NL3 = locationNode.getChildNodes();
                节点latNode = nl3.item(getNodeIndex(NL3,纬度​​));
                双纬度= Double.parseDouble(latNode.getTextContent());
                节点lngNode = nl3.item(getNodeIndex(NL3,LNG));
                双LNG = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(新经纬度(纬度,经度));

                locationNode = nl2.item(getNodeIndex(NL2,折线));
                NL3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(NL3,分));
                ArrayList的<经纬度> ARR =去$ C $℃聚(latNode.getTextContent());
                对于(INT J = 0; J< arr.size(); J ++){
                    listGeopoints.add(新经纬度(arr.get(J).latitude,arr.get(J).longitude));
                }

                locationNode = nl2.item(getNodeIndex(NL2,END_LOCATION));
                NL3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(NL3,纬度​​));
                纬度= Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(NL3,LNG));
                液化天然气= Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(新经纬度(纬度,经度));
            }
        }

        返回listGeopoints;
    }

    私人诠释getNodeIndex(节点列表NL,串节点名称){
        的for(int i = 0; I< nl.getLength();我++){
            如果(nl.item(我).getNodeName()。等于(节点名称))
                返回我;
        }
        返回-1;
    }

    私人的ArrayList<经纬度>德$ C $℃聚(字符串连接codeD){
        ArrayList的<经纬度>聚=新的ArrayList<经纬度>();
        INT指数= 0,len个= EN coded.length();
        INT纬度= 0,LNG = 0;
        而(指数< LEN){
            INT B,移= 0,结果为0;
            做 {
                B = EN coded.charAt(指数++) -  63;
                结果| =(B和0x1F的)LT;<转移;
                Shift + = 5;
            }而(B> = 0x20的);
            INT DLAT =((导致&安培; 1)= 0〜(结果>→1):!?(导致>→1));
            纬度+ = DLAT;
            移= 0;
            结果= 0;
            做 {
                B = EN coded.charAt(指数++) -  63;
                结果| =(B和0x1F的)LT;<转移;
                Shift + = 5;
            }而(B> = 0x20的);
            INT dlng =((导致&安培; 1)= 0〜(结果>→1):!?(导致>→1));
            LNG + = dlng;

            经纬度位置=新的经纬度((双)纬度/ 1E5,(双)LNG / 1E5);
            poly.add(位置);
        }
        返回聚;
    }
 

解决方案

您可以得到Trvelling的时间和距离,下面code ..我已经使用这个code在我的项目之一,希望这将有助于您

  CalculateDistanceTime distance_task =新CalculateDistanceTime(getActivity());

distance_task.getDirectionsUrl(startLatLng,endLatLng);

distance_task.setLoadListener(新CalculateDistanceTime.taskCompleteListener(){
           @覆盖
           公共无效taskCompleted(字符串[] time_distance){
                   approximate_time.setText(+ time_distance [1]);
                   approximate_diatance.setText(+ time_distance [0]);
           }

 });
 

和这里是CalculateDistanceTime类。

 进口android.content.Context;
    进口android.os.AsyncTask;
    进口android.util.Log;

    进口com.google.android.gms.maps.model.LatLng;

    进口org.json.JSONObject;

    进口java.io.BufferedReader中;
    进口java.io.IOException异常;
    进口的java.io.InputStream;
    进口java.io.InputStreamReader中;
    进口java.net.HttpURLConnection中;
    进口的java.net.URL;
    进口的java.util.HashMap;
    进口java.util.Iterator的;
    进口的java.util.List;
    进口java.util.Set中;

    公共类CalculateDistanceTime {

        私人taskCompleteListener mTaskListener;
        私人语境mContext;


        公共CalculateDistanceTime(上下文的背景下){
            mContext =背景;
        }

        公共无效setLoadListener(taskCompleteListener taskListener){
            mTaskListener = taskListener;
        }


        公共无效getDirectionsUrl(经纬度的起源,经纬度DEST){

            //路由地
            字符串str_origin =原产地=+ origin.latitude +,+ origin.longitude;

            //路由的目的
            字符串str_dest =目标=+ dest.latitude +,+ dest.longitude;


            //传感器启用
            弦传感器=传感器=假;

            //构建参数的web服务
            字符串参数= str_origin +&放大器; + str_dest +与& +传感器;

            // 输出格式
            字符串输出=JSON;

            //构建URL给Web服务
            字符串URL =htt​​ps://maps.googleapis.com/maps/api/directions/+输出+? +参数;


            DownloadTask downloadTask =新DownloadTask();

            //开始从谷歌路线API下载JSON数据

            downloadTask.execute(URL);
        }

        私人字符串downloadUrl(字符串strUrl)抛出IOException异常{
            字符串数据=;
            的InputStream的IStream = NULL;
            HttpURLConnection类的URLConnection = NULL;
            尝试 {
                网址URL =新的URL(strUrl);

                //创建一个HTTP连接,与URL沟通
                的URLConnection =(HttpURLConnection类)url.openConnection();

                //连接给url
                urlConnection.connect();

                //从URL中读取数据
                的IStream = urlConnection.getInputStream();

                的BufferedReader BR =新的BufferedReader(新的InputStreamReader(的IStream));

                StringBuffer的SB =新的StringBuffer();

                串线=;
                而((行= br.readLine())!= NULL){
                    sb.append(线);
                }

                数据= sb.toString();

                br.close();

            }赶上(例外五){
                Log.d(异常边下载网址,e.toString());
            } 最后 {
                iStream.close();
                urlConnection.disconnect();
            }
            返回的数据;
        }


        公共接口taskCompleteListener {
            无效taskCompleted(字符串[] time_distance);
        }

        私有类DownloadTask扩展的AsyncTask<字符串,太虚,字符串> {

            //下载在非UI线程的数据
            @覆盖
            保护字符串doInBackground(字符串... URL){

                //从网络服务中存储的数据
                字符串数据=;

                尝试 {
                    //获取从Web服务中的数据
                    数据= downloadUrl(URL [0]);
                }赶上(例外五){
                    Log.d(后台任务,e.toString());
                }
                返回的数据;
            }

            //执行的UI线程,执行后
            // doInBackground()
            @覆盖
            保护无效onPostExecute(字符串结果){
                super.onPostExecute(结果);

                ParserTask parserTask =新ParserTask();

                //调用线程解析JSON数据
                parserTask.execute(结果);

            }
        }

        私有类ParserTask扩展的AsyncTask<字符串,整数,列表< HashMap的<字符串,字符串>>> {

            //解析在非UI线程的数据
            @覆盖
            受保护的名单,其中,HashMap的<字符串,字符串>> doInBackground(字符串... jsonData){

                的JSONObject jObject;
                名单< HashMap的<字符串,字符串>>路线= NULL;

                尝试 {
                    jObject =新的JSONObject(jsonData [0]);
                    DistanceTimeParser分析器=新DistanceTimeParser();

                    //开始分析数据
                    路线= parser.parse(jObject);
                }赶上(例外五){
                    e.printStackTrace();
                }
                返回路线;
            }

            //执行的UI线程,解析过程后,
            @覆盖
            保护无效onPostExecute(名单< HashMap的<字符串,字符串>>的结果){

                字符串距离=;
                字符串duration_distance =;


                如果(result.size()&小于1){
                    Log.e(错误:,没有找到点);
                    返回;
                }


                的String [] date_dist =新的String [2];

                //通过遍历所有路线
                的for(int i = 0; I< result.size();我++){

                    //撷取第i路线
                    HashMap的<字符串,字符串> tmpdata伪= result.get(ⅰ);
                    设置<字符串>键= tmpData.keySet();
                    迭代它= key.iterator();
                    而(it.hasNext()){
                        字符串hmKey =(字符串)it.next();
                        duration_distance = tmpData.get(hmKey);

                        的System.out.println(键+ hmKey +&放大器;数据:+ duration_distance);

                        it.remove(); //避免了ConcurrentModificationException的
                    }

                    date_dist [我] = duration_distance;
                }

                mTaskListener.taskCompleted(date_dist);
            }
        }
    }
 

和DistanceTimeparser

 进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;

进口的java.util.ArrayList;
进口的java.util.HashMap;
进口的java.util.List;

公共类DistanceTimeParser {

    公开名单< HashMap的<字符串,字符串>>解析(JSONObject的jObject){


        名单< HashMap的<字符串,字符串>>路线=新的ArrayList< HashMap的<字符串,字符串>>();
        JSONArray jRoutes = NULL;
        JSONArray jLegs = NULL;

        JSONObject的jDistance = NULL;
        JSONObject的jDuration = NULL;

        尝试 {

            jRoutes = jObject.getJSONArray(路);

            jLegs =((的JSONObject)jRoutes.get(0))getJSONArray(腿)。

            名单< HashMap的<字符串,字符串>>路径=新的ArrayList< HashMap的<字符串,字符串>>();


            / **获取从JSON数据*距离/
            jDistance =((的JSONObject)jLegs.get(0))getJSONObject(距离)。
            HashMap的<字符串,字符串> hmDistance =新的HashMap<字符串,字符串>();
            hmDistance.put(距离,jDistance.getString(文本));

            / **获取时间由JSON数据* /
            jDuration =((的JSONObject)jLegs.get(0))getJSONObject(时间)。
            HashMap的<字符串,字符串> hmDuration =新的HashMap<字符串,字符串>();
            hmDuration.put(持续时间,jDuration.getString(文本));

            routes.add(hmDistance);

            routes.add(hmDuration);

        }赶上(JSONException E){
            e.printStackTrace();
        }赶上(例外五){
        }

        返回路线;
    }

}
 

I am using GoogleMapv2 api in my app. I want to draw a polygon line from source to destination. and show the travel time as well as distance on map activity but I am unable to find it. Please help me. My code snippet is here :

public class NavigationActivity extends FragmentActivity {
    public static final String TAG_SLAT = "sourcelat";
    public static final String TAG_SLONG = "sourcelong";
    public static final String TAG_DLAT = "destinationlat";
    public static final String TAG_DLONG = "destinationg";

    private static LatLng Source = null;
    private static LatLng Destination = null;

    private GoogleMap map;
    private SupportMapFragment fragment;
    private LatLngBounds latlngBounds;
    private Button bNavigation;
    private Polyline newPolyline;
    private Marker smarker;
    private  Marker dmarker;

    private boolean isTraveling = false;
    private int width, height;
    private String sourcelat;
    private String sourcelong;
    private String destinationg;
    private String destinationlat;
    double slat;
    double slong;
    double dlat;
    double dlong;
    TextView tvDistanceDuration;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation);
        tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);
        Intent in = getIntent();
        sourcelat = in.getStringExtra(TAG_SLAT);
        destinationlat = in.getStringExtra(TAG_DLAT);
        destinationg = in.getStringExtra(TAG_DLONG);
        sourcelong = in.getStringExtra(TAG_SLONG);


         slat=Double.parseDouble(sourcelat);
         slong=Double.parseDouble(sourcelong);
         dlat=Double.parseDouble(destinationlat);
         dlong=Double.parseDouble(destinationg);
        Source = new LatLng(slat,slong);
        Destination = new LatLng(dlat,dlong);

        getSreenDimanstions();
        fragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
        map = fragment.getMap();


                if (!isTraveling) {
                    isTraveling = true;


                    findDirections(Source.latitude, Source.longitude, Destination.latitude, Destination.longitude, GMapV2Direction.MODE_DRIVING);
                    DecimalFormat df1 = new DecimalFormat("#.0000");
                    double dLat = Math.toRadians(dlat - slat);
                    double dLon = Math.toRadians(dlong - slong);
                    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                            + Math.cos(Math.toRadians(slat))
                            * Math.cos(Math.toRadians(dlat)) * Math.sin(dLon / 2)
                            * Math.sin(dLon / 2);
                    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                    double tempDistance = 6371 * c;
                    Log.v("sds...", String.valueOf(tempDistance));
                } else {
                    isTraveling = false;

                }

    }

    @Override
    protected void onResume() {

        super.onResume();
        latlngBounds = createLatLngBoundsObject(Source, Destination);
        map.moveCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 150));

    }

    public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
        PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.RED);
        MarkerOptions marker = new MarkerOptions().position(Source).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        MarkerOptions marker1 = new MarkerOptions().position(Destination).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));


        for(int i = 0 ; i < directionPoints.size() ; i++)
        {          
            rectLine.add(directionPoints.get(i));


        }
        if (newPolyline != null)
        {
            newPolyline.remove();
        }
        newPolyline = map.addPolyline(rectLine);
        smarker = map.addMarker(marker);
        dmarker = map.addMarker(marker1);
        if (isTraveling)
        {

            latlngBounds = createLatLngBoundsObject(Source, Destination);
            map.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 150));
        }
        else
        {

            map.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 150));
        }

    }

    private void getSreenDimanstions()
    {
        Display display = getWindowManager().getDefaultDisplay();
        width = display.getWidth(); 
        height = display.getHeight(); 
    }

    private LatLngBounds createLatLngBoundsObject(LatLng firstLocation, LatLng secondLocation)
    {
        if (firstLocation != null && secondLocation != null)
        {
            LatLngBounds.Builder builder = new LatLngBounds.Builder();    
            builder.include(firstLocation).include(secondLocation);

            return builder.build();
        }
        return null;
    }


    public void findDirections(double fromPositionDoubleLat, double fromPositionDoubleLong, double toPositionDoubleLat, double toPositionDoubleLong, String mode)
    {
        Map<String, String> map = new HashMap<String, String>();
        map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT, String.valueOf(fromPositionDoubleLat));
        map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG, String.valueOf(fromPositionDoubleLong));
        map.put(GetDirectionsAsyncTask.DESTINATION_LAT, String.valueOf(toPositionDoubleLat));
        map.put(GetDirectionsAsyncTask.DESTINATION_LONG, String.valueOf(toPositionDoubleLong));
        map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode);

        GetDirectionsAsyncTask asyncTask = new GetDirectionsAsyncTask(this);
        asyncTask.execute(map);
    }
}

Asynctask class code as follow.........

public class GetDirectionsAsyncTask extends AsyncTask<Map<String, String>, Object, ArrayList<LatLng>>
{
    public static final String USER_CURRENT_LAT = "user_current_lat";
    public static final String USER_CURRENT_LONG = "user_current_long";
    public static final String DESTINATION_LAT = "destination_lat";
    public static final String DESTINATION_LONG = "destination_long";
    public static final String DIRECTIONS_MODE = "directions_mode";
    private NavigationActivity activity;
    private Exception exception;
    private ProgressDialog progressDialog;

    public GetDirectionsAsyncTask(NavigationActivity activity)
    {
        super();
        this.activity = activity;
    }

    public void onPreExecute()
    {
        progressDialog = new ProgressDialog(activity);
        progressDialog.setMessage("Calculating directions");
        progressDialog.show();
    }

    @Override
    public void onPostExecute(ArrayList result)
    {
        progressDialog.dismiss();
        if (exception == null)
        {
            activity.handleGetDirectionsResult(result);
        }
        else
        {
            processException();
        }
    }

    @Override
    protected ArrayList<LatLng> doInBackground(Map<String, String>... params)
    {
        Map<String, String> paramMap = params[0];
        try
        {
            LatLng fromPosition = new LatLng(Double.valueOf(paramMap.get(USER_CURRENT_LAT)) , Double.valueOf(paramMap.get(USER_CURRENT_LONG)));
            LatLng toPosition = new LatLng(Double.valueOf(paramMap.get(DESTINATION_LAT)) , Double.valueOf(paramMap.get(DESTINATION_LONG)));
            GMapV2Direction md = new GMapV2Direction();
            Document doc = md.getDocument(fromPosition, toPosition, paramMap.get(DIRECTIONS_MODE));
            ArrayList<LatLng> directionPoints = md.getDirection(doc);
            return directionPoints;
        }
        catch (Exception e)
        {
            exception = e;
            return null;
        }
    }

    private void processException()
    {
        Toast.makeText(activity, "Error retrieving data",Toast.LENGTH_SHORT).show();
    }
}

and class for get direction is as follow :

public class GMapV2Direction {
    public final static String MODE_DRIVING = "driving";
    public final static String MODE_WALKING = "walking";

    public GMapV2Direction() { }

    public Document getDocument(LatLng start, LatLng end, String mode) {
        String url = "http://maps.googleapis.com/maps/api/directions/xml?" 
                + "origin=" + start.latitude + "," + start.longitude  
                + "&destination=" + end.latitude + "," + end.longitude 
                + "&sensor=false&units=metric&mode=driving";

        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse response = httpClient.execute(httpPost, localContext);
            InputStream in = response.getEntity().getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(in);
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getDurationText (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        Log.i("DurationText", node2.getTextContent());
        return node2.getTextContent();
    }

    public int getDurationValue (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        Log.i("DurationValue", node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String getDistanceText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        int i;

        //get the last tag from XML

        for(i = 0;i<nl1.getLength();i++){

        }

        if(i==i){
            i--;
        }

        Node node1 = nl1.item(i);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        Log.i("DistanceText", node2.getTextContent());
        return node2.getTextContent();
    }

    public int getDistanceValue (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        Log.i("DistanceValue", node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String getStartAddress (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("start_address");
        Node node1 = nl1.item(0);
        Log.i("StartAddress", node1.getTextContent());
        return node1.getTextContent();
    }

    public String getEndAddress (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("end_address");
        Node node1 = nl1.item(0);
        Log.i("StartAddress", node1.getTextContent());
        return node1.getTextContent();
    }

    public String getCopyRights (Document doc) {
        NodeList nl1 = doc.getElementsByTagName("copyrights");
        Node node1 = nl1.item(0);
        Log.i("CopyRights", node1.getTextContent());
        return node1.getTextContent();
    }

    public ArrayList<LatLng> getDirection (Document doc) {
        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));

                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));
                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
                for(int j = 0 ; j < arr.size() ; j++) {
                    listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
                }

                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "lat"));
                lat = Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    private int getNodeIndex(NodeList nl, String nodename) {
        for(int i = 0 ; i < nl.getLength() ; i++) {
            if(nl.item(i).getNodeName().equals(nodename))
                return i;
        }
        return -1;
    }

    private ArrayList<LatLng> decodePoly(String encoded) {
        ArrayList<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;
    }

解决方案

You can get Trvelling time and distance with following code.. i have already use this code in one of my project hope this will help you

CalculateDistanceTime distance_task = new CalculateDistanceTime(getActivity());

distance_task.getDirectionsUrl(startLatLng, endLatLng);

distance_task.setLoadListener(new CalculateDistanceTime.taskCompleteListener() {
           @Override
           public void taskCompleted(String[] time_distance) {
                   approximate_time.setText("" + time_distance[1]);
                   approximate_diatance.setText("" + time_distance[0]);
           }

 });

and here is the CalculateDistanceTime class.

    import android.content.Context;
    import android.os.AsyncTask;
    import android.util.Log;

    import com.google.android.gms.maps.model.LatLng;

    import org.json.JSONObject;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;

    public class CalculateDistanceTime {

        private taskCompleteListener mTaskListener;
        private Context mContext;


        public CalculateDistanceTime(Context context) {
            mContext = context;
        }

        public void setLoadListener(taskCompleteListener taskListener) {
            mTaskListener = taskListener;
        }


        public void 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";

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

            // Output format
            String output = "json";

            // Building the url to the web service
            String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;


            DownloadTask downloadTask = new DownloadTask();

            // Start downloading json data from Google Directions API

            downloadTask.execute(url);
        }

        private String downloadUrl(String strUrl) throws IOException {
            String data = "";
            InputStream iStream = null;
            HttpURLConnection urlConnection = null;
            try {
                URL url = new URL(strUrl);

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


        public interface taskCompleteListener {
            void taskCompleted(String[] time_distance);
        }

        private class DownloadTask extends AsyncTask<String, Void, String> {

            // Downloading data in non-ui thread
            @Override
            protected String doInBackground(String... url) {

                // For storing data from web service
                String data = "";

                try {
                    // Fetching the data from web service
                    data = downloadUrl(url[0]);
                } catch (Exception e) {
                    Log.d("Background Task", e.toString());
                }
                return data;
            }

            // Executes in UI thread, after the execution of
            // doInBackground()
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                ParserTask parserTask = new ParserTask();

                // Invokes the thread for parsing the JSON data
                parserTask.execute(result);

            }
        }

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

            // Parsing the data in non-ui thread
            @Override
            protected List<HashMap<String, String>> doInBackground(String... jsonData) {

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

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

                    // Starts parsing data
                    routes = parser.parse(jObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return routes;
            }

            // Executes in UI thread, after the parsing process
            @Override
            protected void onPostExecute(List<HashMap<String, String>> result) {

                String distance = "";
                String duration_distance = "";


                if (result.size() < 1) {
                    Log.e("Error : ", "No Points found");
                    return;
                }


                String[] date_dist = new String[2];

                // Traversing through all the routes
                for (int i = 0; i < result.size(); i++) {

                    // Fetching i-th route
                    HashMap<String, String> tmpData = result.get(i);
                    Set<String> key = tmpData.keySet();
                    Iterator it = key.iterator();
                    while (it.hasNext()) {
                        String hmKey = (String) it.next();
                        duration_distance = tmpData.get(hmKey);

                        System.out.println("Key: " + hmKey + " & Data: " + duration_distance);

                        it.remove(); // avoids a ConcurrentModificationException
                    }

                    date_dist[i] = duration_distance;
                }

                mTaskListener.taskCompleted(date_dist);
            }
        }
    }

and DistanceTimeparser

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DistanceTimeParser {

    public List<HashMap<String, String>> parse(JSONObject jObject) {


        List<HashMap<String, String>> routes = new ArrayList<HashMap<String, String>>();
        JSONArray jRoutes = null;
        JSONArray jLegs = null;

        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            jLegs = ((JSONObject) jRoutes.get(0)).getJSONArray("legs");

            List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();


            /** Getting distance from the json data */
            jDistance = ((JSONObject) jLegs.get(0)).getJSONObject("distance");
            HashMap<String, String> hmDistance = new HashMap<String, String>();
            hmDistance.put("distance", jDistance.getString("text"));

            /** Getting duration from the json data */
            jDuration = ((JSONObject) jLegs.get(0)).getJSONObject("duration");
            HashMap<String, String> hmDuration = new HashMap<String, String>();
            hmDuration.put("duration", jDuration.getString("text"));

            routes.add(hmDistance);

            routes.add(hmDuration);

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

        return routes;
    }

}

这篇关于如何获得驱动两个位置之间的距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆