简体   繁体   中英

Android Google Maps Driving Direction

I'm developing an android Google maps in my thesis, can i ask something about Driving Directions in Android?.

Here is my question.

"How can i generate a random driving directions in android Google maps when a button is clicked, it will randomly give the path from starting point to destination point."

Thank you!.

I asked google maps through this.

    private void parsing(GeoPoint start, GeoPoint end) throws ClientProtocolException, IOException, JSONException, URISyntaxException{
    HttpClient httpclient = new DefaultHttpClient();
    StringBuilder urlstring = new StringBuilder();
    urlstring.append("https://maps.googleapis.com/maps/api/directions/json?origin=")
    .append(Double.toString((double)start.getLatitudeE6()/1E6)).append(",").append(Double.toString((double)start.getLongitudeE6()/1E6)).append("&destination=")
    .append(Double.toString((double)end.getLatitudeE6()/1E6)).append(",").append(Double.toString((double)end.getLongitudeE6()/1E6))
    .append("&sensor=false");
    //urlstring.append("http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=true");
    url = new URI(urlstring.toString());

    HttpPost httppost = new HttpPost(url);

    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    InputStream is = null;
    is = entity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    sb.append(reader.readLine() + "\n");
    String line = "0";
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    reader.close();
    String result = sb.toString();
    JSONObject jsonObject = new JSONObject(result);
    JSONArray routeArray = jsonObject.getJSONArray("routes");
    JSONObject routes = routeArray.getJSONObject(0);
    JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
    String encodedString = overviewPolylines.getString("points");
    List<GeoPoint> pointToDraw = decodePoly(encodedString);

    //Added line:
    mv_mapview.getOverlays().add(new RoutePathOverlay(pointToDraw));
}

Tapped on the map.

    class MapOverlay extends Overlay {

        @Override
        public boolean onTap(final GeoPoint p, MapView mapView) {
            // TODO Auto-generated method stub

            geop_Tpoint = p;
            mcon_mapcontrol = mapView.getController();
            mcon_mapcontrol.animateTo(p);

            mv_mapview.invalidate();

            longitude = (int)(p.getLongitudeE6()*1E6);
            latitude = (int)(p.getLatitudeE6()*1E6);



            new AlertDialog.Builder(ShowMap.this)
                    .setTitle("Routes")
                    .setMessage("Display Routes?")
                    .setNegativeButton("NO",
                            new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // TODO Auto-generated method stub

                                    textlocation.setText("Tap in the Map for Destination!");
                                    dialog.dismiss();


                                }
                            })
                    .setPositiveButton("YES",
                            new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // TODO Auto-generated method stub
                                    try{
                                        textlocation.setText("");
                                        parsing(geop_startpoint,geop_Tpoint);
                                        geocodeExecuter(geop_startpoint,geop_Tpoint);
                                        showButton.setEnabled(true);


                                    }catch(Exception e){

                                        textlocation.setText(""+ e.getMessage());

                                    }


                                }

                            }).show();
            showButton.setEnabled(true);
            return true;
        }

The starting point is through GPS it will give me where im I.

This will help u in getting directions from A to B point.

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=" + startLatitude + "," + startLongitude + "&daddr=" + destlat + "," + destlon));
startActivity(intent);

It depends on how do you ask directions to google maps. If you create an intent using the link tat specifies source and destination, you may try to call something like this:

https://maps.google.com/maps?saddr=START_POINT&daddr=MIDDLE_POINT+to:DESTINATION_POINT

This also accepts GPS coordinates, so you can also call something like this:

https://maps.google.com/maps?saddr=START_POINT&daddr=XX.YYYYY,WW.ZZZZZ+to:DESTINATION_POINT

If start and destination are fixed, you might try to do something like this:

  • Get GPS Coordinates for your start point
  • Get GPS Coordinates for your destination
  • Generate a couple of coordinates (XY) that do not exceed the rectangle defined by source and destination

This should generate a random point somewhere between A and B.

Google Maps is smart enough to choose the point closest to a road to generate the directions if you place your middle point in the middle of a corn field or something similar.


UPDATE: After reading the code: I think that the quickest way to achieve your result is to find GPS Locations for A and B, then generate a random point between the two and make 2 calls: A-RandomPoint B-RandomPoint.

The total distance will be the sum of AR trip and RB trip, same for the time.

About the calculation of the middle point: First: set the bounds. If you want to calculate X: take X of point A and X of point B. At this point: minX will be the lowest and maxX will be the highest (you might want to think carefully of what you are doing if your points are near greenwitch). Now generate a random float between your max and min. This is a trivial task and there are a ton of results for that. Just an example: How do I generate random integers within a specific range in Java?

This is how i convert it in Java.

    public List<GeoPoint> findCoordinatesInACircle(double lat, double longi,double radius){



        double newLat;
        double newLong;

        List<GeoPoint> searchpoints = new ArrayList<GeoPoint>();


        double rLat=(radius/6371)*(180/Math.PI);  
        double rLon= rLat/Math.cos(longi * (Math.PI/180));

        for(int i =0 ; i < 181; i++ ){

            double iRad = i*(Math.PI/180);
            newLat = lat + (rLat * Math.sin(iRad));
            newLong = longi + (rLon * Math.cos(iRad));

            GeoPoint onePoint = new GeoPoint((int)(float)(newLat),(int)(float)(newLong));

            if(i%pointInterval == 0){
                searchpoints.add(onePoint); 
            }

        }
        return searchpoints;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM