如何从我的位置到任何标记的行车路线

时间:2014-06-23 11:22:31

标签: android google-maps-markers google-maps-android-api-2 google-maps-api-2 android-maps-v2

我是编程的初学者。 我得到了从我的位置到目的地的教程。但是这些教程并不是我想要的。

链接教程: http://wptrafficanalyzer.in/blog/driving-route-from-my-location-to-destination-in-google-maps-android-api-v2/

问题是我如何从我的位置获得一条行车路线到我的自定义标记。

GoogleMap map;
ArrayList<LatLng> mMarkerPoints;
double mLatitude=0;
double mLongitude=0;
TextView tvDistanceDuration;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.maps);

    tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    }else { // Google Play Services are available

        // Initializing
        mMarkerPoints = new ArrayList<LatLng>();

        // Getting reference to SupportMapFragment of the activity_main
        SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting Map for the SupportMapFragment
        map = fm.getMap();

        // Enable MyLocation Button in the Map
        map.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location From GPS
        Location location = locationManager.getLastKnownLocation(provider);

        if(location!=null){
            onLocationChanged(location);
        }

        locationManager.requestLocationUpdates(provider, 20000, 0, this);

        // Setting onclick event listener for the map
        map.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {

                // Already map contain destination location
                if(mMarkerPoints.size()>=1){

                    FragmentManager fm = getSupportFragmentManager();
                    mMarkerPoints.clear();
                    map.clear();
                    LatLng startPoint = new LatLng(mLatitude, mLongitude);

                    // draw the marker at the current position
                    drawMarker(startPoint);
                }

                // draws the marker at the currently touched location
                drawMarker(mMarkerPoints.get(1));

                // Checks, whether start and end locations are captured
                if(mMarkerPoints.size() >= 1){
                    LatLng origin = mMarkerPoints.get(0);
                    LatLng dest = mMarkerPoints.get(1);

                    // Getting URL to the Google Directions API
                    String url = getDirectionsUrl(origin, dest);

                    DownloadTask downloadTask = new DownloadTask();

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

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

/** A class to download data from Google Directions URL */
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);
    }
}

/** A class to parse the Google Directions in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{

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

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

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

            // 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<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = null;
        PolylineOptions lineOptions = null;
        MarkerOptions markerOptions = new MarkerOptions();
        String distance = "";
        String duration = "";

        if(result.size()<1){
            Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
            return;
        }

        // Traversing through all the routes
        for(int i=0;i<result.size();i++){
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // 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){    // Get distance from the list
                    distance = (String)point.get("distance");
                    continue;
                }else if(j==1){ // Get duration from the list
                    duration = (String)point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(2);
            lineOptions.color(Color.RED);
        }

        tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);

        // Drawing polyline in the Google Map for the i-th route
        map.addPolyline(lineOptions);
    }
}


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

private void drawMarker(LatLng point){
    mMarkerPoints.add(point);

    // Creating MarkerOptions
    MarkerOptions options = new MarkerOptions();

    // Setting the position of the marker
    options.position(point);

    /**
    * For the start location, the color of marker is GREEN and
    * for the end location, the color of marker is RED.
    */

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
    .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.381407, 106.855766))
    .title("PT. Andalan Sumber Rezeki").snippet("Jln. Ir. H. Juanda, Kp. Bojong RT. 03/06 Kel. Batik Jaya <br/> Kec. Sukma Jaya DEPOK <br/> Phone : 0813 814 77771"));

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
    .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.361964, 106.775808))
    .title("PT. Solia Mitra Motor").snippet("Jln. Limo Raya No.5 Cinere Depok <br/> Phone : 0217540506"));

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
    .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.3845335,106.8285415))
    .title("Mahkota Depok")
    .snippet("Jln. Raya Margonda No.209  <br/> Phone : 02177210208"));

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
    .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.111662, 106.911759))

    .title("Mahkota Arif Rahman Hakim").snippet("Jln. Arif Rahman Hakim No.78 <br/> phone : 02177202260"));

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
    .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.451293, 106.798896))
    .title("PT.Suzuki Citayam").snippet("Jln. Pabuaran Raya No.44-46 Kampung Pintu Air Pabuaran <br/> phone : 02187990951"));

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
    .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.383348, 106.814409))
    .title("PT. Singgalang Motor").snippet("Jln. Nusantara Raya Depok <br/> phone : 021 77212827"));

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
    .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.401883, 106.836572))
    .title("PT. Galaxy Prima Depok").snippet("Jln. Kemakmuran Raya No.50 <br/> phone : 02177825282"));

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
        .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.3901018,106.8268545))
    .title("PT. Suzuki SEM Depok").snippet("Jln. Margonda Raya No.27 <br/> phone : 0217764887"));

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
    .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.391512, 106.851940))
    .title("Suzuki DIPA Motor").snippet("<p>" +"Jln. Kejayaan Raya" + "<br/> " + "phone : 021 77831015"));

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
    .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.3901018,106.8268545))
    .title("PT. Tugu Gema Motorindo").snippet("Jln. Akses UI No. 25 <br/> phone : (021) 8701111, (021) 8702222"));

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
    .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.3590335,106.8586754))
    .title("PT. Restu Mahkota Karya").snippet("Jl. Raya Bogor Km,29 No.18 Cimanggis <br/> phone : 021 87708918"));

    map.addMarker(new MarkerOptions()
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
    .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
    .position(new LatLng(-6.3779722,106.8650424))
    .title("Suzuki Cisalak").snippet("Jalan Raya Bogor KM.31 <br/> phone : 021 8722624"));
}

@Override
public void onLocationChanged(Location location) {
    // Draw the marker, if destination location is not set
    if(mMarkerPoints.size() < 2){

        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng point = new LatLng(mLatitude, mLongitude);

        map.moveCamera(CameraUpdateFactory.newLatLng(point));
        map.animateCamera(CameraUpdateFactory.zoomTo(12));

        drawMarker(point);
    }
}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}
}      

感谢

2 个答案:

答案 0 :(得分:1)

请尝试这种方式,希望这有助于您解决问题。

String uri = "http://maps.google.com/maps?f=d&hl=es&saddr="+startingLatitude+","+startingLongitude+"&daddr="+endingLatitude+","+endingLongitude;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);

答案 1 :(得分:1)

您可以使用以下网址以JSON格式从Google获取路线:

http://maps.googleapis.com/maps/api/directions/json?origin=startLatLng&destination=endLatLng&sensor=false&mode=driving&alternatives=false

private static ArrayList<LatLng> getRoutePoints(String url) {
        JSONObject dirJson = Json.getJson(url);
        if (dirJson != null) {
            try {
                ArrayList<LatLng> routeLine = decodeOverviewPolyline(dirJson
                        .getJSONArray("routes").getJSONObject(0)
                        .getJSONObject("overview_polyline").getString("points"));
                if (routeLine != null & routeLine.size() > 0)
                    return routeLine;
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }


private static ArrayList<LatLng> decodeOverviewPolyline(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 p = new LatLng((double) lat / 1E5, (double) lng / 1E5);
            poly.add(p);
        }
        return poly;

    }

修改

按照步骤显示从您所在位置(GPS)到点击标记的行车路线。

  1. 获取当前位置LatLng

  2. 在标记的点击事件中,调用以startLatLng作为当前位置的网址,并将endLatLng作为标记位置(注意:在{ {1}}以避免AsyncTask例外。

  3. 使用NetworkOnMainThread方法返回的ArrayList LatLng在地图上绘制路线。