Java 跑步/驾驶时在谷歌地图上绘制多段线 运行/绘制时在google地图上绘制多段线

Java 跑步/驾驶时在谷歌地图上绘制多段线 运行/绘制时在google地图上绘制多段线,java,android,google-maps,Java,Android,Google Maps,我正在创建一个应用程序,用户可以在其中跟踪从何处到他刚才运行的位置的路径。我已经尝试了以下代码,它的工作,但当运行它开始落后,谁能告诉我哪里我做错了 要绘制多段线,我将在一段时间后刷新贴图 公共类MapsActivity扩展了AppCompatActivity在MapReadyCallback上的实现{ 私有静态final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION=5445; 私人谷歌地图谷歌地图; 私有FusedLocationProvid

我正在创建一个应用程序,用户可以在其中跟踪从何处到他刚才运行的位置的路径。我已经尝试了以下代码,它的工作,但当运行它开始落后,谁能告诉我哪里我做错了

要绘制多段线,我将在一段时间后刷新贴图

公共类MapsActivity扩展了AppCompatActivity在MapReadyCallback上的实现{
私有静态final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION=5445;
私人谷歌地图谷歌地图;
私有FusedLocationProviderClient FusedLocationProviderClient;
专用标记currentLocationMarker;
私人位置;
私有布尔值firstTimeFlag=true;
private ArrayList points=new ArrayList();//已添加
多段线;//已添加
/*private final View.OnClickListener clickListener=View->{
if(view.getId()==R.id.currentLocationImageButton&&googleMap!=null&¤tLocation!=null)
animateCamera(当前位置);
};
*/
私有最终位置回调mlLocationCallback=新位置回调(){
@凌驾
public void onLocationResult(LocationResult LocationResult){
super.onLocationResult(定位结果);
if(locationResult.getLastLocation()==null)
返回;
currentLocation=locationResult.getLastLocation();
if(firstTimeFlag&&googleMap!=null){
animateCamera(当前位置);
firstTimeFlag=false;
}
显示标记(当前位置);
}
};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
SupportMapFragment SupportMapFragment=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(此文件);
//findViewById(R.id.currentLocationImageButton);
}
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
this.googleMap=谷歌地图;
}
私有void startCurrentLocationUpdate(){
LocationRequest LocationRequest=LocationRequest.create();
locationRequest.setPriority(locationRequest.PRIORITY\u高精度);
位置请求设置间隔(3000);
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.M){
if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予和&ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS\u LOCATION)!=PackageManager.permission\u已授予){
ActivityCompat.requestPermissions(MapsActivity.this,
新字符串[]{Manifest.permission.ACCESS\u FINE\u LOCATION},
我的权限、请求、访问、位置);
返回;
}
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest,mlLocationCallback,Looper.myLooper());
}
私有布尔值isGooglePlayServicesAvailable(){
GoogleAppAvailability GoogleAppAvailability=GoogleAppAvailability.getInstance();
int status=GooglePayAvailability.isGooglePlayServicesAvailable(此);
if(ConnectionResult.SUCCESS==状态)
返回true;
否则{
if(GoogleAppAvailability.isUserResolvableError(状态))
Toast.makeText(此“请安装google play服务以使用此应用程序”,Toast.LENGTH_LONG.show();
}
返回false;
}
@凌驾
public void onRequestPermissionsResult(int-requestCode,@NonNull-String[]permissions,@NonNull-int[]grantResults){
super.onRequestPermissionsResult(请求代码、权限、授权结果);
if(requestCode==我的权限请求访问位置){
if(grantResults[0]==PackageManager.PERMISSION\u被拒绝)
Toast.makeText(这是“用户拒绝的权限”,Toast.LENGTH_SHORT).show();
else if(grantResults[0]==已授予PackageManager.PERMISSION)
startCurrentLocationUpdates();
}
}
私有void animateCamera(@NonNull Location){
LatLng LatLng=新LatLng(location.getLatitude(),location.getLongitude());
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng));
}
@非空
专用摄像机位置获取带轴承的摄像机位置(车床){
返回新的CameraPosition.Builder().target(latLng.zoom(16.build));
}
私有void showMarker(@NonNull Location currentLocation){
LatLng LatLng=新LatLng(currentLocation.getLatitude(),currentLocation.getLength());
如果(currentLocationMarker!=null){
System.out.println(“lastmarkerposition”+currentLocationMarker.getPosition());
add(currentLocationMarker.getPosition());
currentLocationMarker.remove();
}
PolylineOptions=新的PolylineOptions();
对于(int i=0;i解决方案

经过大量研究,我在GitHub存储库中找到了解决方案

我对原始代码做了一些更改

公共类MapsActivity扩展了FragmentActivity在MapreadyCallback上的实现{
私有静态最终字符串TAG=“MapsActivity”;
公共谷歌地图;
私有数组列表点;
多段线;
现在标记;
双板条1;
双克隆1;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
points=新的ArrayList();
setContentView(R.layout.activity_映射);
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentByI
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;

    private GoogleMap googleMap;
    private FusedLocationProviderClient fusedLocationProviderClient;
    private Marker currentLocationMarker;
    private Location currentLocation;
    private boolean firstTimeFlag = true;


    private ArrayList<LatLng> points =new ArrayList<>(); //added
    Polyline line; //added

    /* private final View.OnClickListener clickListener = view -> {
         if (view.getId() == R.id.currentLocationImageButton && googleMap != null && currentLocation != null)
             animateCamera(currentLocation);
     };
 */
    private final LocationCallback mLocationCallback = new LocationCallback() {

        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            if (locationResult.getLastLocation() == null)
                return;
            currentLocation = locationResult.getLastLocation();
            if (firstTimeFlag && googleMap != null) {
                animateCamera(currentLocation);
                firstTimeFlag = false;
            }
            showMarker(currentLocation);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        supportMapFragment.getMapAsync(this);
        // findViewById(R.id.currentLocationImageButton).setOnClickListener(clickListener);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.googleMap = googleMap;
    }

    private void startCurrentLocationUpdates() {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(3000);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MapsActivity.this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
                return;
            }
        }
        fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
    }

    private boolean isGooglePlayServicesAvailable() {
        GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
        int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status)
            return true;
        else {
            if (googleApiAvailability.isUserResolvableError(status))
                Toast.makeText(this, "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED)
                Toast.makeText(this, "Permission denied by uses", Toast.LENGTH_SHORT).show();
            else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                startCurrentLocationUpdates();
        }
    }

    private void animateCamera(@NonNull Location location) {
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
    }

    @NonNull
    private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
        return new CameraPosition.Builder().target(latLng).zoom(16).build();
    }

    private void showMarker(@NonNull Location currentLocation) {
        LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
        if (currentLocationMarker != null){
            System.out.println("LastMArkerPostion" + currentLocationMarker.getPosition());
            points.add(currentLocationMarker.getPosition());
            currentLocationMarker.remove();



        }
        PolylineOptions options  = new PolylineOptions();

        for (int i = 0 ; i<points.size() ; i++ ){
            options.add(points.get(i)).width(15).color(Color.BLUE).geodesic(true);
            googleMap.addPolyline(options);
        }
        Drawable vectorDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_green_car_marker, null);
        Bitmap bit = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
                vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bit);
        vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        vectorDrawable.draw(canvas);

        currentLocationMarker = googleMap.addMarker(new MarkerOptions().icon( BitmapDescriptorFactory.fromBitmap(bit)).position(latLng));
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (fusedLocationProviderClient != null)
            fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isGooglePlayServicesAvailable()) {
            fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
            startCurrentLocationUpdates();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        fusedLocationProviderClient = null;
        googleMap = null;
    }
}
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    private static final String TAG = "MapsActivity";
    public GoogleMap mMap;
    private ArrayList<LatLng> points;
    Polyline line;
    Marker now;
    double lat1;
    double lon1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        points = new ArrayList<LatLng>();
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }


    @SuppressLint("MissingPermission")
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        if (!mMap.isMyLocationEnabled())
            mMap.setMyLocationEnabled(true);

        LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);


        if (myLocation == null) {
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            String provider = lm.getBestProvider(criteria, true);
            myLocation = lm.getLastKnownLocation(provider);
        }

        if (myLocation != null) {
            LatLng userLocation = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());

            lat1=myLocation.getLatitude();
            lon1=myLocation.getLongitude();

            mMap.addMarker(new MarkerOptions()
                    .position(userLocation)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
                    .title("Welcome ")
                    .snippet("Latitude:"+lat1+",Longitude:"+lon1)
            );

            Log.v(TAG, "Lat1=" + lat1);
            Log.v(TAG, "Long1=" + lon1);

            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 20), 1500, null);


            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,0, new LocationListener() {
                @Override
                public void onLocationChanged(Location myLocation) {

                    // Getting latitude of the current location
                    double latitude = myLocation.getLatitude();

                    // Getting longitude of the current location
                    double longitude = myLocation.getLongitude();

                    // Creating a LatLng object for the current location
                    LatLng latLng = new LatLng(latitude, longitude);

                    //Adding new marker
                 /*   now = mMap.addMarker(new MarkerOptions()
                            .icon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
                            .position(latLng).title("New")
                            .snippet("Latitude:"+lat1+",Longitude:"+lon1)
                    );*/

                    // Showing the current location in Google Map
                 //   mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

                    // Zoom in the Google Map
                 //   mMap.animateCamera(CameraUpdateFactory.zoomTo(20));

                    //Draw polyline
                    drawPolygon(latitude, longitude);

                 //   Toast.makeText(MapsActivity.this, String.valueOf(latitude)+String.valueOf(longitude), Toast.LENGTH_SHORT).show();


                }

                @Override
                public void onProviderDisabled(String provider) {
                    // TODO Auto-generated method stub
                }
                @Override
                public void onProviderEnabled(String provider) {
                    // TODO Auto-generated method stub
                }
                @Override
                public void onStatusChanged(String provider, int status,
                                            Bundle extras) {
                    // TODO Auto-generated method stub
                }
            });

        }


        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, 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;
        }


        mMap.getUiSettings().setZoomControlsEnabled(true);
    }

    private void drawPolygon( double latitude, double longitude) {

        List<LatLng> polygon = new ArrayList<>();
        //old lat and long
        polygon.add(new LatLng(lat1, lon1));
        //new lat and long


        polygon.add(new LatLng(latitude,longitude));



        mMap.addPolygon(new PolygonOptions()
                .addAll(polygon)
                .strokeColor(Color.parseColor("#03A9F4"))
                .strokeWidth(15)
                .fillColor(Color.parseColor("#B3E5FC"))
        );

        lat1=latitude;
        lon1=longitude;
    }

}