簡體   English   中英

你如何計算你自己的位置和標記之間的距離,並讓它只有在足夠近的時候才能點擊?

[英]How can you calculate distance between your own location and a marker and make it only clickable when close enough?

因此,簡而言之,我們正在開發一款應用程序來引導新生在校園內參觀。 我們已經讓您可以單擊 map 上的所有標記(它們每個 go 到其相應的信息活動)。 現在我們希望用戶只有在距離該位置足夠近時才能單擊標記。 我們已經在變量mLastKnownLocation中獲得了用戶位置。 現在我做了一些研究,在SphericalUtil中有一個工具computeDistanceBetween() ,可以計算 2 點之間的距離。 但是現在我對如何實現這一點感到困惑? 當我們為所有的setOnMarkerClickListeners使用一個大的 If 語句時,我們是否需要在每個位置的大的 if 語句中獲取一個新的 if 語句,以檢查它們是否足夠接近或者是否有其他方法? 這是我們在 appdesign 中的第一個項目,使用 Java,因此完全有可能出現一些大錯誤。

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.os.Bundle;

import android.view.View;

import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.AutocompletePrediction;
import com.google.android.libraries.places.api.model.AutocompleteSessionToken;

import com.google.android.libraries.places.api.net.PlacesClient;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.kaart);
        mapFragment.getMapAsync(this);
        mapView = mapFragment.getView();

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapS.this);
        Places.initialize(MapS.this, ("My_APIkey"));





        final AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onMapReady(GoogleMap googleMap) {
        int height = 100;
        int width = 100;
        BitmapDrawable bitmapdraw=(BitmapDrawable)getResources().getDrawable(R.drawable.marker_dark);
        Bitmap b=bitmapdraw.getBitmap();
        Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);





        //All that LatLng are stated here, removed them for privacy reasons





        //Code die markers zet en ze klikbaar maakt.
        //Hal A
        googleMap.addMarker(new MarkerOptions().position(HalA)
                .title("Hal A")
                .icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        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(smallMarker)));

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

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

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

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

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

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

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

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

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


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


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

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

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

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

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

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

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

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

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

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

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

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

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

        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")) {
                      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")) {
                      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();
                }
            }
        }}





        );


    }


    @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(10000);
                                locationRequest.setFastestInterval(5000);
                                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();
                        }
                    }
                });
    }
}

SphericalUtil類的computeDistanceBetween(LatLng from, LatLng to)采用 LatLng 對象,因此首先您必須使用轉換已知位置和標記位置

LatLng knownLatLng = new LatLng(mKnownLocation.getLatitude(), mKnownLocation.getLongitude());

對標記Location object 重復此操作,或者如果它們尚不存在於您的代碼中,則使用其緯度和經度為每個標記實例化一個新的LatLng

要檢查用戶是否足夠近,您現在可以調用computeDistanceBetween方法來獲取距離,例如。

double distanceBetween = SphericalUtil.computeDistanceBetween(knownLatLng, markerLatLng);

然后修改您的 if 語句以包含第二個條件,例如。

if (marker.getTitle().equals("Ecolab")) {
    if (distanceBetween < 1) {

將檢查是否單擊了“Ecolab”標記,以及用戶是否在標記的一米范圍內。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM