Android maps measure distances and being close to make a change


I'm doing a game on android with maps. I have 3 key points that are to be reached, each point has its marker and its coordinates, this works well, now what I do not get is that when I am a few meters away from one of the marker I stop the music in the background that I have and another one starts, who says music says something else.

I put you as I have a marker:

    LatLng latLng = new LatLng(42.237439, -8.714226);
    int radius = 10;

    CircleOptions circleOptions = new CircleOptions()
    Circle circle = mMap.addCircle(circleOptions);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));

    mMap.addMarker(new MarkerOptions()
            .title("Mision 1.")
            .snippet("Fundador: user")        

    Location location1p = new Location("mision1");
    distancia1 = locationGPS.distanceTo(location1p);
    lblPista.setText("Mts a mision1: "+distancia1);

distance1 is declared as float in the main

As you can see I have declared the marker with its circle and the distanceTo () that would be to determine from my current position how much would remain to reach that point in meters I suppose. If I do a method with an if saying "if distance1 is less than or equal to 10 for the background music and plays this":

private void localizacionPistas() {

    if(distancia1 <= 10){

What is wrong so that it does not work?

asked by Pedro 16.01.2018 в 20:31

1 answer


Ok, I discovered the problem. You can not use Location alone, you must use the LocationListener. What I did was to use the LocationListener of the methods that were returning my position on the map via GPS:

This is a method that tells you 20 meters away from the marker, changes the sound of the app and if it is more than 10 meters away from that sound:

private void distancia_a_puntoA(Location localitation) {
    distancia1 = localitation.distanceTo(location1);
    lblPanda.setText(("Mts a Punto A: " + distancia1));
    if (localitation.distanceTo(locationa) <= metroscerca) {
    } else if (localitation.distanceTo(locationa) > metroslejos) {

// Here would be where we have to add the method so that distances work correctly

LocationListener locListener = new LocationListener(){
    public void onLocationChanged(Location location) {

        distancia_a_puntoA(location); //este es el método de arriba

        Log.i(TAG, "Lat " + location.getLatitude() + " Long " + location.getLongitude());
        lblLatitud.setText(("Lat: " +   location.getLatitude()));
        lblLongitud.setText(("Long: " + location.getLongitude()));

    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.i(TAG, "onProviderDisabled()");


    public void onProviderEnabled(String provider) {
        Log.i(TAG, "onProviderDisabled()");


    public void onProviderDisabled(String provider) {
        Log.i(TAG, "onProviderDisabled()");

answered by 02.02.2018 / 21:51