Return an address using Google Maps API

1

I'm finalizing an application where I need to use Google Maps API for two things: select an address from the user's choice (example: user navigates to the desired address and chooses it) and show the map based on the location of a example (open the map at the address that the user chose earlier).

I have read that it is possible to receive the selected address using the following code:

private GoogleMap mMap;

{...}

mMap.setOnMapClickListener(new OnMapClickListener() {

    @Override
    public void onMapClick(LatLng newLatLon) {
        Toast.makeText(getApplicationContext(), point.toString(), Toast.LENGTH_SHORT).show();                       
    }
});

But I would like to pass this function to a button outside the map. How can I do this? And although I looked for how do I open a map using a pre-defined address, I could not find anything straightforward. Is it possible to pass a parameter of type String to the API?

    
asked by anonymous 22.06.2014 / 20:13

1 answer

2

You will have to use a reverse geolocation. I made a post on this in 2010 ( Android: Reverse Geolocation ), but the code for this part has not changed much.

The class that contains the data address is the Address . In order to know each field and what you can get from the address, I suggest you visit the documentation . Below is the code for a function that searches for the city and the address line 1, which for most cases will return the name of the street. But be careful that in some cases it may be null, so it is good to do the right tests:

private void getCityByLocation(Location location) {
    //obtendo coordenadas
    double latPoint = location.getLatitude();
    double lngPoint = location.getLongitude();

    //Classe que fornece a localização da cidade
    Geocoder geocoder = new Geocoder(this.getApplicationContext());
    List myLocation = null;

    try {
        //Obtendo os dados do endereço
        myLocation = geocoder.getFromLocation(latPoint, lngPoint, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if ( myLocation != null && myLocation.size() > 0) {
        Address a = myLocation.get(0);
        //Pronto! Vocêm tem o nome da cidade!
        String city = a.getLocality();
        String street = a.getAddressLine(0);
       //Seu código continua aqui...
    } else {
        Log.d("geolocation", "endereço não localizado");
    }
}
    
24.06.2014 / 08:53