[英]Google Maps: How to make a marker only clickable when the user is close enough?
[英]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.