Location reset in Android Maps API

Asked

Viewed 51 times

0

My code creates a route between two points on the map at the coordinates I am trying to pass from the coordinate of my current location to fromPosition, using the low code. But he’s giving 0.0 on Log. i;

double lat;
double lng;

LatLng fromPosition = new LatLng(lat, lng);
LatLng toPosition = new LatLng(-5.082434, -42.807364);

But I need the co-penned fromPosition to be my current position.

Thanks for any help.

public class MapsActivity2 extends FragmentActivity  {

private GoogleMap map;

double lat;
double lng;

LatLng fromPosition = new LatLng(lat, lng);
LatLng toPosition = new LatLng(-5.082434, -42.807364);

ArrayList<LatLng> directionPoint;
Marker mPositionMarker;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps2);
    initializeMap();

    Log.i("david", "LATLNG= " + fromPosition);

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    long tempo = 1000; //5 minutos
    float distancia = 1; // 30 metros

    map.setMyLocationEnabled(true);



    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER , tempo , distancia,  new LocationListener() {


        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {

        }

        @Override
        public void onProviderEnabled(String arg0) {
            Toast.makeText(getApplicationContext(), "GPS Habilitado", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onProviderDisabled(String arg0) {
            Toast.makeText(getApplicationContext(), "GPS Desabilitado", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onLocationChanged(Location location) {
            if (location == null)
                return;

             map.setMyLocationEnabled(true);

             lat = location.getLatitude();
             lng = location.getLongitude();


            map.moveCamera(CameraUpdateFactory.newLatLngZoom(new
                    LatLng(lat, lng), 16));

            if (mPositionMarker == null) {

                mPositionMarker = map.addMarker(new MarkerOptions()
                        .flat(true)
                        .icon(BitmapDescriptorFactory
                                .fromResource(R.drawable.car))
                        .anchor(0.5f, 0.5f)
                        .position(
                                new LatLng(location.getLatitude(), location
                                        .getLongitude())));
            }


            animateMarker(mPositionMarker, location); // Helper method for smooth
            // animation

            map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));

        }


        public void animateMarker(final Marker marker, final Location location) {
            final Handler handler = new Handler();
            final long start = SystemClock.uptimeMillis();
            final LatLng startLatLng = marker.getPosition();
            final double startRotation = marker.getRotation();
            final long duration = 500;

            final Interpolator interpolator = new LinearInterpolator();

            handler.post(new Runnable() {
                @Override
                public void run() {
                    long elapsed = SystemClock.uptimeMillis() - start;
                    float t = interpolator.getInterpolation((float) elapsed
                            / duration);

                    double lng = t * location.getLongitude() + (1 - t)
                            * startLatLng.longitude;
                    double lat = t * location.getLatitude() + (1 - t)
                            * startLatLng.latitude;

                    float rotation = (float) (t * location.getBearing() + (1 - t)
                            * startRotation);

                    marker.setPosition(new LatLng(lat, lng));
                    marker.setRotation(rotation);

                    if (t < 1.0) {
                        // Post again 16ms later.
                        handler.postDelayed(this, 16);
                    }
                }
            });
        }
    }, null);
}

private void initializeMap() {
    if (map == null) {
        map = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map)).getMap();



        new WebserviceTask(this).execute();





    }
}


public void setDirectionPoints(ArrayList<LatLng> result) {
    directionPoint = new ArrayList<LatLng>();
    directionPoint = result;
}

protected void onResume() {
    super.onResume();
    initializeMap();
}

public class WebserviceTask extends
        AsyncTask<Void, Void, ArrayList<LatLng>> {
    MapsActivity2 mContext;
    PolylineOptions rectline;

    public WebserviceTask(MapsActivity2 context) {
        this.mContext = context;
    }

    @Override
    protected void onPostExecute(ArrayList<LatLng> result) {
        super.onPostExecute(result);
        if (result != null) {
            rectline = new PolylineOptions().width(10).color(Color.BLUE);

            for (int i = 0; i < result.size(); i++)
                rectline.add(result.get(i));
            map.addPolyline(rectline);
        }
    }

    @Override
    protected ArrayList<LatLng> doInBackground(Void... params) {
        GMapV2Direction md = new GMapV2Direction();
        Document doc = md.getDocument(fromPosition, toPosition,
                GMapV2Direction.MODE_DRIVING);
        if (doc != null) {
            ArrayList<LatLng> directionPoint = md.getDirection(doc);

            rectline = new PolylineOptions().width(10).color(Color.RED);

            for (int i = 0; i < directionPoint.size(); i++)
                rectline.add(directionPoint.get(i));

            return directionPoint;
        } else
            return null;
    }

}

}

1 answer

1

In this section of your method

public void onLocationChanged(Location location) {
    if (location == null)
        return;

     map.setMyLocationEnabled(true);

     lat = location.getLatitude();
     lng = location.getLongitude();
}

you arrow the new lat and lng, but never a new fromLocation, ie it will always stay with 0,0;

  • can exemplify the code please? I searched on Google and found nothing on it.

  • But this chunk of code I took from your own, there at the beginning: Latlng fromPosition = new Latlng(lat, lng); this fromPosition variable is never filled with the correct lat/lng value that you take in the onLocationChanged method. You urged it the way above.

Browser other questions tagged

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