【问题标题】:Desperately need to add directions to android project迫切需要向android项目添加方向
【发布时间】:2016-11-18 23:14:04
【问题描述】:

几天我一直在思考和上网,但是在大约 0 一周的工作效率之后,我决定问这个模糊的问题。我的问题 - 谁能告诉我如何在我的 android 项目中实施指示?

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

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

最后这是我的 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) {

    }
}

【问题讨论】:

  • @mastrgamr 哇!当我输入问题时,它没有弹出相关的问题,而且我之前找不到这个(显然是因为它发生在一小时前)。非常感谢!

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


【解决方案1】:

在 github 上查看这个库:

jd-alexander/Google-Directions-Android

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

乍一看,您在问题中的逻辑似乎是合理的,但为了限制搜索位置,我可能会在搜索框中获取任何查询并进行比较,看看它是否在您提供的指定 LatLngBounds 内。

【讨论】:

  • 您好,感谢您的快速回复。无法早点回复,因为我没想到会这么快回复(在永无止境的好咖啡搜索中AFK)!至于你的回答,我真的不明白 github 项目是关于什么的。我是否必须通过 maven 或 gradle 添加它以便易于使用?请给我的本心解释一下!
  • @Rainbowteddycoderguy 如果您在链接的页面上向下滚动一点,您可以找到有关如何使用它的说明。您通过 gradle 添加它,将 RoutingListener 添加到引用 GoogleMap 的类中,然后像本页所示那样处理它:github.com/jd-alexander/Google-Directions-Android/blob/master/…
  • 我已经向下滚动页面并理解了一些东西(抱歉我之前没有提到这一点)。如何指定路线必须经过的地方?
  • @Rainbowteddycoderguy 航点取 2 LatLnggithub.com/jd-alexander/Google-Directions-Android/blob/master/…
  • 一个qq..我在onCreate方法中实例化Routing对象吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-03
  • 2014-12-23
  • 1970-01-01
相关资源
最近更新 更多