Google Map上的Radar Animation不起作用

时间:2019-04-25 11:33:13

标签: java android

在我的案例中,我遵循此链接How to create the radar animation at the center of Google Map?的问题是动画无法正常工作,并且标记上出现了一些静态圆圈。标记上仅显示圆圈,没有动画。我已经按照我遵循的准则对代码进行了交叉检查,没有区别。如果我错过了一些重要的事情,这些事情会限制我的代码正常工作,请提供指导。

这是MapsActivity

为简单起见,我在描述基本流程。 我将RadarView的实例声明为mapRadar,然后在onCreate()中实例化它。在onMapReady中,调用goToLocationZoom来设置标记位置。在goToLocationZoom内部,我调用了RadarView类的startAnimation方法。

    public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{

            private GoogleMap mMap;
            protected GoogleApiClient mGoogleApiClient;
            //MapRipple mapRipple;
            private RadarView mapRadar;
            EditText locationEditText,radiusEditText;

            // parameters for geofence///
            public static String locationKeyName="Eziline Software House";
            public static double latitude=33.603559;
            public static double longitude=73.026470;
            public static int radius=20;
            public static long geofenceExpiration=12 * 60 * 60 * 1000;


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

                mapRadar=new RadarView(this);

                locationEditText=(EditText)findViewById(R.id.et_place);
                radiusEditText=(EditText)findViewById(R.id.et_radius);
                // Obtain the SupportMapFragment and get notified when the map is ready to be used.

                if(googlePayServicesAvailable()){
                    Toast.makeText(this, "Perfect!!!", Toast.LENGTH_LONG).show();
                }
                // default feofence parameters//
                locationKeyName="Eziline Software House";
                latitude=33.603559; longitude=73.026470;
                radius=20;
                geofenceExpiration=12 * 60 * 60 * 1000;


                MapFragment mapFragment = (MapFragment) getFragmentManager()
                        .findFragmentById(R.id.map);
                Toast.makeText(this, " mapFragment Perfect!!!", Toast.LENGTH_LONG).show();
                mapFragment.getMapAsync(this);
            }



            public boolean googlePayServicesAvailable(){
                GoogleApiAvailability api=GoogleApiAvailability.getInstance();
                int isAvailable=api.isGooglePlayServicesAvailable(this);

                if(isAvailable== ConnectionResult.SUCCESS){
                    return true;
                }
                else if(api.isUserResolvableError(isAvailable)){
                    Dialog dialog=api.getErrorDialog(this,isAvailable,0);
                    dialog.show();
                }
                else {
                    Toast.makeText(this, "Cann't connect to play services", Toast.LENGTH_LONG).show();
                }
                return false;
            }


            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
                locationEditText.setText("Eziline Software House Pvt. Ltd.");
                radiusEditText.setText(20+"");
                // Add a marker in Sydney and move the camera
                try {
                    goToLocationZoom(33.603559, 73.026470, 15, "Eziline Software House Pvt. Ltd.");
                    Toast.makeText(this, "go to location zoom Perfect!!!", Toast.LENGTH_LONG).show();
                }
                catch (Exception e){
                    Toast.makeText(this, "Exception "+e, Toast.LENGTH_LONG).show();
                }


                mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
                   @Override
                   public void onMapLongClick(LatLng latLng) {
                       Geocoder gc=new Geocoder(MapsActivity.this);
                       double lat=latLng.latitude;double lng=latLng.longitude;
                       List<Address> list = null;
                       try {
                           list = gc.getFromLocation(lat, lng,1);
                       } catch (IOException e) {
                           e.printStackTrace();
                       }
                       Address address = list.get(0);
                       final String locality = address.getLocality();
                       Toast.makeText(getApplicationContext(), "Location "+locality, Toast.LENGTH_LONG).show();
                       goToLocationZoom(lat,lng,15,locality);
                       locationEditText.setText(locality);
                       }
               });
               mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
                    @Override
                    public void onMarkerDragStart(Marker marker) {

                    }

                    @Override
                    public void onMarkerDrag(Marker marker) {

                    }

                    @Override
                    public void onMarkerDragEnd(Marker marker) {
                        Geocoder gc = new Geocoder(MapsActivity.this);
                        LatLng ll=marker.getPosition();
                        double lat=ll.latitude;double lng=ll.longitude;
                        List<Address> list = null;
                        try {
                            list = gc.getFromLocation(lat, lng,1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Address address = list.get(0);
                        final String locality = address.getLocality();
                        marker.setTitle(locality);
                        //drawCircle(new LatLng(lat,lng));
                        locationEditText.setText(locality);
                        if(TextUtils.isEmpty(radiusEditText.getText())){
                            radiusEditText.setText(radius+"");
                        }

                    }
                });
                /**mMap.setMyLocationEnabled(true);
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .addApi(LocationServices.API)
                        .build();
                mGoogleApiClient.connect();**/
            }

            Marker marker=null;
            private void setMarker(double lat,double lng, String location){

                if(marker!=null){
                    marker.remove();
                }
                marker.setDraggable(true);
                MarkerOptions markerOptions= new MarkerOptions();
                markerOptions.title(location).position(new LatLng(lat,lng)).snippet("Here You're");
                marker= mMap.addMarker(markerOptions);
            }
            public
            Circle circle=null;
            private void drawCircle(LatLng latLng){
                if(circle!=null){
                    circle.remove();
                }
                CircleOptions options= new CircleOptions().center(latLng).fillColor(0x33FF0000).strokeColor(Color.BLUE).strokeWidth(3).radius(Integer.parseInt(radiusEditText.getText().toString()));

                circle=mMap.addCircle(options);
            }


            public void geoLocate(View view)throws Exception{

                if(TextUtils.isEmpty(locationEditText.getText())){
                    locationEditText.setError("Location can't be empty");

                    return;
                }
                else if(TextUtils.isEmpty(radiusEditText.getText())){
                    radiusEditText.setError("Radius can't be empty");

                    return;
                }
                else {
                    final String location = locationEditText.getText().toString();
                    final int rad=Integer.parseInt(radiusEditText.getText().toString());
                    Geocoder gc = new Geocoder(this);
                    List<Address> list=null;
                    try {
                        list = gc.getFromLocationName(location, 1);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(this, "No Location matched. Kindly check your internet connection or enter correct location", Toast.LENGTH_LONG).show();
                        return;
                    }
                    //List<Address> list = gc.getFromLocationName(location, 1);
                    Address address = list.get(0);




                    final String locality = address.getLocality();
                    Toast.makeText(this, locality, Toast.LENGTH_SHORT).show();

                    final double lat = address.getLatitude();
                    final double lng = address.getLongitude();
                    final LatLng locLatlng = new LatLng(lat, lng);


                    AlertDialog.Builder alertDialog= new AlertDialog.Builder(this)
                            .setTitle("Confirmation")
                            .setMessage("Do you want to set a geofence of Radius: "+radiusEditText.getText()+" at Location: "+locationEditText.getText())
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    latitude=lat;longitude=lng;
                                    radius=rad;
                                    locationKeyName=locality;
                                    goToLocationZoom(lat, lng, 15, location);
                                    //drawCircle(locLatlng);
                                    dialog.dismiss();
                                }
                            }).setNegativeButton("No",new DialogInterface.OnClickListener(){
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                   dialog.dismiss();
                                }
                            });
                    AlertDialog dialog = alertDialog.create();
                    dialog.show();

                }



            }

            public void setLongLatGeofence(View view)throws Exception{
                final Dialog dialog=new Dialog(this);
                dialog.setContentView(R.layout.dialog_set_latlong_geofence);
                dialog.setTitle("Custom Dimensions");
                final EditText latEditText=(EditText)dialog.findViewById(R.id.et_lat);
                final EditText longEditText=(EditText)dialog.findViewById(R.id.et_lng);
                final EditText radEditText=(EditText)dialog.findViewById(R.id.et_rad);
                Button setButton=(Button)dialog.findViewById(R.id.btn_set_geofence);
                setButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try{
                        if(TextUtils.isEmpty(latEditText.getText())){
                            latEditText.setError("Latitude can't be empty");
                            return;
                        }
                        else if(TextUtils.isEmpty(longEditText.getText())){
                            longEditText.setError("Latitude can't be empty");
                            return;
                        }
                        else if(TextUtils.isEmpty(radEditText.getText())){
                            radEditText.setError("Radius can't be empty");
                            return;
                        }
                        else {

                            try {
                                final double lat = Double.parseDouble(latEditText.getText().toString().trim());
                                final double lng= Double.parseDouble(longEditText.getText().toString().trim());
                                final int rad=Integer.parseInt(radEditText.getText().toString().trim());
                                Geocoder gc = new Geocoder(getApplicationContext());
                                List<Address> list=null;
                                LatLng latLng=new LatLng(lat,lng);
                                list = gc.getFromLocation(33.8785834,73.7549315, 1);
                                Address address = list.get(0);
                                final String locality = address.getLocality();

                                latitude=lat;longitude=lng;
                                radius=rad;
                                locationKeyName=locality;
                                locationEditText.setText(locality);
                                radiusEditText.setText(rad);
                                goToLocationZoom(lat, lng, 15, locality);
                                dialog.dismiss();
                            } catch (IOException e) {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Exception "+e, Toast.LENGTH_SHORT).show();

                                return;
                            }
                            //List<Address> list = gc.getFromLocationName(location, 1);

                        }
                    }catch (Exception e ){
                            Toast.makeText(getApplicationContext(), "Location Not Found or check your internet connection "+e, Toast.LENGTH_SHORT).show();
                            //Toast.makeText(getApplicationContext(), "No Location matched. Kindly check your internet connection or enter correct location", Toast.LENGTH_LONG).show();
                            return;
                        }
                    }
                });
                dialog.show();
            }

            public void goToLocationZoom(double lat, double lng, float zoom, String location){
                LatLng sydney = new LatLng(lat, lng);
                if(marker!=null){
                    marker.remove();
                }
                //marker.setDraggable(true);
                marker= mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in "+location).snippet("Here You're"));
                //setMarker(lat,lng,location);
                //drawCircle(sydney);


                //// marker draw circles for radar type animation/////

                mapRadar.setShowCircles(true);
               if (mapRadar!= null) {
                    mapRadar.startAnimation();
                }
                else{
                    Toast.makeText(this, "mapRadar=null", Toast.LENGTH_SHORT).show();
                }
                ////////////////////////////////////////////

                if(circle!=null){
                    circle.remove();
                }
                CircleOptions options= new CircleOptions().center(sydney).fillColor(0x33FF0000).strokeColor(Color.BLUE).strokeWidth(3).radius(Integer.parseInt(radiusEditText.getText().toString()));

                circle=mMap.addCircle(options);
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,zoom));


            }
            LocationRequest mLocationRequest;
            @Override
            public void onConnected(Bundle bundle) {
                mLocationRequest=LocationRequest.create();
                mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                mLocationRequest.setInterval(1000);

                if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
                    if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
                        return;

                    }
                }

                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest, (com.google.android.gms.location.LocationListener) this);
            }

            @Override
            public void onConnectionSuspended(int i) {

            }

            @Override
            public void onConnectionFailed(ConnectionResult connectionResult) {

            }


            @Override
            public void onLocationChanged(Location location) {
                if(location==null){
                    Toast.makeText(this, "Can't get current location", Toast.LENGTH_SHORT).show();
                }
                else{
                    LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
                    if(marker!=null){
                        marker.remove();
                    }
                    marker=mMap.addMarker(new MarkerOptions().position(loc).title("Current Location"));
                    //setMarker(location.getLatitude(),location.getLongitude(),"Current Location");
                    CircleOptions options= new CircleOptions().center(loc).fillColor(0x33FF0000).strokeColor(Color.BLUE).strokeWidth(3).radius(Integer.parseInt(radiusEditText.getText().toString()));
                    if(circle!=null){
                        circle.remove();
                    }
                    circle=mMap.addCircle(options);
                    //drawCircle(loc);
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc,15));


                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }

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


            }
        }

here is RadarView class


    public class RadarView extends View {

        private final String LOG = "RadarView";
        private final int POINT_ARRAY_SIZE = 25;
        float alpha = 0;
        Point latestPoint[] = new Point[POINT_ARRAY_SIZE];
        Paint latestPaint[] = new Paint[POINT_ARRAY_SIZE];
        android.os.Handler mHandler = new android.os.Handler();
        private int fps = 100;
        Runnable mTick = new Runnable() {
            @Override
            public void run() {
                invalidate();
                mHandler.postDelayed(this, 1000 / fps);
            }
        };
        private boolean showCircles = true;

        public RadarView(Context context) {
            this(context, null);
        }


        public RadarView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }

        public RadarView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);

            Paint localPaint = new Paint();
            localPaint.setColor(getResources().getColor(R.color.colorPrimary));
            localPaint.setAntiAlias(true);
            localPaint.setStyle(Paint.Style.STROKE);
            localPaint.setStrokeWidth(1.0F);
            localPaint.setAlpha(0);

            int alpha_step = 255 / POINT_ARRAY_SIZE;
            for (int i = 0; i < latestPaint.length; i++) {
                latestPaint[i] = new Paint(localPaint);
                latestPaint[i].setAlpha(255 - (i * alpha_step));
            }
        }

        public void startAnimation() {
            mHandler.removeCallbacks(mTick);
            mHandler.post(mTick);
        }

        public void stopAnimation() {
            mHandler.removeCallbacks(mTick);
        }

        public int getFrameRate() {
            return this.fps;
        }

        public void setFrameRate(int fps) {
            this.fps = fps;
        }

        ;

        public void setShowCircles(boolean showCircles) {
            this.showCircles = showCircles;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);


            int width = getWidth();
            int height = getHeight();

            int r = Math.min(width, height);


            //canvas.drawRect(0, 0, getWidth(), getHeight(), localPaint);

            int i = r / 2;
            int j = i - 1;
            Paint localPaint = latestPaint[0]; // GREEN

            if (showCircles) {
                canvas.drawCircle(i, i, j, localPaint);
                canvas.drawCircle(i, i, j, localPaint);
                canvas.drawCircle(i, i, j * 3 / 4, localPaint);
                canvas.drawCircle(i, i, j >> 1, localPaint);
                canvas.drawCircle(i, i, j >> 2, localPaint);
            }

            alpha -= 0.5;
            if (alpha < -360) alpha = 0;
            double angle = Math.toRadians(alpha);
            int offsetX = (int) (i + (float) (i * Math.cos(angle)));
            int offsetY = (int) (i - (float) (i * Math.sin(angle)));

            latestPoint[0] = new Point(offsetX, offsetY);

            for (int x = POINT_ARRAY_SIZE - 1; x > 0; x--) {
                latestPoint[x] = latestPoint[x - 1];
            }


            int lines = 0;
            for (int x = 0; x < POINT_ARRAY_SIZE; x++) {
                Point point = latestPoint[x];
                if (point != null) {
                    canvas.drawLine(i, i, point.x, point.y, latestPaint[x]);
                }
            }


            lines = 0;
            for (Point p : latestPoint) if (p != null) lines++;

            boolean debug = false;
            if (debug) {
                StringBuilder sb = new StringBuilder(" >> ");
                for (Point p : latestPoint) {
                    if (p != null) sb.append(" (" + p.x + "x" + p.y + ")");
                }

                Log.d(LOG, sb.toString());
                //  " - R:" + r + ", i=" + i +
                //  " - Size: " + width + "x" + height +
                //  " - Angle: " + angle +
                //  " - Offset: " + offsetX + "," + offsetY);
            }

        }

    }

activity_maps.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.saba.geogooglemap.MapsActivity"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        android:layout_margin="10dp">
        <EditText
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="match_parent"
            android:id="@+id/et_place"
            android:hint="Location"
            android:textSize="15sp"
            android:layout_marginRight="5dp"
            android:textColor="@color/textColor"
            android:tooltipText="Geofence central location"/>
        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:id="@+id/et_radius"
            android:hint="Radius im meters"
            android:textSize="15sp"
            android:textColor="@color/textColor"
            android:inputType="number"
            android:maxLength="4"
            android:tooltipText="Geofence radiud in meters"/>

    </LinearLayout>
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
        android:gravity="center">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn_set"
            android:text="Set Geofence"
            android:onClick="geoLocate"
            android:layout_gravity="center"
            android:background="@color/textColor"
            android:textColor="@color/white_color"
            android:layout_marginBottom="5dp"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:padding="5dp"
            android:layout_marginRight="8dp"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn_latlong"
            android:text="Custom Dimensions"
            android:onClick="setLongLatGeofence"
            android:layout_gravity="center"
            android:background="@color/textColor"
            android:textColor="@color/white_color"
            android:layout_marginBottom="5dp"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:padding="5dp"/>
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:layout_above="@+id/bootomLayout">

        <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="8dp"
            android:name="com.google.android.gms.maps.MapFragment"
            android:id="@+id/map"/>

        <com.example.saba.geogooglemap.RadarView
            android:id="@+id/radarView"
            android:layout_width="240dp"
            android:layout_height="240dp"
            android:layout_centerInParent="true"
            />
    </RelativeLayout>


</LinearLayout>

0 个答案:

没有答案