迫切需要为android项目添加方向

时间:2016-07-15 16:44:26

标签: android google-maps google-maps-markers google-maps-api-2 google-direction

我一直在思考和网上冲浪,但在 0 生产力一周后,我决定提出这个模糊的问题。我的问题 - 有人可以告诉我如何在我的android项目中实现方向吗?

详细说明,我在这里要求的确切功能将在下一段中突出显示。

我的项目的目标:每当用户键入一个位置(它会在点击后隐藏键盘),它将转到该位置并在那里放置一个标记。 然后它将显示当前位置和标记之间的最短旅行时间的路线。我不知道如何限制用户可以在其中搜索位置的国家/地区,但我很确定会放轻松。我已经拥有了我最终目标的点点滴滴,但并不是我真正想要的。

最后这是我的MainActivity。我已经引用了一些我没有在这里添加的类,所以,只需询问是否需要它们在您自己的编译器中运行此代码或其他:

public class MainActivity extends FragmentActivity
        implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    @SuppressWarnings("unused")
    private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9002;
    @SuppressWarnings("unused")
    private static final String LOGTAG = "Maps";

    private static final int GPS_ERRORDIALOG_REQUEST = 9001;
    private static final float DEFAULTZOOM = 15;
    private GoogleApiClient mGoogleApiClient;
    private LocationListener mListener;
    private Marker marker;

    ArrayList<LatLng> mMarkerPoints;
    GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (servicesOK()) {
            setContentView(R.layout.activity_main);

            if (initMap()) {
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                        .addApi(LocationServices.API)
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .build();
            } else {
                Toast.makeText(this, "Hmmm. Maps didn't load.", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "There's something wrong with your play services", Toast.LENGTH_SHORT).show();
        }

        UiSettings config = mMap.getUiSettings();
        config.setMapToolbarEnabled(false);
        config.setZoomControlsEnabled(false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.legal:
                Intent intent = new Intent(this, LicenseActivity.class);
                startActivity(intent);
                break;

            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MapStateManager mgr = new MapStateManager(this);
        CameraPosition position = mgr.getSavedCameraPosition();
        if (position != null) {
            CameraUpdate update = CameraUpdateFactory.newCameraPosition(position);
            mMap.moveCamera(update);
            mMap.setMapType(mgr.getSavedMapType());
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        MapStateManager mgr = new MapStateManager(this);
        mgr.saveMapState(mMap);
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    public boolean servicesOK() {
        int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

        if (isAvailable == ConnectionResult.SUCCESS) {
            return true;
        } else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
            dialog.show();
        } else {
            Toast.makeText(this, "Can't connect to Google Play services", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    private boolean initMap() {
        if (mMap == null) {
            MapFragment mapFrag =
                    (MapFragment) getFragmentManager().findFragmentById(R.id.map);
            mMap = mapFrag.getMap();
        }
        return (mMap != null);
    }

    @SuppressWarnings("unused")
    private void gotoLocation(double lat, double lng) {
        LatLng ll = new LatLng(lat, lng);
        CameraUpdate update = CameraUpdateFactory.newLatLng(ll);
        mMap.moveCamera(update);
    }

    private void gotoLocation(double lat, double lng,
                              float zoom) {
        LatLng ll = new LatLng(lat, lng);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
        mMap.moveCamera(update);
    }

    public void geoLocate(View v) throws IOException {

        EditText et = (EditText) findViewById(R.id.editText1);
        String location = et.getText().toString();
        if (location.length() == 0) {
            Toast.makeText(this, "Please enter a location", Toast.LENGTH_SHORT).show();
            return;
        }

        hideSoftKeyboard(v);

        Geocoder gc = new Geocoder(this);
        List<Address> list = gc.getFromLocationName(location, 1);
        Address add = list.get(0);
        String locality = add.getLocality();
        Toast.makeText(this, locality, Toast.LENGTH_LONG).show();

        double lat = add.getLatitude();
        double lng = add.getLongitude();

        gotoLocation(lat, lng, DEFAULTZOOM);

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

        MarkerOptions options = new MarkerOptions()
                .position(new LatLng(lat, lng));
        marker = mMap.addMarker(options);
    }

    private void hideSoftKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    public void showCurrentLocation(MenuItem item) {
        int permCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
        if (permCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            Location currentlocation = LocationServices.FusedLocationApi
                    .getLastLocation(mGoogleApiClient);
            if (currentlocation == null) {
                Toast.makeText(this, "Couldn't find you!", Toast.LENGTH_SHORT).show();
            } else {
                LatLng latlng = new LatLng(
                        currentlocation.getLatitude(),
                        currentlocation.getLongitude()
                );
                CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
                        latlng, 15
                );
                mMap.animateCamera(update);
            }
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        int permCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
        if (permCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            Toast.makeText(this, "Go go go!", Toast.LENGTH_SHORT).show();

            mListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    gotoLocation(location.getLatitude(), location.getLongitude(), 15);
                }
            };

            LocationRequest request = LocationRequest.create();
            request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            request.setInterval(20000);
            request.setFastestInterval(0);
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request, mListener
            );
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

1 个答案:

答案 0 :(得分:-1)

在github上查看这个库:

jd-alexander/Google-Directions-Android

我在我的项目中使用它,您可以克隆它并根据您的特定需求进行修改。

你在问题​​中的逻辑看起来似乎是乍一看,但是为了限制搜索位置,我可能只需要搜索框中的任何查询并进行比较,看它是否在你提供的指定LatLngBounds