androidgoogle-mapsandroid-alertdialoggoogle-maps-api-2geocode

How to use an alert dialog to search for an address in google maps api v2?


I've made an AlertDialog with an EditText, and I want that when the user clicks on 'Buscar' (positiveButton) the map shows a Marker in the address entered on the AlertDialog. So I think I need to pass the data from this EditText to the MapFragment in order to use the Geocoder with that data.

Here's my mainActivity.java with the AlertDialog:

package com.example.alex.testing_map;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;


public class MapsActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private String location = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
   ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(
            this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer);

    drawerLayout.setDrawerListener(drawerToggle);
    drawerToggle.syncState();

    Fragment fragment = new MapFragment();
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.add(R.id.frame_content, fragment);
    ft.commit();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@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.add_item:
            Intent intent = new Intent(this, AddMail.class);
            this.startActivity(intent);
            break;
        case R.id.search:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Dirección");

            final EditText input = new EditText(this);
            input.setInputType(InputType.TYPE_CLASS_TEXT);
            builder.setView(input);

            builder.setPositiveButton("Buscar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  location = input.getText().toString();

                }
            });
            builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

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

    return true;

}


@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

    Fragment fragment = null;

    switch (item.getItemId()){
        case R.id.mapa:
            fragment = new MapFragment();
            FragmentTransaction ft1 = getSupportFragmentManager().beginTransaction();
            ft1.replace(R.id.frame_content, fragment);
            ft1.commit();
            getSupportActionBar().setTitle(R.string.app_name);
            break;
        case R.id.help:
            fragment = new Help();
            FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
            ft2.replace(R.id.frame_content, fragment);
            ft2.commit();
            getSupportActionBar().setTitle(item.getTitle());
            break;
        case R.id.about:
            fragment = new About();
            FragmentTransaction ft3 = getSupportFragmentManager().beginTransaction();
            ft3.replace(R.id.frame_content, fragment);
            ft3.commit();
            getSupportActionBar().setTitle(item.getTitle());
            break;
        case R.id.rate:
            Intent face = new Intent(Intent.ACTION_VIEW);
            face.setData(Uri.parse("fb://profile/" + "100000914715145"));
            startActivity(face);
            break;
        default:
            return true;

    }


    DrawerLayout drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    drawerLayout.closeDrawer(GravityCompat.START);
    return true;
}


}

And my MapFragment.java:

package com.example.alex.testing_map;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;



public class MapFragment extends Fragment implements OnMapReadyCallback {


private GoogleMap mMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.map_fragment, viewGroup, false);
    FragmentManager manager = getFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    SupportMapFragment fragment = new SupportMapFragment();
    transaction.replace(R.id.mapView, fragment);
    transaction.commit();

    fragment.getMapAsync(this);
    return view;
}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mMap.setMyLocationEnabled(true);
    } else {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);

        } else {
        }
    }

    mMap.getUiSettings().setCompassEnabled(false);
    mMap.getUiSettings().setIndoorLevelPickerEnabled(false);
    mMap.getUiSettings().setMapToolbarEnabled(false);
    mMap.getUiSettings().setRotateGesturesEnabled(false);
    mMap.getUiSettings().setZoomControlsEnabled(false);


    // Primer poso les coordenades i estableixo els punts (numerats amb lletres en castellà)
    // i després afegeixo els marcadors, posant de localització
    // el nom dels punts definits amb anterioritat

    LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(provider);

    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    LatLng p1 = new LatLng(41.39355, 2.15473);
    mMap.addMarker(new MarkerOptions().position(p1).icon(BitmapDescriptorFactory.fromResource(R.drawable.pointer_bici1)));
   mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));


}

}

Solution

  • As I understand what you are trying to do, the AlertDialog you are showing is like a search dialog where you put in the address query and when the Buscar button is clicked, you want it to be sent to the MapFragment, where it will be used by your Geocoder.

    To put it simply, the only issue you have is passing the location value from the EditText to the MapFragment. Looked around the community and found this answer on How to pass data from Activity to Fragment by using setArguments(), like so:

    Bundle bundle = new Bundle();
    bundle.putString(key, value); // preferred key and the location string you want
    fragment.setArguments(bundle);
    

    Then receive it in the Fragment like so:

    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
              String strtext=getArguments().getString("message"); // replace "message" with the key you used.
    
        return inflater.inflate(R.layout.fragment, container, false);
        }
    

    You can also use a listener, if you want.