How can I set the address as the street and neighborhood corresponding to latitude and longitude?

Asked

Viewed 818 times

2

I have that code:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == MAPA_REQUEST_BAIRRO){
        if(resultCode == RESULT_OK){
                try {
                Place place = PlacePicker.getPlace(this, data);
                LatLng latLng = place.getLatLng();

                //txtLocalLogradouroB.setText(logradouro +"-"+ bairro);

                Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
                List<Address> addresses1 = null;
                List<Address> addresses = null;

                double um= Double.parseDouble(latitude);
                double dois = Double.parseDouble(longitude);


                addresses1 = gcd.getFromLocation(um, dois, 1);

//                    }
                     if (addresses1.size() > 0) {
                    br = addresses1.get(0).getSubLocality();
                    lg = addresses1.get(0).getThoroughfare();
                    txtLocalLogradouroB.setText(lg + "-"+br);

                }

But it doesn’t work. I have latitude and longitude that comes from a webservice but I want to convert these values to pick up the address and show the user someone could help me please? :)

3 answers

5


Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
 try {
        addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
        String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = addresses.get(0).getLocality();
        String state = addresses.get(0).getAdminArea();
        String country = addresses.get(0).getCountryName();
        String postalCode = addresses.get(0).getPostalCode();
        String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
    } catch (IOException e) {
        e.printStackTrace();
    }

https://stackoverflow.com/questions/9409195/how-to-get-complete-address-from-latitude-and-longitude

  • is not working

  • wait...just one thing here

  • I need to put this code on the oncreate is?

  • No. You create this class only when you need it, if you need it.

  • You read the comments of the people on the original page of that reply?

  • Now it worked...but I did not create class no. I put in the oncreate pq in that method I receive the data from the webservice and Seto

  • I will read friend. I hope I know how to look for my questions...the problem is that I do not know English :(

Show 2 more comments

2

Option 1:

Behold some examples how you can use Geocoder. But precisely for what you want, try using the function below that returns the location based on the LatLng past tense:

/**
 * Obtem um endereço baseado LatLng
 * @param latitude e longitude do ponto que quer encontrar
 * @return local em relação ao ponto.
 */
public List<Address> getAddress(LatLng point) {
    try {
        Geocoder geocoder;
        List<Address> addresses;
        geocoder = new Geocoder(this);
        if (point.latitude != 0 || point.longitude != 0) {
            addresses = geocoder.getFromLocation(point.latitude ,
                    point.longitude, 1);
            String address = addresses.get(0).getAddressLine(0);
            String city = addresses.get(0).getAddressLine(1);
            String country = addresses.get(0).getAddressLine(2);
            System.out.println(address+" - "+city+" - "+country);

            return addresses;

        } else {
            Toast.makeText(this, "latitude and longitude are null",
                    Toast.LENGTH_LONG).show();
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

Option 2:

Go on to latitude and longitude for the following query sequence, and you will get a result in JSON:

http://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&sensor=true 

After that(link), just interpret the JSON and get only the necessary information.

Details in the documentation Google Maps Geocoding API.

  • ahn? how do I do that/

  • I don’t know how to do it that way

-2

I will provide a code that returns the address and you can edit to get the information you want, but it is plugAndPlay. Come on.

Declare these variables before your onCreate.

private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var lastLocation: Location

On onCreate initialize this variable:

 fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

In the override fun method onMapReady(Googlemap: Googlemap) { what android Studio creates for you, call the following method:

getUserLocation()

Now let’s create the getUserLocation method:

private fun getUserLocation (){
    // 1
    mMap.isMyLocationEnabled = true //libera buscar a localização do usuário

    // 2
    fusedLocationClient.lastLocation.addOnSuccessListener(this) { location -> //pega a localização
        // Got last known location. In some rare situations this can be null.
        // 3
        if (location != null) { //se encontrou algo, vai marcar a posição no mapa.
            lastLocation = location
            val currentLatLng = LatLng(location.latitude, location.longitude)
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 17f))

            val mTxt = findViewById<TextView>(R.id.mTxtMsg)  //objeto que vai receber o endereço
            mTxt.setText(getAddress(currentLatLng, location.latitude, location.longitude))  //coloca o endereço dentro do objeto através deste método. 

        }
    }
}

Finally we will create the method that actually fetches the user address data.

private fun getAddress(latLng: Latlng, lat: Double, long: Double) :String { // 1 val geocoder = Geocoder(this) val Addresses: List? val address: Address? var addressText = ""

    try {
        // 2
        addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
        // 3
        if (null != addresses && !addresses.isEmpty()) {
            address = addresses[0]
            val mFullAddress = Geocoder(this, Locale.getDefault())
            var mUserCidade = ""
            if (addresses[0].locality == null){ //as vezes a cidade vem em locality e outras em subAdminArea, então precisamos fazer essa verificação
                mUserCidade = addresses[0].subAdminArea
            } else {
                mUserCidade = addresses[0].locality
            }
            val mUserEstado = addresses[0].adminArea
            val mUserBairro = addresses[0].subLocality
            val mUserNumeroCasa = addresses[0].subThoroughfare
            val mUserRua = addresses[0].thoroughfare
            val mUuserPais = addresses[0].countryName
            val mUserCep = addresses[0].postalCode
            addressText = mUserRua+" nº "+mUserNumeroCasa+", "+mUserBairro+", "+mUserCidade+" - "+mUserEstado
            //user as outras variaveis se quiser usar cep, país, bairro


        }
    } catch (e: IOException) {
        Log.e("MapsActivity", e.localizedMessage)
    }

    return addressText
}

Remarks: For this method to work you must already have the permissions of the user to access this information and also have already put in the manifest.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.