I would like to find the distance in km between two markers how can I do?

Asked

Viewed 1,125 times

2

I have two markers in this code and I want to find the distance in miles between them.

private void setUpMap() {
    Database_Congregacao database_congregacao = new Database_Congregacao(this);
    int tamanho = 0;
    int size = 0;
    tamanho = database_congregacao.Buscar_Ultimas_Coordenadas().size() - 1;
    size = tamanho;

    Float lt = Float.parseFloat(latitude);
    Float lon = Float.parseFloat(longitude);
    String nome_congregacao = Activity_informacao_congregacao.this.getIntent().getExtras().getString("nome_congregacao");
    //Marker do LOcal do evento
    Marker marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lt,lon)).title(nome_congregacao).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker3)));

    //Marker da localizacao do usuario
    Marker marker2 = mMap.addMarker(new MarkerOptions().position(new LatLng(database_congregacao.Buscar_Ultimas_Coordenadas().get(size).getLatitude(),database_congregacao.Buscar_Ultimas_Coordenadas().get(size).getLongitude())).title("Minha Localização").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker5)));

    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lt, lon), 12));
    marker.showInfoWindow();
    marker2.showInfoWindow();
}

1 answer

2

As you ask just by the distance between two points, you can use distanceTo class Location. According to the documentation, it returns the approximate distance in meters between the two points.

So, to calculate in KM, something like this will help you:

public double calculaDistanciaEmKM(double lat1, double lon1, double lat2, double lon2) { 
    final Location start = new Location("Start Point"); 
    start.setLatitude(lat1); 
    start.setLongitude(lon1);

    final Location finish = new Location("Finish Point"); 
    finish.setLatitude(lat2); 
    finish.setLongitude(lon2); 
    final float distance = start.distanceTo(finish);

    return distance / 1000;
}

For detailed information on distance, traffic, etc., consider looking at the API Directions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.