0

I am trying to draw path from current location to destination using the answer Android: How to draw route directions google maps API V2 from current location to destination.

But in place of the hard coded I longitude and Latitude of the current location I want to use my real location. But whenever I try to do that, the App is crashing with error in line location = mMap.getMyLocation();

Any help is appreciated.

MapsActivity.Java

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    Location location;
    LatLng myPosition;
    GMapV2Direction md;

    LatLng fromPosition = getYourLocation();
    LatLng toPosition = new LatLng(13.683660045847258, 100.53900808095932);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        md = new GMapV2Direction();
        setUpMapIfNeeded();
        LatLng coordinates = new LatLng(13.685400079263206, 100.537133384495975);
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));

        mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
        mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));

        Document doc = md.getDocument(fromPosition, toPosition, 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);
    }


    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever

     * <p/>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p/>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    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) {
                /*myPosition = getLocation();
                ZoomCurrentLocation(myPosition);*/
            }
        }
    }

    private LatLng getYourLocation() {
        mMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);
        double latitude = 0;
        double longitude = 0;
        if (location != null) {
            // Getting latitude of the current location
            latitude = location.getLatitude();

            // Getting longitude of the current location
            longitude = location.getLongitude();

            // Creating a LatLng object for the current location

        }
        LatLng latLng = new LatLng(latitude, longitude);
        return latLng;
    }


    private void ZoomCurrentLocation(LatLng myPosition)
    {
        mMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);

        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 16));
    }



    private void setUpMap(LatLng myPosition) {
        mMap.addMarker(new MarkerOptions().position(myPosition).title("Marker"));
    }
}
Community
  • 1
  • 1
bazinga
  • 2,120
  • 4
  • 21
  • 35
  • Do you mean `location = mMap.getMyLocation();` is the method `getYourLocation()` in the code, and the crash is at `Location location = locationManager.getLastKnownLocation(provider);` ? – bjiang Apr 08 '15 at 00:08
  • Follow the given three links : http://wptrafficanalyzer.in/blog/driving-route-from-my-location-to-destination-in-google-maps-android-api-v2/ http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/ http://wptrafficanalyzer.in/blog/route-between-two-locations-with-waypoints-in-google-map-android-api-v2/ – Anoop M Maddasseri Apr 08 '15 at 06:08

1 Answers1

0

Do you mean location = mMap.getMyLocation(); is the method getYourLocation() in the code, and the crash is at Location location = locationManager.getLastKnownLocation(provider); ?

If so, it may cause by NullPointer Exception, you need use new api FusedLocationApi to avoid getLastLocation null pointer.

Please check here to know how to use it. And here is the code for it on my github.

For the destination you can check here to get some idea.

enter image description here

bjiang
  • 6,068
  • 2
  • 22
  • 35
  • Thanks for the answer, but is there any way by which I can also find the estimated time to travel between those two points and distance between them? – bazinga Apr 09 '15 at 05:27
  • Sure, please check out [here](http://wptrafficanalyzer.in/blog/driving-distance-and-travel-time-duration-between-two-locations-in-google-map-android-api-v2/), [here](http://stackoverflow.com/questions/18310126/get-the-distance-between-two-locations-in-android) and [here](http://stackoverflow.com/questions/22351984/how-to-find-the-distance-between-two-points-along-a-specific-route) – bjiang Apr 09 '15 at 05:32
  • why it opens google maps when I click on Directions? Cant it show the path on the that activity itself? – bazinga Apr 09 '15 at 05:47