Home > database >  How do I draw a repeatable polyline on googleMap?
How do I draw a repeatable polyline on googleMap?

Time:06-20

'''

public class GpsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final int PRIORITY_HIGH_ACCURACY = 100;
    private GoogleMap mMap;
    private static final int PERMISSIONS_FINE_LOCATION = 99;

    Location loc;
    LatLng curPo;
    boolean state = false;

    private LocationRequest locationRequest;
    private FusedLocationProviderClient fusedLocationProviderClient;

    Button rstart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        locationRequest = LocationRequest.create()
                .setInterval(5000)
                .setPriority(PRIORITY_HIGH_ACCURACY)
                .setSmallestDisplacement(5);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(locationRequest);

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(GpsActivity.this);

        setContentView(R.layout.activity_gps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);


        rstart = findViewById(R.id.rstart);
        rstart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changeState();
            }


        });

        askforPermission();

    }


    @SuppressLint("MissingPermission")
    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;
        if(checkPermission()){
            mMap.setMyLocationEnabled(true);
        }


        mMap.getUiSettings().setMyLocationButtonEnabled(true);

    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");

        if (checkPermission()) {

            Log.d(TAG, "onStart : call mFusedLocationClient.requestLocationUpdates");
            fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);

            if (mMap!=null)
                mMap.setMyLocationEnabled(true);
        }
    }

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



    // Methods

    private void askforPermission(){
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED){

            LocationCallback mCallback = new LocationCallback() {
                @Override
                public void onLocationResult(@NonNull LocationResult locationResult) {
                    super.onLocationResult(locationResult);
                    for(Location location : locationResult.getLocations()){
                        setCurrentLocation(location);
                    }
                }
            };

            fusedLocationProviderClient.requestLocationUpdates(locationRequest,mCallback,null);
            fusedLocationProviderClient.removeLocationUpdates(mCallback);
        }else{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
            }
        }
    }

    private boolean checkPermission() {
        int hasFineLocationPermission = ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION);
        int hasCoarseLocationPermission = ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION);
        if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED &&
                hasCoarseLocationPermission == PackageManager.PERMISSION_GRANTED ) {
            return true;
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case PERMISSIONS_FINE_LOCATION:
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    askforPermission();
                }else{
                    Toast.makeText(this,"this App requires permission for gps", Toast.LENGTH_SHORT).show();
                    finish();
                }
        }
    }

    public void setCurrentLocation(Location location) {

        LatLng startLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(startLatLng, 15);
        mMap.moveCamera(cameraUpdate);
        //mMap.addMarker(new MarkerOptions().position(currentLatLng));  //확인용
    }

    LocationCallback locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(@NonNull LocationResult locationResult) {
            super.onLocationResult(locationResult);

            List<Location> savedLocation = locationResult.getLocations();

            if(savedLocation.size() > 0){
                loc = savedLocation.get(savedLocation.size() - 1);
                curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
                String curPoLog = "Lat: "   loc.getLatitude()   "Long: "   loc.getLongitude();
                Log.d(TAG,"OnLocationResult: "   curPoLog);
                setCurrentLocation(loc);
            }
        }
    };
    public void changeState() {
        if(!state){
            mMap.clear();
            state = true;
            Toast.makeText(this, "Recording Start", Toast.LENGTH_SHORT).show();
            if(state && checkPermission()){
                fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
                addMarkerSingle();
            }
            rstart.setText("Stop");
        }else{
            state = false;
            Toast.makeText(this, "Recording Stop", Toast.LENGTH_SHORT).show();
            if(!state) {
                addMarkerSingle();
                fusedLocationProviderClient.removeLocationUpdates(locationCallback);
            }
            rstart.setText("Start");
        }
    }

    public void addMarkerSingle(){
        if(checkPermission()){
            fusedLocationProviderClient.getLastLocation()
                    .addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    double markerLat = location.getLatitude();
                    double markerLong = location.getLongitude();
                    LatLng startEnd = new LatLng(markerLat, markerLong);

                    mMap.addMarker(new MarkerOptions().position(startEnd));
                }
            });
        }
    }
}

'''

Hi I'm a noob to programming this is my first project after learning 3month and I have no idea how to make it happen

I want to draw a real time foot print tracking polyline but no matter what I do, it never works I tried to get a LatLng and draw a polyline from inside LocationCallback and I also tried making a new Thread to handle it I tried in onCreate, onMapReady and everything but it never works. so I came here to ask how you guys handle these kindda stuff.

I know it's shitty code and I know I suck plz understand, among 3 month of lessons java class went for only 2weeks we never even got to using Thread part, plz help me out.

the code above is code with out any errors. I can check my location on real time and there is start marker and end marker. What I want to do is track the paths I walked and show it with polyline. not after i finish I want it to keep updating real time

Thank you for your time and help

CodePudding user response:

You need to store/cache the list of LatLng you get from LocationCallback.

Create a property

private ArrayList<String> myPath = new ArrayList<>();

Now every time a new location is received in the LocationCallback you add it to the myPath and update your map

LocationCallback locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(@NonNull LocationResult locationResult) {
            super.onLocationResult(locationResult);

            List<Location> savedLocation = locationResult.getLocations();

            if(savedLocation.size() > 0){
                loc = savedLocation.get(savedLocation.size() - 1);
                curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
                String curPoLog = "Lat: "   loc.getLatitude()   "Long: "   loc.getLongitude();
                Log.d(TAG,"OnLocationResult: "   curPoLog);
                setCurrentLocation(loc);
                
                //add this
                myPath.add(loc)
                updateMap()
            }
        }
    };

Your updateMap() method might look like this

PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.addAll(myPath);
polylineOptions.width(10f)
    .color(Color.RED)
    .geodesic(true);

if(mMap != null {
    mMap.addPolyline(polylineOptions);
}
polyLineCollection.addPolyline(polylineOptions)
tempLine.tag = MarkerID(line.id, line.layerId , null)

CodePudding user response:

try this code

    //...
        LocationCallback locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(@NonNull LocationResult locationResult) {
                super.onLocationResult(locationResult);
    
                List<Location> savedLocation = locationResult.getLocations();
        Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
                    .clickable(false);
                    for(int i = 0; i<savedLocation.size; i  ){
polyline1.add(new LatLng(savedLocation[i].latitude, savedLocation[i].longitude)));
}
            // Store a data object with the polyline, used here to indicate an arbitrary type.
            polyline1.setTag("A");
            // Style the polyline.
            stylePolyline(polyline1);
    
                if(savedLocation.size() > 0){
                    loc = savedLocation.get(savedLocation.size() - 1);
                    curPo = new LatLng(loc.getLatitude(), loc.getLongitude());
                    String curPoLog = "Lat: "   loc.getLatitude()   "Long: "   loc.getLongitude();
                    Log.d(TAG,"OnLocationResult: "   curPoLog);
                    setCurrentLocation(loc);
                }
            }
        };
    ...//
  • Related