0

i wrote a class, which gets my current location when i press button, and get other points from other class to draw a route. In case I don't pass my current location address, it should get my current location, and draw route from current location. I cant find the way to get my current location LatLng. How may i get it ? Here is my class : btw, im new in android programing, so code is not very good YET :)

public class MyLocationDemoActivity extends FragmentActivity implements
        ConnectionCallbacks, OnConnectionFailedListener, LocationListener,
        OnMyLocationButtonClickListener {
    GMapV2Direction md;
    private GoogleMap mMap;
    GeoPoint gp;
    private LocationClient mLocationClient;
    private TextView mMessageView;
    Bundle extras;
    Location mycurrent;
    // These settings are the same as the settings for the map. They will in
    // fact give you updates
    // at the maximal rates currently possible.
    private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(5000) // 5 seconds
            .setFastestInterval(16) // 16ms = 60fps
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_location_demo);
        Intent intent = getIntent();
        RouteActivity route = new RouteActivity();
        // if (route.myAddress.isEmpty()) {
        // System.out.println(" 60 line ");
        // } else {
        // mMap = ((SupportMapFragment) getSupportFragmentManager()
        // .findFragmentById(R.id.map)).getMap();
        extras = getIntent().getExtras();
        LatLng a = null;
        try {
            a = (LatLng) extras.get("coord");
        } catch (Exception x) {
        }
        if (a == null) {
            try {
                System.out.println();
                /*//if (mLocationClient != null && mLocationClient.isConnected()) {
                LocationManager locManager;

                locManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
                                //idetas
                locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
                    500.0f, locationListener);
                Location location = locManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                }
                */
                //}
                LatLng x = new LatLng(mycurrent.getLatitude(),
                        mycurrent.getLongitude());
                a = x;
                System.out.print(a);
            } catch (Exception x) {

            }

            System.out.print(a);
        }
        LatLng b ;
        try{
        b = (LatLng) extras.get("Obj1");

        draw_route(a, b);
        }catch(Exception e){

        }

        LatLng c = null;
        try {
            c = (LatLng) extras.get("Obj2");
            b = (LatLng) extras.get("Obj1");
            draw_route(b, c);

        } catch (Exception e) {
            System.out.println("smth went wrong");
        }
        try {
            LatLng d = (LatLng) extras.get("Obj3");

            draw_route(c, d);

        } catch (Exception e) {
            System.out.println("smth went wrong");
        }

        // mMap.addMarker(new MarkerOptions().position(a));

        mMap.setMyLocationEnabled(true);
        mMap.setOnMyLocationButtonClickListener(this);

        // }
        // if (!route.ObjLoc1String.isEmpty()) {

    }

    // }

    private final LocationListener locationListener = new LocationListener() {

        public void onLocationChanged(Location location) {
            updateWithNewLocation(location);
        }

        public void onProviderDisabled(String provider) {
            updateWithNewLocation(null);
        }

        public void onProviderEnabled(String provider) {}

        public void onStatusChanged(String provider,int status,Bundle extras){}
    };
    private void updateWithNewLocation(Location location) {
       // TextView myLocationText = (TextView) findViewById(R.id.text);
        String latLongString = "";
        if (location != null) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            latLongString = "Lat:" + lat + "\nLong:" + lng;
        } else {
            latLongString = "No location found";
        }
       // myLocationText.setText("Your Current Position is:\n" + latLongString);
    }
    private void setUpLocationClientIfNeeded() {
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
                    this); // OnConnectionFailedListener
        }
    }

    public void draw_route(LatLng start, LatLng finish) {
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        md = new GMapV2Direction();
        mMap = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map)).getMap();

        LatLng coordinates = new LatLng(54.72, 25.3);
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 10));

        mMap.addMarker(new MarkerOptions().position(start).title("Start"));
        mMap.addMarker(new MarkerOptions().position(finish).title("End"));

        Document doc = md.getDocument(start, finish,
                GMapV2Direction.MODE_DRIVING);
        int duration = md.getDurationValue(doc);
        String distance = md.getDistanceText(doc);
        String start_address = md.getStartAddress(doc);
        String copy_right = md.getCopyRights(doc);

        ArrayList<LatLng> directionPoint = md.getDirection(doc);
        PolylineOptions rectLine = new PolylineOptions().width(3).color(
                Color.RED);

        for (int i = 0; i < directionPoint.size(); i++) {
            rectLine.add(directionPoint.get(i));
        }

        mMap.addPolyline(rectLine);
    }

    /**
     * Button to get current Location. This demonstrates how to get the current
     * Location as required without needing to register a LocationListener.
     */
    public void showMyLocation(View view) {
        if (mLocationClient != null && mLocationClient.isConnected()) {
            String msg = "Location = " + mLocationClient.getLastLocation();
            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT)
                    .show();
            mycurrent = mLocationClient.getLastLocation();
        }
    }

    /**
     * Implementation of {@link LocationListener}.
     */
    @Override
    public void onLocationChanged(Location location) {
        mMessageView.setText("Location = " + location);
    }

    /**
     * Callback called when connected to GCore. Implementation of
     * {@link ConnectionCallbacks}.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        mLocationClient.requestLocationUpdates(REQUEST, this); // LocationListener
    }

    /**
     * Callback called when disconnected from GCore. Implementation of
     * {@link ConnectionCallbacks}.
     */
    @Override
    public void onDisconnected() {
        // Do nothing
    }

    /**
     * Implementation of {@link OnConnectionFailedListener}.
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Do nothing
    }

    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT)
                .show();
        // Return false so that we don't consume the event and the default
        // behavior still occurs
        // (the camera animates to the user's current position).
        return false;
    }
}
user3416113
  • 61
  • 1
  • 10

1 Answers1

0
public void onLocationChanged(Location location) {
    mMessageView.setText("Location = " + location);
    draw_route(new LatLng(location.getLatitude(), location.getLongitude()), new LatLng( ... point where should be the end of route ...));
}

I dont know if I understood correctly, but it seems, that You should call draw_route and get LatLng from location which is passed to onLocationChanged event. This is starting point. Further, You have some end point which is passed as LatLng as second parameter to draw_route. In draw route, if You want to get correct route, use Google Directions service using passed parameters coordinates and after receiving data, You will get all points in route and also You will be able to draw correct polyline.

dpitkevics
  • 1,238
  • 8
  • 12
  • See answers in this question: http://stackoverflow.com/questions/16262837/how-to-draw-route-in-google-maps-api-v2-from-my-location – dpitkevics Apr 03 '14 at 10:19