android - 在 android 中使用 Place Autocomplete 实现 Google Maps Directions API

标签 android google-maps google-places-api google-maps-android-api-2

我已经在本教程的帮助下实现了 Google Maps Directions API https://github.com/hiepxuan2008/GoogleMapDirectionSimple/tree/master/app/src/main/java/Modules 其中两个 EditText 字段用于 Origin 和 Destination 但这看起来有点困惑,当有两个同名的地方时有时会给出错误的方向。后来我发现有地方自动完成功能。所以,我的问题是我是否可以修改现有代码以获取位置自动完成而不是 EditText,或者我应该重新开始。如果可能,我该怎么做?

public class MapViewFragment extends Fragment implements OnMapReadyCallback, DirectionFinderListener {


    private Button btnFindPath;
    private EditText etOrigin;
    private EditText etDestination;
    private ProgressDialog progressDialog;

    private List<Marker> originMarkers = new ArrayList<>();
    private List<Marker> destinationMarkers = new ArrayList<>();
    private List<Polyline> polylinePaths = new ArrayList<>();


    GoogleMap mGoogleMap;
    MapView mMapView;
    View mView;




    public MapViewFragment() {
        // Required empty public constructor
    }

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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mView = inflater.inflate(R.layout.fragment_map_view, container, false);
        btnFindPath = (Button) mView.findViewById(R.id.btnFindPath);
        etOrigin = (EditText) mView.findViewById(R.id.etOrigin);
        etDestination = (EditText) mView.findViewById(R.id.etDestination);

        btnFindPath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequest();
            }
        });



        return mView;
    }

    private void sendRequest() {
        String origin = etOrigin.getText().toString();
        String destination = etDestination.getText().toString();
        if (origin.isEmpty()) {
            Toast.makeText(getActivity(), "Please enter origin address!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (destination.isEmpty()) {
            Toast.makeText(getActivity(), "Please enter destination address!", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            new DirectionFinder(this, origin, destination).execute();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }



    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mMapView = (MapView) mView.findViewById(R.id.map);
        if (mMapView != null){
            mMapView.onCreate(null);
            mMapView.onResume();
            mMapView.getMapAsync(this);

        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        MapsInitializer.initialize(this.getActivity());
        mGoogleMap = googleMap;
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.addMarker(new MarkerOptions().position(new LatLng(27.717245, 85.323960)).title("Yo ho Kathmandu University") .snippet("I study Here"));
        CameraPosition Liberty = CameraPosition.builder().target(new LatLng(27.717245, 85.323960)).zoom(16).bearing(0).tilt(45).build();
        googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(Liberty));

        googleMap.setMyLocationEnabled(true);


    }


    @Override
    public void onDirectionFinderStart() {
        progressDialog = ProgressDialog.show(getActivity(), "Please wait.",
                "Finding direction..!", true);

        if (originMarkers != null) {
            for (Marker marker : originMarkers) {
                marker.remove();
            }
        }

        if (destinationMarkers != null) {
            for (Marker marker : destinationMarkers) {
                marker.remove();
            }
        }

        if (polylinePaths != null) {
            for (Polyline polyline:polylinePaths ) {
                polyline.remove();
            }
        }
    }

    @Override
    public void onDirectionFinderSuccess(List<Route> routes) {
        progressDialog.dismiss();
        polylinePaths = new ArrayList<>();
        originMarkers = new ArrayList<>();
        destinationMarkers = new ArrayList<>();

        for (Route route : routes) {
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
            ((TextView) getView().findViewById(R.id.tvDuration)).setText(route.duration.text);
            ((TextView) getView().findViewById(R.id.tvDistance)).setText(route.distance.text);

            originMarkers.add(mGoogleMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_media_pause))
                    .title(route.startAddress)
                    .position(route.startLocation)));
            destinationMarkers.add(mGoogleMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_media_play))
                    .title(route.endAddress)
                    .position(route.endLocation)));

            PolylineOptions polylineOptions = new PolylineOptions().
                    geodesic(true).
                    color(Color.BLUE).
                    width(10);

            for (int i = 0; i < route.points.size(); i++)
                polylineOptions.add(route.points.get(i));

            polylinePaths.add(mGoogleMap.addPolyline(polylineOptions));
        }
    }
}

最佳答案

etOrigin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            findPlace();
        }
    });
etDestination.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            findPlace2();
        }
    });

private void findPlace2() {
    try {
        Intent intent = new PlaceAutocomplete
                .IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                .build(this);
        startActivityForResult(intent, 2);
    } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
        // TODO: Handle the error.
    }
}

private void findPlace() {
    try {
        Intent intent = new PlaceAutocomplete
                .IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                .build(this);
        startActivityForResult(intent, 1);
    } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
        // TODO: Handle the error.
    }
}

// A place has been received; use requestCode to track the request.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if (resultCode == RESULT_OK) {
            // retrive the data by using getPlace() method.
            Place place = PlaceAutocomplete.getPlace(this, data);
            Log.e("Tag", "Place: " + place.getAddress() + place.getPhoneNumber());

            ((EditText) findViewById(R.id.etLokasiAwal))
                    .setText(place.getName());

        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(this, data);
            // TODO: Handle the error.
            Log.e("Tag", status.getStatusMessage());

        } else if (resultCode == RESULT_CANCELED) {
            // The user canceled the operation.
        }
    } else if (requestCode == 2) {
        if (resultCode == RESULT_OK) {
            // retrive the data by using getPlace() method.
            Place place = PlaceAutocomplete.getPlace(this, data);
            Log.e("Tag", "Place: " + place.getAddress() + place.getPhoneNumber());

            ((EditText) findViewById(R.id.etLokasiAkhir))
                    .setText(place.getName());

        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(this, data);
            // TODO: Handle the error.
            Log.e("Tag", status.getStatusMessage());

        } else if (resultCode == RESULT_CANCELED) {
            // The user canceled the operation.
        }
    }
}

希望对你有帮助

并确保在您的编辑文本中设置 android:focusable="false"

关于android - 在 android 中使用 Place Autocomplete 实现 Google Maps Directions API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44886265/

相关文章:

javascript - Angular 2 : Multiple included error

javascript - Google Places API 中具有关联 html_attributions 的地点或 place_id(用于测试目的)是什么?

android - 加载内置应用程序后选项卡消失

android - 在 Google Drive API 中重复上传所需的 MIME 类型吗?

java - 地点自动完成未找到类 "com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable"

android - Google Places Api 按距离排序

google-places-api - 如何使用文本搜索通过 google place api 按距离对结果进行排序

android - AppBarLayout + TabLayout + CollapsingToolbarLayout + SwipeToRefresh

java - 通过 Intent 传递 Bundle

javascript - 需要从google map API获取纬度和经度