如何从当前位置到目的地绘制路线方向

时间:2013-03-18 04:02:57

标签: java android google-maps

如何使用google maps api v2从当前位置到目的地绘制路线方向?  我想从我的位置画到我的目的地。 这是我的第一个应用程序,请帮助我..

这是我的代码:

`public class Trazo_Rutas extends FragmentActivity implements 
    OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

private GoogleMap mMap;
GoogleApiClient googleApiClient;
LocationRequest locationRequest;
Location lastLocation;
Marker userLocation;
private static final int Request_User_Location_Code = 99;
PlaceAutocompleteFragment placeAutoComplete;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_trazo__rutas);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkUserLocationPermission();
    }

    //Check if Google Play Services Available or not
    if (!CheckGooglePlayServices()) {
        Log.d("onCreate", "Finishing test case since Google Play Services are not available");
        finish();
    }
    else {
        Log.d("onCreate","Google Play Services available.");
    }

    //AutoComplete search bar
    placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
    placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {

            Log.d("Maps", "Place selected: " + place.getName());
        }

        @Override
        public void onError(Status status) {
            Log.d("Maps", "An error occurred: " + status);
        }
    });

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

private boolean CheckGooglePlayServices() {
    GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
    int result = googleAPI.isGooglePlayServicesAvailable(this);
    if(result != ConnectionResult.SUCCESS) {
        if(googleAPI.isUserResolvableError(result)) {
            googleAPI.getErrorDialog(this, result,
                    0).show();
        }
        return false;
    }
    return true;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.getUiSettings().setZoomControlsEnabled(true);

    //get latlong for corners for specified place
    LatLng corner1 = new LatLng(25.64379, -103.60966);
    LatLng corner2 = new LatLng(25.64317, -103.20935);
    LatLng corner3 = new LatLng(25.43872, -103.61104);
    LatLng corner4 = new LatLng(25.43748, -103.20866);

    LatLngBounds.Builder builder = new LatLngBounds.Builder();

    builder.include(corner1);
    builder.include(corner2);
    builder.include(corner3);
    builder.include(corner4);

    LatLngBounds bounds = builder.build();

    //add them to builder
    int width = getResources().getDisplayMetrics().widthPixels;
    int height = getResources().getDisplayMetrics().heightPixels;

    // 20% padding
    int padding = (int) (width * 0.20);

    //set latlng bounds
    mMap.setLatLngBoundsForCameraTarget(bounds);

    //move camera to fill the bound to screen
    mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));

    //set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
    mMap.setMinZoomPreference(mMap.getCameraPosition().zoom);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    } else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

}

public boolean checkUserLocationPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){
            ActivityCompat.requestPermissions(this, new String[] {
                    Manifest.permission.ACCESS_FINE_LOCATION
            }, Request_User_Location_Code);
        } else {
            ActivityCompat.requestPermissions(this, new String[] {
                    Manifest.permission.ACCESS_FINE_LOCATION
            }, Request_User_Location_Code);
        }

        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case Request_User_Location_Code:

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    if (googleApiClient == null) {
                        buildGoogleApiClient();
                    }

                    mMap.setMyLocationEnabled(true);
                }
            } else {
                Toast.makeText(this, "Se requieren Permisos de Google", Toast.LENGTH_SHORT).show();
                finish();
            }

            return;
    }
}

protected synchronized void buildGoogleApiClient() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    googleApiClient.connect();
}


@Override
public void onLocationChanged(Location location) {
    lastLocation = location;

    if (userLocation != null) {
        userLocation.remove();
    }

    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.draggable(true);
    markerOptions.title("Tu ubicación");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

    userLocation = mMap.addMarker(markerOptions);

    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));

    if (googleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    locationRequest = new LocationRequest();
    locationRequest.setInterval(1100);
    locationRequest.setFastestInterval(1100);
    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }

}`

此代码仅用于添加标记..如何从当前位置绘制方向到目的地..谢谢..

1 个答案:

答案 0 :(得分:1)

有多种方法可以做到这一点..

  • 使用浏览器,传递来源和目的地

    public void showDirections(View view) {
      final Intent intent = new  Intent(Intent.ACTION_VIEW,Uri.parse("http://maps.google.com/maps?" + "saddr="+ latitude + "," + longitude + "&daddr=" + latitude + "," + longitude));
    intent.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity");
    startActivity(intent);
    }
    
  • 在地图中使用投影请参阅How to draw straight path between two points。它不是你问题的完美解决方案,但你会明白的。