如何在我的应用程序中添加uber / ola动画

时间:2019-03-27 14:42:44

标签: android google-maps uber-api

这是我的代码。我想要实现的是,每当用户在editext中输入一个位置时,单击按钮时,像uber(汽车应移动)之类的动画将从硬编码位置添加到用户输入的位置。目前,每当我单击该按钮时,它只会向我显示该硬代码位置。谁能帮忙吗?

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {


    SupportMapFragment mapFragment;
    private GoogleMap mMap;
    private List<LatLng> polylineList;
    private Marker marker;
    private float v;
    private double lat, lng;
    private Handler handler;
    private LatLng startposition, endposition;
    private int index, next;
    private Button btngo;
    private EditText editplace;
    private String destination;
    private PolylineOptions polylineOptions, blackpolylineoptions;
    private Polyline blackpolyline, greypolyline;
    private LatLng mylocation;
    IGoogleApi mservice;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

        //Here begins;

        polylineList = new ArrayList<>();
        btngo = findViewById(R.id.btnsearch);
        editplace = findViewById(R.id.editplace);
        btngo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                destination = editplace.getText().toString();
                destination = destination.replace(" ", "+");
                mapFragment.getMapAsync(MapsActivity.this);
            }
        });

        mservice = Common.getGoogleApi();


    }



    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.setTrafficEnabled(false); 
        mMap.setIndoorEnabled(false);
        mMap.setBuildingsEnabled(false);

        mMap.getUiSettings().setZoomControlsEnabled(true);
        // Add a marker in Sydney and move the camera
        final LatLng sydney = new LatLng(28.6753814, 77.1618454);
        mMap.addMarker(new MarkerOptions().position(sydney).title("My Location"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(googleMap.
                getCameraPosition().target).zoom(17).bearing(30).tilt(45).build()));
        String requesturl = null;
        try {

            requesturl = "https://maps.googleapis.com/maps/api/directions/json?" + "mode=driving&" + "transit_routing_preference" +
                    "=less_driving&" + "origin=" + sydney.latitude + "," + sydney.longitude + "&destination=" + destination + "&key=" +
                    getResources().getString(R.string.google_direction_key);
            Log.d("URL", requesturl);

            mservice.getDatafromGoogleApi(requesturl).enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {

                    try {

                        JSONObject jsonObject = new JSONObject(response.body().toString());
                        JSONArray jsonArray = jsonObject.getJSONArray("routes");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject route = jsonArray.getJSONObject(i);
                            JSONObject poly = route.getJSONObject("overview_polyline");
                            String polyline = poly.getString("points");
                            polylineList = decodePoly(polyline);
                        }

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : polylineList)
                            builder.include(latLng);
                        LatLngBounds bounds = builder.build();
                        CameraUpdate mcameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 2);
                        mMap.animateCamera(mcameraUpdate);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.GRAY);
                        polylineOptions.width(5);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(JointType.ROUND);
                        polylineOptions.addAll(polylineList);
                        greypolyline = mMap.addPolyline(polylineOptions);

                        blackpolylineoptions = new PolylineOptions();
                        blackpolylineoptions.color(Color.GRAY);
                        blackpolylineoptions.width(5);
                        blackpolylineoptions.startCap(new SquareCap());
                        blackpolylineoptions.endCap(new SquareCap());
                        blackpolylineoptions.jointType(JointType.ROUND);
                        blackpolylineoptions.addAll(polylineList);
                        blackpolyline = mMap.addPolyline(polylineOptions);

                        mMap.addMarker(new MarkerOptions().position(polylineList.get(polylineList.size() - 1)));

                        //Animator
                        final ValueAnimator polylineanimator = ValueAnimator.ofInt(0, 100);
                        polylineanimator.setDuration(5000);
                        polylineanimator.setInterpolator(new LinearInterpolator());
                        polylineanimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {
                                List<LatLng> points = greypolyline.getPoints();
                                int percentvalue = (int) animation.getAnimatedValue();
                                int size = points.size();
                                int newpoints = (int) (size * (percentvalue / 100.0f));
                                List<LatLng> p = points.subList(0, newpoints);
                                blackpolyline.setPoints(p);

                            }
                        });
                        polylineanimator.start();

                        marker = mMap.addMarker(new MarkerOptions().position(sydney).flat(true).icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));

                        //car moving
                        handler = new Handler();
                        index = -1;
                        next = 1;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                if (index < polylineList.size() - 1) {
                                    index++;
                                    next = index + 1;

                                }
                                if (index < polylineList.size() - 1) {
                                    startposition = polylineList.get(index);
                                    endposition = polylineList.get(next);

                                }
                                final ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
                                valueAnimator.setDuration(3000);
                                valueAnimator.setInterpolator(new LinearInterpolator());
                                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                    @Override
                                    public void onAnimationUpdate(ValueAnimator animation) {
                                        /*List<LatLng> points = greypolyline.getPoints();
                                        int percentvalue = (int) animation.getAnimatedValue();
                                        int size = points.size();
                                        int newpoints = (int) (size * (percentvalue / 100.0f));
                                        List<LatLng> p = points.subList(0, newpoints);
                                        blackpolyline.setPoints(p);*/
                                        v = valueAnimator.getAnimatedFraction();
                                        lng = v * endposition.longitude + (1 - v) * startposition.longitude;
                                        lat = v * endposition.latitude + (1 - v) * startposition.latitude;
                                        LatLng newPos = new LatLng(lat, lng);
                                        marker.setPosition(newPos);
                                        marker.setAnchor(0.5f, 0.5f);
                                        marker.setRotation(getBearing(startposition, newPos));
                                        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
                                                .target(newPos).zoom(15.5f).build()));

                                    }
                                });
                                valueAnimator.start();
                                handler.postDelayed(this, 3000);


                            }
                        }, 3000);

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

                @Override
                public void onFailure(Call<String> call, Throwable t) {

                    Toast.makeText(MapsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });


        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    private float getBearing(LatLng startposition, LatLng newPos) {
        double lat = Math.abs(startposition.latitude - newPos.latitude);
        double lng = Math.abs(startposition.longitude - newPos.longitude);

        if (startposition.latitude < newPos.latitude && startposition.longitude < newPos.longitude) {
            return (float) (Math.toDegrees(Math.atan(lng / lat)));
        } else if (startposition.latitude >= newPos.latitude && startposition.longitude < newPos.longitude) {
            return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
        } else if (startposition.latitude >= newPos.latitude && startposition.longitude >= newPos.longitude) {
            return (float) (Math.toDegrees(Math.atan(lng / lat)) + 180);
        } else if (startposition.latitude < newPos.latitude && startposition.longitude >= newPos.longitude) {
            return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
        }
        return -1;
    }

    private List<LatLng> decodePoly(String encoded) {
        List poly = new ArrayList();
        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;
    }

}

0 个答案:

没有答案