如何在此公共场所之外使用可变的distanceHala?

时间:2019-12-05 13:49:00

标签: java android android-fragments location

所以我想要的是计算用户当前位置和地图上标记之间的距离。

    final LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setInterval(2000);
    locationRequest.setFastestInterval(1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            if (locationResult == null) {
                return;
            }
            mLastKnownLocation = locationResult.getLastLocation();
            LatLng lastKnownLatLng = new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude());
            final double distanceHala = SphericalUtil.computeDistanceBetween(lastKnownLatLng, HalA);
            mFusedLocationProviderClient.removeLocationUpdates(locationCallback);
        }
    };

所以这是我现在用来计算距离的代码。我不确定这是否行得通。现在,我想在if语句中使用变量distanceHala来激活Onclicklistener:

else if (marker.getTitle().equals("Hal A")) {
                      if (distanceHala < 10){
                        Intent halaIntent = new Intent(MapS.this, hala.class);
                        startActivity(halaIntent);}}

这就是我要的。 问题在于它无法识别可变的distanceHala。 这是我的第一个使用Android Studio和Java的项目,因此请像我12岁时解释它。

完整代码:

package com.example.discoverkoelak;

import ...

public class MapS extends AppCompatActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    private FusedLocationProviderClient mFusedLocationProviderClient;

    private List<AutocompletePrediction> predictionList;

    private Location mLastKnownLocation;
    private LocationCallback locationCallback;
    private final float DEFAULT_ZOOM = 18;



    private View mapView;
    private Marker kaka;

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


        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.MapS);
        mapFragment.getMapAsync(this);
        mapView = mapFragment.getView();

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapS.this);
        Places.initialize(MapS.this, ("MY API KEY"));
        ImageView legendeBtn = (ImageView) findViewById(R.id.merkar);
        legendeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent maptoLegende = new Intent(getApplicationContext(), activity_legende.class);
                startActivity(maptoLegende);
            }
        });





        final AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 51) {
            if (resultCode == RESULT_OK) {
                getDeviceLocation();

            }
        }


    }
    @SuppressLint("MissingPermission")
    private void getDeviceLocation() {
        mFusedLocationProviderClient.getLastLocation()
                .addOnCompleteListener(new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {
                            mLastKnownLocation = task.getResult();
                            if (mLastKnownLocation != null) {
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                            } else {
                                final LocationRequest locationRequest = LocationRequest.create();
                                locationRequest.setInterval(2000);
                                locationRequest.setFastestInterval(1000);
                                locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                                locationCallback = new LocationCallback() {
                                    @Override
                                    public void onLocationResult(LocationResult locationResult) {
                                        super.onLocationResult(locationResult);
                                        if (locationResult == null) {
                                            return;
                                        }
                                        mLastKnownLocation = locationResult.getLastLocation();
                                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                                        mFusedLocationProviderClient.removeLocationUpdates(locationCallback);
                                    }
                                };
                                mFusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);

                            }
                        } else {
                            Toast.makeText(MapS.this, "Laatste gekende locatie kan niet worden ontvangen", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }



    @Override
    public void onMapReady(GoogleMap googleMap) {





        int height = 120;
        int width = 90;
        BitmapDrawable bitmapdraw=(BitmapDrawable)getResources().getDrawable(R.drawable.marker_dark);
        BitmapDrawable bitmapdraw2=(BitmapDrawable)getResources().getDrawable(R.drawable.marker_aula_0);
        BitmapDrawable bitmapdraw3=(BitmapDrawable)getResources().getDrawable(R.drawable.marker_research_0);
        BitmapDrawable bitmapdraw4=(BitmapDrawable)getResources().getDrawable(R.drawable.marker_residentie);
        BitmapDrawable bitmapdraw5=(BitmapDrawable)getResources().getDrawable(R.drawable.marker_ontspanning);
        BitmapDrawable bitmapdraw6=(BitmapDrawable)getResources().getDrawable(R.drawable.marker_mobiliteit_1);
        BitmapDrawable bitmapdraw7=(BitmapDrawable)getResources().getDrawable(R.drawable.marker_research_1);
        BitmapDrawable bitmapdraw8=(BitmapDrawable)getResources().getDrawable(R.drawable.marker_mobiliteit_0);
        BitmapDrawable bitmapdraw9=(BitmapDrawable)getResources().getDrawable(R.drawable.marker_administratie);


        Bitmap b=bitmapdraw.getBitmap();
        Bitmap b2=bitmapdraw2.getBitmap();
        Bitmap b3=bitmapdraw3.getBitmap();
        Bitmap b4=bitmapdraw4.getBitmap();
        Bitmap b5=bitmapdraw5.getBitmap();
        Bitmap b6=bitmapdraw6.getBitmap();
        Bitmap b7=bitmapdraw7.getBitmap();
        Bitmap b8=bitmapdraw8.getBitmap();
        Bitmap b9=bitmapdraw9.getBitmap();
        Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
        Bitmap aulas = Bitmap.createScaledBitmap(b2, width, height, false);
        Bitmap research = Bitmap.createScaledBitmap(b3, width, height, false);
        Bitmap residenties = Bitmap.createScaledBitmap(b4, width, height, false);
        Bitmap ontspanning = Bitmap.createScaledBitmap(b5, width, height, false);
        Bitmap mobiliteitU = Bitmap.createScaledBitmap(b6, width, height, false);
        Bitmap researchU = Bitmap.createScaledBitmap(b7, width, height, false);
        Bitmap mobiliteit = Bitmap.createScaledBitmap(b8, width, height, false);
        Bitmap administratie = Bitmap.createScaledBitmap(b9, width, height, false);
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);


Here I give all the markers their coordinates



        //Code die markers zet en ze klikbaar maakt.
        //Hal A
        googleMap.addMarker(new MarkerOptions().position(HalA)
                .title("Hal A")
                .icon(BitmapDescriptorFactory.fromBitmap(ontspanning)));
        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker) {
                  if (marker.getTitle().equals("Hal A")) {
                      Intent halaIntent = new Intent(MapS.this, hala.class);
                      startActivity(halaIntent);
                      return false;
                  }
                  return false;
              }
          }
        );

        googleMap.addMarker(new MarkerOptions().position(stuvo)
                .title("Stuvo")
                .icon(BitmapDescriptorFactory.fromBitmap(administratie)));

        googleMap.addMarker(new MarkerOptions().position(bib)
                .title("Bib")
                .icon(BitmapDescriptorFactory.fromBitmap(administratie)));

        googleMap.addMarker(new MarkerOptions().position(acco)
                .title("Acco boekenhandel")
                .icon(BitmapDescriptorFactory.fromBitmap(administratie)));

        googleMap.addMarker(new MarkerOptions().position(rectoraat)
                .title("Hal Rectoraat")
                .icon(BitmapDescriptorFactory.fromBitmap(administratie)));

        googleMap.addMarker(new MarkerOptions().position(spina)
                .title("Spina")
                .icon(BitmapDescriptorFactory.fromBitmap(mobiliteit)));

        googleMap.addMarker(new MarkerOptions().position(stilleRuimte)
                .title("Stille ruimte")
                .icon(BitmapDescriptorFactory.fromBitmap(ontspanning)));

        googleMap.addMarker(new MarkerOptions().position(A301)
                .title("Aula Stijn Streuvels (A301)")
                .icon(BitmapDescriptorFactory.fromBitmap(aulas)));

        googleMap.addMarker(new MarkerOptions().position(weetkelder)
                .title("Weetkelder")
                .icon(BitmapDescriptorFactory.fromBitmap(researchU)));

        googleMap.addMarker(new MarkerOptions().position(fietsena)
                .title("FietsenA")
                .icon(BitmapDescriptorFactory.fromBitmap(mobiliteitU)));

        googleMap.addMarker(new MarkerOptions().position(labos)
                .title("Labo's (gang 3)")
                .icon(BitmapDescriptorFactory.fromBitmap(research)));


        //gebouw B
        googleMap.addMarker(new MarkerOptions().position(B422)
                .title("B422")
                .icon(BitmapDescriptorFactory.fromBitmap(aulas)));


        googleMap.addMarker(new MarkerOptions().position(puc)
                .title("puc")
                .icon(BitmapDescriptorFactory.fromBitmap(research)));

        //gebouw c
        googleMap.addMarker(new MarkerOptions().position(C611)
                .title("C611")
                .icon(BitmapDescriptorFactory.fromBitmap(aulas)));

        googleMap.addMarker(new MarkerOptions().position(gang7)
                .title("Gang 7")
                .icon(BitmapDescriptorFactory.fromBitmap(research)));

        //gebouw E
        googleMap.addMarker(new MarkerOptions().position(E1001)
                .title("Aula Andreas Vesalius (E1001)")
                .icon(BitmapDescriptorFactory.fromBitmap(aulas)));

        googleMap.addMarker(new MarkerOptions().position(vaardigheidscentrum)
                .title("Vaardigheidscentrum")
                .icon(BitmapDescriptorFactory.fromBitmap(research)));

        googleMap.addMarker(new MarkerOptions().position(IRF)
                .title("IRF")
                .icon(BitmapDescriptorFactory.fromBitmap(research)));

        googleMap.addMarker(new MarkerOptions().position(fietsene)
                .title("fietsene")
                .icon(BitmapDescriptorFactory.fromBitmap(mobiliteitU)));

        //residenties
        googleMap.addMarker(new MarkerOptions().position(spoelberg)
                .title("Spoelberg")
                .icon(BitmapDescriptorFactory.fromBitmap(residenties)));

        googleMap.addMarker(new MarkerOptions().position(studentendorp)
                .title("Studentendorp")
                .icon(BitmapDescriptorFactory.fromBitmap(residenties)));

        googleMap.addMarker(new MarkerOptions().position(corona)
                .title("Corona")
                .icon(BitmapDescriptorFactory.fromBitmap(residenties)));

        //andere
        googleMap.addMarker(new MarkerOptions().position(IICK)
                .title("IICK")
                .icon(BitmapDescriptorFactory.fromBitmap(research)));

        googleMap.addMarker(new MarkerOptions().position(almaZweetkelder)
                        .title("Alma & Cantor en Zweetkelder")
                        .icon(BitmapDescriptorFactory.fromBitmap(ontspanning)));

        googleMap.addMarker(new MarkerOptions().position(ecolab)
                .title("Ecolab")
                .icon(BitmapDescriptorFactory.fromBitmap(ontspanning)));

        //Afstand berekenen tussen laatst gekende locatie en PoI's
//        LatLng lastKnownLatLng = new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude());
//        final double distanceEcolab = SphericalUtil.computeDistanceBetween(lastKnownLatLng, ecolab);
//        final double distanceHala = SphericalUtil.computeDistanceBetween(lastKnownLatLng, HalA);

        final LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setInterval(2000);
        locationRequest.setFastestInterval(1000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                if (locationResult == null) {
                    return;
                }
                mLastKnownLocation = locationResult.getLastLocation();
                LatLng lastKnownLatLng = new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude());
                final double distanceHala = SphericalUtil.computeDistanceBetween(lastKnownLatLng, HalA);
                mFusedLocationProviderClient.removeLocationUpdates(locationCallback);
            }
        };



        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
              @Override
              public boolean onMarkerClick(final Marker marker) {
                  if (marker.getTitle().equals("Ecolab")) {
                      Intent ecolabIntent = new Intent(MapS.this, activity_ecolab.class);
                      startActivity(ecolabIntent);
                  }

                  else if (marker.getTitle().equals("Alma & Cantor en Zweetkelder")) {
                      Intent AlmaIntent = new Intent(MapS.this, activity_acz.class);
                      startActivity(AlmaIntent);
                  }

                  else if (marker.getTitle().equals("IICK")) {
                      Intent IICKIntent = new Intent(MapS.this, activity_iick.class);
                      startActivity(IICKIntent);

                  }

                  else if (marker.getTitle().equals("Corona")) {
                      Intent coronaIntent = new Intent(MapS.this, activity_corona.class);
                      startActivity(coronaIntent);
                  }

                  else if (marker.getTitle().equals("Studentendorp")){
                      Intent studentendorpIntent = new Intent(MapS.this, activity_studentendorp.class);
                      startActivity(studentendorpIntent);
                  }

                  else if (marker.getTitle().equals("Spoelberg")) {
                      Intent spoelbergIntent = new Intent(MapS.this, activity_spoelberg.class);
                      startActivity(spoelbergIntent);
                  }

                  else if (marker.getTitle().equals("fietsene")) {
                      Intent fietseneIntent = new Intent(MapS.this, activity_fietsene.class);
                      startActivity(fietseneIntent);
                  }

                  else if (marker.getTitle().equals("IRF")) {
                      Intent IRFIntent = new Intent(MapS.this, activity_irf.class);
                      startActivity(IRFIntent);
                  }

                  else if (marker.getTitle().equals("Vaardigheidscentrum")) {
                      Intent vaardigheidscentrumIntent = new Intent(MapS.this, activity_vaardigheid.class);
                      startActivity(vaardigheidscentrumIntent);
                  }

                  else if (marker.getTitle().equals("Aula Andreas Vesalius (E1001)")) {
                      Intent E1001Intent = new Intent(MapS.this, activity_e1001.class);
                      startActivity(E1001Intent);
                  }

                  else if (marker.getTitle().equals("Gang 7")) {
                      Intent gang7Intent = new Intent(MapS.this, activity_kantoren.class);
                      startActivity(gang7Intent);
                  }

                  else if (marker.getTitle().equals("C611")) {
                      Intent C611Intent = new Intent(MapS.this, activity_c611.class);
                      startActivity(C611Intent);
                  }

                  else if (marker.getTitle().equals("puc")) {
                      Intent pucIntent = new Intent(MapS.this, activity_puc.class);
                      startActivity(pucIntent);
                  }

                  else if (marker.getTitle().equals("B422")) {
                      Intent B422Intent = new Intent(MapS.this, activity_b422.class);
                      startActivity(B422Intent);
                  }

                  else if (marker.getTitle().equals("Labo's (gang 3)")) {
                      Intent labosIntent = new Intent(MapS.this, activity_labo.class);
                      startActivity(labosIntent);
                  }

                  else if (marker.getTitle().equals("FietsenA")) {
                      Intent fietsenaIntent = new Intent(MapS.this, activity_fietsena.class);
                      startActivity(fietsenaIntent);
                  }

                  else if (marker.getTitle().equals("Weetkelder")) {

//                      LatLng lastKnownLatLng = new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude());
//                      final double distanceWeet = SphericalUtil.computeDistanceBetween(lastKnownLatLng, HalA);
//                      if (distanceWeet < 20) {
                      Intent weetkelderIntent = new Intent(MapS.this, activity_weetkelder.class);
                      startActivity(weetkelderIntent);
                  }

                  else if (marker.getTitle().equals("Aula Stijn Streuvels (A301)")) {
                      Intent A301Intent = new Intent(MapS.this, activity_A301.class);
                      startActivity(A301Intent);
                  }

                  else if (marker.getTitle().equals("Stille ruimte")) {
                      Intent stilIntent = new Intent(MapS.this, activity_stil.class);
                      startActivity(stilIntent);
                  }

                  else if (marker.getTitle().equals("Spina")) {
                      Intent spinaIntent = new Intent(MapS.this, activity_spina.class);
                      startActivity(spinaIntent);
                  }

                  else if (marker.getTitle().equals("Hal Rectoraat")) {
                      Intent rectoraatIntent = new Intent(MapS.this, activity_rectoraat.class);
                      startActivity(rectoraatIntent);
                  }

                  else if (marker.getTitle().equals("Acco boekenhandel")) {
                      Intent accoIntent = new Intent(MapS.this, activity_acco.class);
                      startActivity(accoIntent);
                  }

                  else if (marker.getTitle().equals("Bib")) {
                      Intent bibIntent = new Intent(MapS.this, activity_onthaalbib.class);
                      startActivity(bibIntent);
                  }

                  else if (marker.getTitle().equals("Stuvo")) {
                      Intent stuvoIntent = new Intent(MapS.this, activity_secstuvo.class);
                      startActivity(stuvoIntent);
                  }

                  else if (marker.getTitle().equals("Hal A")) {
                      if (distanceHala < 10){
                        Intent halaIntent = new Intent(MapS.this, hala.class);
                        startActivity(halaIntent);}}
                  return true;
              }
          }
        );













        if(mapView != null && mapView.findViewById(Integer.parseInt("1")) != null)  {
            View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            layoutParams.setMargins(0,0,40,180);

        }

        // kijken of gps signaal aanstaat
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setInterval(10000);
        locationRequest.setFastestInterval(5000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
        SettingsClient settingsClient = LocationServices.getSettingsClient(MapS.this);
        Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());
        task.addOnSuccessListener(MapS.this, new OnSuccessListener<LocationSettingsResponse>() {
            @Override
            public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                getDeviceLocation();
            }
        });

        task.addOnFailureListener(MapS.this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                if(e instanceof  ResolvableApiException) {
                    ResolvableApiException resolvable = (ResolvableApiException) e;
                    try{
                    resolvable.startResolutionForResult(MapS.this, 51);
                } catch (IntentSender.SendIntentException e1) {
                    e1.printStackTrace();
                }
            }
        }}





        );


    }
}

1 个答案:

答案 0 :(得分:0)

好的,所以您要做的是将变量设为类中的全局变量,以便其他方法可以访问它。 在此行的正下方:

public class MapS extends AppCompatActivity implements OnMapReadyCallback {

添加一行: private final double distanceHala;

然后,转到为distanceHala赋值的行:

final double distanceHala =SphericalUtil.computeDistanceBetween(lastKnownLatLng, HalA);

并将其更改为:- distanceHala =SphericalUtil.computeDistanceBetween(lastKnownLatLng, HalA);

就这样,它应该可以工作。 如果没有,请告诉我:)