当前位置: 首页 > 知识库问答 >
问题:

Google Map API v2-获取从当前位置到已知位置的行驶距离

曾苗宣
2023-03-14
public class Locations extends Fragment {

private Location currentLocation = null;
private LocationManager locationManager;
private GeoPoint currentPoint;

TextView location1;

ArrayList<LatLng> markerPoints;
GoogleMap map;

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

    getLastLocation();
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_locations, container, false);
    ...some other stuff being done here...
    // Return view
    return view;
}

public void getLastLocation(){
    String provider = getBestProvider();
    currentLocation = locationManager.getLastKnownLocation(provider);

    this.markerPoints = new ArrayList<LatLng>();

    LatLng fromPosition = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
    LatLng toPosition = new LatLng(29.633289, -82.305838);
    // These are the other 3 end locations
    LatLng toPosition1 = new LatLng(35.205374, -82.614587);
    LatLng toPosition2 = new LatLng(35.405342, -82.316587);
    LatLng toPosition3 = new LatLng(35.702354, -82.515837);

    Locations.this.markerPoints.add(fromPosition);
    Locations.this.markerPoints.add(toPosition);

    // Getting URL to the Google Directions API
    String url = Locations.this.getDirectionsUrl(fromPosition, toPosition);

    DownloadTask downloadTask = new DownloadTask();

    // Start downloading json data from Google Directions API
    downloadTask.execute(url);

    if(currentLocation != null) {
        setCurrentLocation(currentLocation);
    } else { 
        // do something
    }
}

public String getBestProvider() {
    locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
    criteria.setAccuracy(Criteria.NO_REQUIREMENT);
    String bestProvider = locationManager.getBestProvider(criteria, true);
    return bestProvider;
}

public void setCurrentLocation(Location location){
    // Get current location
    int currLatitude = (int) (location.getLatitude()*1E6);
    int currLongitude = (int) (location.getLongitude()*1E6);
    currentPoint = new GeoPoint(currLatitude,currLongitude); 
    // Set current location
    currentLocation = new Location("");
    currentLocation.setLatitude(currentPoint.getLatitudeE6() / 1e6);
    currentLocation.setLongitude(currentPoint.getLongitudeE6() / 1e6);
}

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

    return url;
}

/** A method to download json data from 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;
}

// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>> {
    @Override
    protected ArrayList<String> doInBackground(String... urlList) {
        try {
            ArrayList<String> returnList = new ArrayList<String>();
            for (String url : urlList) {
                // Fetching the data from web service
                String data = Locations.this.downloadUrl(url);
                returnList.add(data);
            }
            return returnList;
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
            return null; // Failed, return null
        }
    }

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

        ParserTask parserTask = new ParserTask();

        for (String url : results) {
            parserTask.execute(url);
        }

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

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, ArrayList<List<HashMap<String, String>>>> {
    // Parsing the data in non-ui thread
    @Override
    protected ArrayList<List<HashMap<String, String>>> doInBackground(String... jsonData) {
        try {
            ArrayList<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();

            // for (String url : jsonData) {
            for (int i = 0; i < jsonData.length; i++) {
                JSONObject jObject = new JSONObject(jsonData[i]);

                DirectionsJSONParser parser = new DirectionsJSONParser();
                // Starts parsing data
                routes = (ArrayList<List<HashMap<String, String>>>) parser.parse(jObject);
            }
            return routes;
        } catch (Exception e) {
            Log.d("Background task", e.toString());
            return null; // Failed, return null
        }
    }

    // Executes in UI thread, after the parsing process
    @Override
    protected void onPostExecute(ArrayList<List<HashMap<String, String>>> result) {
        if (result.size() < 1) {
            Toast.makeText(getActivity(), "No Points", Toast.LENGTH_LONG).show();
            return;
        }

        TextView tv1 = (TextView) getActivity().findViewById(R.id.location1);
        TextView tv2 = (TextView) getActivity().findViewById(R.id.location2);
        TextView tv3 = (TextView) getActivity().findViewById(R.id.location3);
        TextView tv4 = (TextView) getActivity().findViewById(R.id.location4);

        TextView[] views = { tv1, tv2, tv3, tv4 };

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);
            String distance = "No distance";

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {
                    distance = point.get("distance");
                    continue;
                }
            }

            Log.d("Distance: ", distance);

            // Set text
            views[i].setText(distance);
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/location1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/location2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="TextView" />
    <TextView
        android:id="@+id/location3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="TextView" />
    <TextView
        android:id="@+id/location4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="TextView" />
</LinearLayout>
</RelativeLayout>

共有1个答案

万高洁
2023-03-14

以下是现有代码的更新:

// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result)  
{
    if (result.size() < 1) 
    {
        Toast.makeText(getActivity(), "No Points", Toast.LENGTH_SHORT).show();
        return;
    }

    TextView tv1 = (TextView) getActivity().findViewById(R.id.location1);
    TextView tv2 = (TextView) getActivity().findViewById(R.id.location2);
    TextView tv3 = (TextView) getActivity().findViewById(R.id.location3);
    TextView tv4 = (TextView) getActivity().findViewById(R.id.location4);

    TextView[] views = {tv1, tv2, tv3, tv4};


    // Traversing through all the routes
    for (int i = 0; i < result.size(); i++) 
    {
        // Fetching i-th route
        List<HashMap<String, String>> path = result.get(i);
        String distance = "No distance";

        // Fetching all the points in i-th route
        for (int j = 0; j < path.size(); j++) 
        {
            HashMap<String, String> point = path.get(j);

            if (j == 0)  
            {
                distance = point.get("distance");
                continue;
            }
        }

        // Set text
        views[i].setText(distance);
    }
}

这段代码做了一个不太好的假设:它假设result的大小与views相同,在您的例子中应该是4。在运行此代码时,如果有超过4个结果,则可能会出现indexoutofbounds错误(这是不应该发生的)。最终,您需要验证result的大小是否为4,或者textview的数量是否为。如果你有任何问题或这不是正确的,请让我知道:)

编辑:要同时获得所有距离,可以修改DownloadTask以接收多个URL。

更改类定义:

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

这表明您的后台操作将返回字符串的列表。

修改了doinbackground(),现在可以处理多个URL:

// Downloading data in non-ui thread
@Override
protected ArrayList<String> doInBackground(String... urlList) 
{
    try 
    {
        ArrayList<String> returnList = new ArrayList<String>();
        for(String url : urlList)
        {
            // Fetching the data from web service
            String data = Locations.this.downloadUrl(url);
            returnList.add(data);
        }

        return returnList;
    } 
    catch (Exception e) 
    {
        Log.d("Background Task", e.toString());
        return null; // Failed, return null
    }
}
// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(ArrayList<String> results) 
{
    super.onPostExecute(results);

    ParserTask parserTask = new ParserTask();

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

}

编辑两个:在getlastlocation()中,您只使用一个URL调用downloadtask,但是您应该放置四个URL,类似于downloadtask.execute(url1,url2,url3,url4)。另外,由于ParserTask仍然只处理一个JSON字符串,因此应该从onPostExecute()中取出四个TextView和数组循环。要告诉ParserTask要填充哪个TextView,请向ParserTask添加一个构造函数,该构造函数接受TextView作为参数。然后在ParserTask中创建一个实例变量,该变量在构造函数中赋值,并在onPostExecute()中使用,以显示距离。

然后,将我之前给出的TextView数组内容放在DownloadTaskonPostExecute()中。在遍历字符串结果时,也要遍历TextView数组,并在ParserTask构造函数中传入TextView

基本上,您要在ParserTask中添加一个构造函数来告诉它要在哪个TextView上绘制。当DownloadTask完成时,将为URL传递正确的TextView。例如,第三个URL的r.id.location3

 类似资料:
  • 我意识到这个问题以前被问过很多次,但我现在问这个问题是因为答案很旧(与新的API相比)。 我以前使用过Location Manager,但我发现它非常不可靠。例如,在我的应用程序中,使用getLastKnownLocation和/或current location,它会立即将相机加载到用户的当前位置。但是,如果我在启动应用程序之前打开设备上的位置,它就不会把摄像头放在用户的当前位置,而是放在Nig

  • 问题内容: 我在这个项目中使用该类。在我的地图上,您可以看到许多标记。我有许多已知的位置,但是在我的代码中,例如,我仅显示两个位置。 我不明白如何使用方向API和JSON。如何显示从当前位置(更改)到已知位置(恒定)的路线,距离和行进时间? 问题答案: 看一下本教程: 使用Google Map Android API V2中的Google Directions在两个位置之间绘制行车路线 它显示了如

  • 求一个vue单页面或者H5 对接任意地图的API 获取当前位置 输入结束位置 并测算公里距离的dome 类似这样的

  • 问题内容: 嗨,我写了一个应用程序,获取当前的纬度和经度并将其转换为相应的地址。我可以获取纬度和经度,但是如何使用json将其转换为相应的地址。我是json的新手。我尝试了一些示例代码,但没有得到地址 这是我的代码 请帮助我 提前致谢 问题答案: 要改回可读格式,您也可以使用Geocoder,但有时由于Google Play服务问题而无法正常工作。我将这个json地理编码用作第二种选择,以防万一。

  • 问题内容: 我正在尝试通过GPS功能获取用户的当前位置, 编写了一个实现的简单类 通过一个简单的动作,我正在访问这些经度和纬度值 但是它总是返回0.0作为结果。无法找出问题所在。 问题答案: 您必须在onCreate()返回之后才能触发您的位置更新回调。如果您将经纬度变量初始化为虚拟值,则可能会看到您正在打印这些值。 在onLocationChanged中添加一些日志记录,以便可以看到它已被触发,

  • 问题内容: 我正在同时学习ARKit和Scenekit,这是一个挑战。 创建了ARWorldTrackingSessionConfiguration会话后,我想知道是否有人知道一种在场景会话中获取用户“相机”位置的方法。我的想法是要向用户的当前位置设置对象的动画。 但是,即使我四处移动相机,currentCameraPosition似乎始终为[0,0,0]。知道我在做什么错吗?最终的想法是,我将围