有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计算Android中两个标记之间的距离

对于我目前正在开发的应用程序,我想设置一个按钮,用于查找google maps活动中两个标记之间的距离,当您单击该按钮时,它会显示您当前位置与另一个标记之间的距离 我的java类中还没有关于按钮的任何代码,但目前我只是想知道如何找到当前位置和设置标记之间的距离。这是我查找用户当前位置的代码,它在随机位置设置了一个标记

package dashpage.example.com.myapplication;

import 安卓.content.IntentSender;
import 安卓.location.Location;
import 安卓.os.Bundle;
import 安卓.support.v4.app.FragmentActivity;
import 安卓.util.Log;

import com.google.安卓.gms.common.ConnectionResult;
import com.google.安卓.gms.common.api.GoogleApiClient;
import com.google.安卓.gms.location.LocationListener;
import com.google.安卓.gms.location.LocationRequest;
import com.google.安卓.gms.location.LocationServices;
import com.google.安卓.gms.maps.CameraUpdateFactory;
import com.google.安卓.gms.maps.GoogleMap;
import com.google.安卓.gms.maps.SupportMapFragment;
import com.google.安卓.gms.maps.model.LatLng;
import com.google.安卓.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    public static final String TAG = MapsActivity.class.getSimpleName();

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

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

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds



    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(53.3835, 6.5996)).title("Marker"));
    }

    private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());

        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();

        LatLng latLng = new LatLng(currentLatitude, currentLongitude);

        //mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title("I am here!");
        mMap.addMarker(options);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }
}

我还知道,在Android Studio中,为了找到两个标记之间的距离,您可以使用以下内容

Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lon1);

Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);

float distanceInMeters = loc1.distanceTo(loc2);

所以我只是想知道是否有人能帮我实现寻找距离的代码,因为我不确定它应该放在我的课堂上的什么地方,或者我是否需要重做课堂上的一些部分来实现距离


共 (2) 个答案

  1. # 1 楼答案

    当试图找到标记之间的距离时,我建议将它们转换回Location对象,以便能够使用内置的Android方法计算距离

    考虑到一些Marker marker您已经设置并通过onMarkerClick()访问,或者已经保存并处于当前位置Location currentLocation,在onClick(View v)方法中Button

    LatLng markerLatLng = marker.getPosition();
    Location markerLocation = new Location("");
    markerLocation.setLatitude(markerLatLng.latitude);
    markerLocation.setLongitude(markerLatLng.longitude);
    
    currentLocation.distanceTo(markerLocation);
    
  2. # 2 楼答案

    Hi I made an example and its like your qquestion.But you must customise for your build.You can use Collections class.Its easy and perfectly work.

       Comparator<Sinemalar> comparator=new Comparator<Sinemalar>() {
                @Override
                public int compare(Sinemalar left, Sinemalar right) {
                    return (int)(left.getDistance()-right.getDistance());
    
                }
            };
            Collections.sort(sinemalarList, comparator);
    

    I hope work for you

     public float distanceCounter(String value, Context context) {
        Location cinemaLocation = new Location("CinemaLocation");
        String s = new String(value);
        String[] result = s.split(",");
        List<String> elephantList = Arrays.asList(s.split(","));
        String longitude = elephantList.get(1);
        String latitude = elephantList.get(0);
        cinemaLocation.setLatitude(Double.parseDouble(latitude));
        cinemaLocation.setLongitude(Double.parseDouble(longitude));
    
     float distance = getCurrrentLocation(context).distanceTo(cinemaLocation)/1000 ;
    
        return distance;
    }
    

    字符串值=34.54665,23.54546

    Full code here you can use with here.Sory i forgot.