如何移动地图标记,如移动汽车在道路上从源到目的地

时间:2017-06-09 19:11:16

标签: android-maps

我想将Google地图上的标记从源头移动到目的地,如Uber或Ola,我正在使用谷歌地图,我是新手,请帮助我如何实现......?

我的代码是:

public void onMapReady(GoogleMap googleMap){

    GoogleMap gMap = googleMap;


    addMarks1(gMap);
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    gMap.setMyLocationEnabled(true);

    gMap.getUiSettings().setZoomControlsEnabled(true);

    // Turns on 3D buildings
    gMap.setBuildingsEnabled(true);


}


private void addMarks1(GoogleMap googleMap) {
    googleMap.clear();
    //  updateRouteOnMAp();
    double d_lat=Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LAT));
    double d_loing=Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LNG));
    fromPosition=new LatLng(d_lat,d_loing);

    toPosition=new LatLng(Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_END_LAT)),
            Double.valueOf(rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_END_LNG)));


    List<Marker> markersList = new ArrayList<Marker>();
    Marker StartLatLon= googleMap.addMarker(new MarkerOptions().position(fromPosition).title("Start Point").icon(BitmapDescriptorFactory.fromResource(R.drawable.red_car_image)));
    Marker EndLatLon= googleMap.addMarker(new MarkerOptions().position(toPosition).icon(BitmapDescriptorFactory.fromResource(R.drawable.red_car_image)));
    markersList.add(StartLatLon);
    markersList.add(EndLatLon);

    builder = new LatLngBounds.Builder();
    for (Marker m : markersList) {
        builder.include(m.getPosition());
    }

    int padding = 150;
    LatLngBounds bounds = builder.build();
    cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
    googleMap.animateCamera(cu);

    traceMe(googleMap);


}

private void traceMe(final GoogleMap googleMap) {
    String srcParam;
    String destParam;

    String startLat=rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LAT);
    String startLng=rideDetailSessionManager.getColumnFromTaxiDriver(RideDetailSessionManager.KEY_START_LNG);

    GPSTracker gpsTracker=new GPSTracker(getActivity());

    srcParam = startLat + "," + startLng;
    destParam = gpsTracker.getLatitude() + "," + gpsTracker.getLongitude();
    Log.d("drop lat pp2", ":" + destParam);


    String modes[] = {"driving", "walking", "bicycling", "transit"};
    String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + srcParam + "&destination=" + destParam + "&sensor=false&units=metric&mode=driving";
    StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("dkp lat long", ":" + response);
                    JSONObject jsonObject=null;
                    try {
                        jsonObject=new JSONObject(response);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    MapDirectionsParser parser = new MapDirectionsParser();
                    List<List<HashMap<String, String>>> routes = parser.parse(jsonObject);

                    for (int i = 0; i < routes.size(); i++) {
                        points = new ArrayList<LatLng>();
                        List<HashMap<String, String>> path = routes.get(i);
                        Log.d("dkp lat long", ":" + path);
                        for (int j = 0; j < path.size(); j++) {
                            HashMap<String, String> point = path.get(j);
                            double lat = Double.parseDouble(point.get("lat"));
                            double lng = Double.parseDouble(point.get("lng"));
                            LatLng position = new LatLng(lat, lng);
                            points.add(position);
                        }

                    }

                    Log.d("dkp points lat long", ":" + points);
                    drawPoints(points, googleMap);
                    String str_dist=parser.distance();
                    //String str_dur=parser.duration();
                    if (!str_dist.equals("null"))
                    {
                    distance= Integer.parseInt(str_dist);
                    //estimate_distance= (distance/100)+50;
                    //rideEstimateDistance.setText((estimate_distance-50)+"-"+estimate_distance);
                    Log.d("dkp kkk distance", ":" + distance);
                     }

                    /*if (!str_dur.equals("null"))
                    {
                    int duration=Integer.parseInt(parser.duration());
                        estimate_duration= duration/60;
                    ideEstimateDistance.setText((estimate_distance-50)+"-"+estimate_distance);
                    Log.d("dkp kkk duration", ":" + duration);
                       }*/
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                        Log.d("error ocurred", "TimeoutError");
                        //Toast.makeText(getActivity(), "TimeoutError", Toast.LENGTH_LONG).show();
                    } else if (error instanceof AuthFailureError) {
                        Log.d("error ocurred", "AuthFailureError");
                        //Toast.makeText(getActivity(), "AuthFailureError", Toast.LENGTH_LONG).show();
                    } else if (error instanceof ServerError) {
                        Log.d("error ocurred", "ServerError");
                        // emailEdt.requestFocus();
                        //  Toast.makeText(getActivity(), "Please enter valid email or password", Toast.LENGTH_LONG).show();
                        // Toast.makeText(getActivity(), "ServerError", Toast.LENGTH_LONG).show();
                    } else if (error instanceof NetworkError) {
                        Log.d("error ocurred", "NetworkError");
                        //Toast.makeText(getActivity(), "NetworkError", Toast.LENGTH_LONG).show();
                    } else if (error instanceof ParseError) {
                        Log.d("error ocurred", "ParseError");
                        //Toast.makeText(getActivity(), "ParseError", Toast.LENGTH_LONG).show();
                    }
                }
            });

    // MyApplication.getInstance().addToRequestQueue(jsonObjectRequest, "jreq");
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    requestQueue.add(jsonObjectRequest);
}

private void drawPoints(ArrayList<LatLng> points, GoogleMap mMaps) {
    if (points == null) {
        return;
    }
    traceOfMe = points;
    PolylineOptions polylineOpt = new PolylineOptions();
    for (LatLng latlng : traceOfMe) {
        polylineOpt.add(latlng);
    }
    polylineOpt.color(Color.BLUE);
    if (mPolyline != null) {
        mPolyline.remove();
        mPolyline = null;
    }
    if (mMaps != null) {
        mPolyline = mMaps.addPolyline(polylineOpt);
    } else {
    }
    if (mPolyline != null)
        mPolyline.setWidth(7);

} 

1 个答案:

答案 0 :(得分:0)

您必须使用googleMap.clear()从地图中删除标记,然后在新位置重新绘制标记。