android - 如何在 android 的谷歌地图中选择不同的路线?

标签 android google-maps-android-api-2 google-directions-api

我正在开发一个使用大量谷歌地图交互的应用程序。在一项 Activity 中,我展示了两点之间的路线。我希望这些路线可以选择,根据用户的选择显示请帮助我。 我在这里附上 Activity 的图片:As you can see the paths

这是上面显示的 Activity 的代码:

public class RouteActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
double sl1,sl2,el1,el2;
FrameLayout fl;
TextView distTextView,timeTextView;
String routeArray[];
List<LatLng> list;
List<Polyline> polylineList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_route);
    setUpMapIfNeeded();
    mMap.getUiSettings().setZoomControlsEnabled(true);
    polylineList=new ArrayList<Polyline>();
    fl=(FrameLayout)findViewById(R.id.frame_layout);
    distTextView=(TextView)findViewById(R.id.distance_textView);
    timeTextView=(TextView)findViewById(R.id.time_textView);
    String start = getIntent().getStringExtra("start");
    String end = getIntent().getStringExtra("end");
    Geocoder coder = new Geocoder(this);
    List<Address> address;
    try {
        address = coder.getFromLocationName(start, 5);
        if (address == null) {
        }
        Address location = address.get(0);
         sl1=location.getLatitude();
         sl2=location.getLongitude();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        address = coder.getFromLocationName(end, 5);
        if (address == null) {
        }
        Address location = address.get(0);
        el1=location.getLatitude();
        el2=location.getLongitude();
    } catch (IOException e) {
        e.printStackTrace();
    }

    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.from);
    markers[0]=mMap.addMarker(new MarkerOptions().position(new LatLng(sl1, sl2)).title(start).icon(icon));
    markers[1]=mMap.addMarker(new MarkerOptions().position(new LatLng(el1, el2)).title(end).icon(icon));
    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (Marker marker : markers) {
        builder.include(marker.getPosition());
    }
    LatLngBounds bounds = builder.build();

    CameraUpdate cu=CameraUpdateFactory.newLatLngBounds(bounds,500,500,0);
    mMap.moveCamera(cu);
    mMap.animateCamera(cu);
    String url=makeURL(sl1,sl2,el1,el2);
    Log.e("Generated URL ",url);
    new MyAsyncTask().execute(url);
    fl.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });
    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            int x=0;
            for (Polyline polyline : polylineList)
            {
                for (LatLng polyCoords : polyline.getPoints()) {
                    float[] results = new float[1];
                    Location.distanceBetween(latLng.latitude, latLng.longitude,
                            polyCoords.latitude, polyCoords.longitude, results);


                    if (results[0] < 100) {
                        mMap.clear();
                        for(Polyline pl:polylineList)
                        {
                            if(pl!=polyline) {
                                mMap.addPolyline(new PolylineOptions().color(Color.GRAY).addAll(pl.getPoints()));
                                }
                            else if(pl==polyline)
                            {
                                mMap.addPolyline(new PolylineOptions()
                                        .color(Color.BLUE)
                                        .addAll(pl.getPoints()));
                            }
                        }





                    }


                }

            }
            Log.e("PolyLine ",polylineList.toString());



        }
    });


}

    @Override
protected void onResume() {
    super.onResume();

}

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

public class MyAsyncTask extends AsyncTask<String,Void,String> {
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        progressDialog=new ProgressDialog(RouteActivity.this);
        progressDialog.setMessage("Finding Route ...");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(false);

        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... str) {
        ParserClass parser = new ParserClass();
        String json_str = parser.getJSON(str[0], 2000);
        Log.e("JSON Data", json_str);
        return json_str;
    }

    @Override
    protected void onPostExecute(String s) {
        try {
            progressDialog.dismiss();
            JSONObject  jsonRootObject = new JSONObject(s);
            JSONArray routeArray=jsonRootObject.getJSONArray("routes");
            Log.e("ROUTES ",routeArray.toString());
            for(int i=routeArray.length()-1;i>=0;i--) {
                JSONObject routes = routeArray.getJSONObject(i);
                JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
                JSONArray legs=routes.getJSONArray("legs");
                for(int j=0;j<legs.length();j++)
                {
                    JSONObject distObj=legs.getJSONObject(j);
                    JSONObject distance =distObj.getJSONObject("distance");
                    String dist=distance.getString("text");
                    JSONObject duration=distObj.getJSONObject("duration");
                    String time=duration.getString("text");
                    Log.e("Route"+i+" DISTANCE ",dist);
                    Log.e("Route"+i+" TIME ",time);
                    distTextView.setText("Distance   "+dist);
                    timeTextView.setText("Time    "+time);
                }
                String encodedString = overviewPolylines.getString("points");
                Log.e("Waypoint "+i,encodedString);
                 list = decodePoly(encodedString);
                Log.e("List "+i,list.toString());
                if(i==0) {
                    Polyline line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(12)
                                    .color(Color.BLUE)
                                    .geodesic(true)
                            );
                    Log.e("PolyLine ",line.toString());
                    polylineList.add(line);
                }
                else{
                    Polyline line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(12)
                                    .color(Color.DKGRAY)
                                    .geodesic(true)
                    );
                    polylineList.add(line);



                    Log.e("PolyLine ",line.toString());

                    }

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

        super.onPostExecute(s);
    }
}

private void setUpMap() {
    mMap.clear();
}
public void showMap(Double l1,Double l2,String str)
{
    LatLng position=new LatLng(l1,l2);
    SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
    GoogleMap googleMap = fm.getMap();
    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.from);
    mMap.addMarker(new MarkerOptions().position(new LatLng(l1, l2)).title(str).icon(icon));
    CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);
    CameraUpdate updateZoom=CameraUpdateFactory.zoomTo(15);
    googleMap.moveCamera(updatePosition);
    googleMap.animateCamera(updateZoom);
}
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
    StringBuilder urlString = new StringBuilder();
    urlString.append("https://maps.googleapis.com/maps/api/directions/json");
    urlString.append("?origin=");// from
    urlString.append(Double.toString(sourcelat));
    urlString.append(",");
    urlString.append(Double.toString( sourcelog));
    urlString.append("&destination=");// to
    urlString.append(Double.toString( destlat));
    urlString.append(",");
    urlString.append(Double.toString( destlog));
    urlString.append("&sensor=false&mode=driving&alternatives=true&units=imperial");
    urlString.append("&key=AIzaSyD5NOOpYKObjlZbt_-4CUOMi14mObzbGNo");
    return urlString.toString();
}

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

在 abouce 代码中,我使用 google directions api 创建了这些路径

请帮助选择不同的路线。谢谢

最佳答案

伙计们,我已经实现了所需的功能,只是对现有代码进行了一些更改,现在可以正常工作了。感谢您的指导:)

关于android - 如何在 android 的谷歌地图中选择不同的路线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32971366/

相关文章:

android - Dagger 2 @Component.Builder 依赖项缺少 setter 错误

android - 发现 vs-android 不适合 java

Android 谷歌地图版本 2 显示方向和谷歌地图图标

java - 删除 Google map 上之前的方向路线

java - 从服务器获取数据

android - 是否可以在 slider View 上设置 GIF 图像(有四种布局)

java - 访问 map 中MyLocation蓝点的可绘制资源

android - 动画在 Google Map Android 上不起作用

geolocation - 如何避开 Google Directions API 中的限制收费站和高速公路?

android - { "error_message": "You must enable Billing on the Google Cloud Project }