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

时间:2015-12-18 14:18:27

标签: java android android-studio

对于我目前正在处理的应用,我想设置一个按钮,找到谷歌地图活动中两个标记之间的距离,当您点击该按钮时,它会显示当前位置与另一个标记之间的距离 我的java类中没有任何代码用于按钮,但此刻我只是想知道我是如何找到当前位置和我的设置标记之间的距离。这是我查找用户当前位置的代码,它在随机位置设置了标记。

package dashpage.example.com.myapplication;

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

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.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 个答案:

答案 0 :(得分:2)

在尝试查找标记之间的距离时,我建议将它们转换回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); 或已保存且当前位置 <form action="" method=""> <!-- Name containing only letters or _ --> Name: <input type="text" name="name" pattern="[a-zA-Z][[A-Za-z_]+" /> <!-- using type email, will validate the email format for you--> Email: <input type="email" id="email" /> <input type="submit" value="Submit"> </form> 具有访问权限}:

 public static void SendEmailsTask(List<string> emails)
                {
                    BackgroundTaskRunner.FireAndForgetTask(async () =>
                    {
                        for (int i = 0; i < emails.Count; i++)
                        {
                            BL.funcs.SendEmail(emails[i]);
                            if (i%4 == 0)
                            {                              
                                    await Task.Delay(10000);    
                            }
                        }
                    });
                }            
     public static class BackgroundTaskRunner
            {
                public static void FireAndForgetTask(Action action)
                {


HostingEnvironment.QueueBackgroundWorkItem(cancellationToken =>
                    {
                        try
                        {
                            action();
                        }
                        catch (Exception e)
                        {
                            // TODO: handle exception
                        }
                    });
                }       
                public static void FireAndForgetTask(Func<Task> action)
                {

答案 1 :(得分:0)

  

您好我做了一个例子,它就像您的qquestion.But您必须自定义您的构建。您可以使用Collections类。它简单而完美的工作。

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

            }
        };
        Collections.sort(sinemalarList, comparator);
  

我希望为你工作

 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

  

这里有完整的代码,你可以在这里使用。我忘了。