akexorcist / GoogleDirectionLibrary

[Android] Library for Google Direction API for Google Maps Android API v2
Apache License 2.0
571 stars 174 forks source link

How do I know which marker has been clicked? #30

Closed yhznd closed 6 years ago

yhznd commented 7 years ago

First of all, thank you for gorgeous work.

I have a tiny issue. I'm adding many markers on my map. And I want to show route between user's current location and clicked marker location.

GoogleDirection.withServerKey(serverKey) .from(suanKonumumuz) .to(?) //What should I write here? .transportMode(TransportMode.DRIVING) .execute(this);

sagar-bhatt commented 7 years ago

Hey @yhaznedar,

Here is the working copy of the code snippet. Note - mMap is the GoogleMap object

mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
    @Override
    public void onMapClick(LatLng destination) {
        // if you wish to clear previous route
        mMap.clear();

        MarkerOptions sourceMarker = new MarkerOptions().position(suanKonumumuz);
        MarkerOptions destinationMarker = new MarkerOptions().position(destination);
        mMap.addMarker(sourceMarker);
        mMap.addMarker(destinationMarker);
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(destination, 12));

        GoogleDirection.withServerKey(serverKey)
            .from(suanKonumumuz)
            .to(destination)
            .transportMode(TransportMode.DRIVING)
            .execute(new DirectionCallback() {
                @Override
                public void onDirectionSuccess(Direction direction, String rawBody) {
                    if(direction.isOK()) {
                        try{
                            List<Step> stepList = direction.getRouteList().get(0).getLegList().get(0).getStepList();
                            ArrayList<PolylineOptions> polylineOptionList = DirectionConverter.createTransitPolyline(getActivity(), stepList, 5, Color.GREEN, 3, Color.BLUE);
                            for (PolylineOptions polylineOption : polylineOptionList) {
                                mMap.addPolyline(polylineOption);
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onDirectionFailure(Throwable t) {

                }
            });
    }
});

Hope it helps.

Best, Sagar

yhznd commented 7 years ago

Oh, I will try asap in my project. Thank you for guiding help,sir.