Search code examples
androidgoogle-maps-api-3dialogitemizedoverlay

Android starting a google maps intent from within a dialog


I am using the google maps api with overlay items and want to be able to get directions when the user clicks these overlays.

I want this linked to the middle button of my dialog:

// Middle button
    dialog.setNeutralButton("Directions",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                    Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
                            Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
                    intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");

                    startActivity(intent);

                }
            });

I get the following error "The method startActivity(Intent) is undefined for the type new DialogInterface.OnClickListener(){}"

There are several answers to this on here but I cannot get any of them to work. I have tried both creating a constructor and calling getContext().

I am not sure if it is because my class is:

public class ItemizedOverlayLayoutActivity extends ItemizedOverlay {

Any help greatly appreciated.

Thanks


Solution

  • In the constructer of your class ItemizedOverlayLayoutActivity add a parameter Context:

    private Context context;
    public MyItemizedNewOverlay(Drawable defaultMarker, Context context) {
        //...
        this.context = context;
    }
    

    just before you create your dialog add:

    final Context fcontext = context;
    

    Then in the dialog middle button use:

    fcontext.startActivity(intent);
    

    good luck