【问题标题】:Calculating the distance between two markers in Android计算Android中两个标记之间的距离
【发布时间】:2016-03-25 06:47:54
【问题描述】:

对于我目前正在开发的应用程序,我想设置一个按钮,用于查找谷歌地图活动中两个标记之间的距离,当您单击该按钮时,它会显示您当前位置与另一个标记之间的距离 我的 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);

所以我只是想知道是否有人能够帮助我实现查找距离的代码,因为我不确定它应该在我的班级中的哪个位置,或者我是否必须重做班级的某​​些部分让距离发挥作用

【问题讨论】:

  • 使用DistanceMatrix。只需输入您的 OriginLatLng 和 DestinationLatLng 您将获得 JSON 格式的结果。
  • 你听说过距离公式吗?
  • 嗯,我去年大学毕业,我以前用java写过haversine公式的代码。我了解如何实际找到距离等,更重要的是实现它我遇到了麻烦。 IE。我在哪里放入我的 java 活动等

标签: java android android-studio


【解决方案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】:

    您好,我做了一个示例,它就像您的问题一样。但是您必须为您的构建进行自定义。您可以使用 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

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

    【讨论】:

    • 与问题无关。 OP 询问的是谷歌地图标记之间的距离,而不是排序的方式......无论如何,什么是正弦波?
    • 我告诉过你必须自定义。正弦波是一个对象。它有位置。如果你可以将正弦波更改为位置对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    相关资源
    最近更新 更多