perdonad pues somos novatos. Estamos tratando de obtener latitud y longitud de una dirección en Google Places SDK, pero solo conseguimos obtener la dirección, hemos buscado, que es utilizando getLat y getLng, pero o no sabemos donde colocarlo o lo ponemos erroneamente. Muchas gracias de antemanos
//JAVA ACTIVITY
package com.example.fl.trabajomapa;
//PARTE CODIGO AUTOOMPLETE
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
private static final String TAGGOOGLE = "GoogleActivity";
private static final int RC_SIGN_IN = 1;
private int STORAGE_PERMISSION_CODE= 1;//Para los permisos
final private int REQUEST_CODE_ASK_PERMISSIONS = 111;
private static final String TAG = "CAPublicaOfertaActivity";
//COORDENADAS ENTRE LAS QUE BUSCA EL AUTOCOMPLETE
private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
new LatLng(27.666172, -18.273932), new LatLng(42.772283, 4.747570));
//PARTE CODIGO AUTOOMPLETE
AutoCompleteTextView etdireccionnegocioAutoCA;
PlaceAutocompleteAdapter mPlaceAutocompleteAdapter;
GoogleApiClient mGoogleApiClient;
//DECLARO VARIANTES
TextView tvocultolatitudCA, tvocultolongitudCA, tvocultoCA;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capublicar_oferta);
// AUTOCOMPLETE
etdireccionnegocioAutoCA = (AutoCompleteTextView) findViewById(R.id.etdireccionnegocioAutoCA);
//INICIAR PROCESO AUTOOMPLETE
init();
//ENLAZO VARIANTES
tvocultolatitudCA = (TextView) findViewById(R.id.tvocultolatitudCA);
tvocultolongitudCA = (TextView) findViewById(R.id.tvocultolongitudCA);
tvocultoCA = (TextView) findViewById(R.id.tvocultoCA);
}//FIN ONCREATE
//BOTON OBTENER DIRECCION
public void obtenerdireccion (View view){
locationStart();
}
//MANDAR OFERTA
public void publicaroferta(View view) {
//ENLAZO VARIANTES CAMPOS OBLIGATORIOS
String direccionnegocioCA = etdireccionnegocioAutoCA.getText().toString();
String latitudnegocioCA = tvocultolatitudCA.getText().toString();
//TODO es double porque tiene decimales so retraso de hombre
//Double latitudint = Double.parseDouble(latitudnegocioCA);
String longitudnegocioCA = tvocultolongitudCA.getText().toString();
//Double longitudint = Double.parseDouble(longitudnegocioCA);
}
//PROTOCOLO PARA OBTENER DIRECCION ▼
private void locationStart() {
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Localizacion Local = new Localizacion();
Local.setMainActivity(this);
final boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnabled) {
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
return;
}
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) Local);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) Local);
tvocultoCA.setText("Localizacion agregada");
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 1000) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationStart();
return;
}
}
}
public void setLocation(Location loc) {
//OBTENER LA DIRECCION DE LA CALLE A PARTIR DE LA LATITUD Y LA LONGITUD
if (loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0) {
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> list = geocoder.getFromLocation(
loc.getLatitude(), loc.getLongitude(), 1);
//004
if (!list.isEmpty()) {
Address DirCalle = list.get(0);
etdireccionnegocioAutoCA.setText(DirCalle.getAddressLine(0));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//COMIENZA GESTION DE LOCALIZACION
public class Localizacion implements LocationListener {
CAPublicarOfertaActivity CAPublicarOfertaActivity;
public CAPublicarOfertaActivity getCAPublicarOfertaActivity() {
return CAPublicarOfertaActivity;
}
public void setMainActivity(CAPublicarOfertaActivity CAPublicarOfertaActivity) {
this.CAPublicarOfertaActivity = CAPublicarOfertaActivity;
}
@Override
public void onLocationChanged(Location loc) {
// ESTE METODO SE EJECUTA CADA VEZ QUE EL GPS RECIBE NUEVAS COORDENADAS DEBIDO A LA DETECCION DE UN CAMBIO DE UBICACION
loc.getLatitude();
loc.getLongitude();
String Text = "Lat = " + loc.getLatitude() + "\n Long = " + loc.getLongitude();
tvocultoCA.setText(Text);
this.CAPublicarOfertaActivity.setLocation(loc);
}
@Override
public void onProviderDisabled(String provider) {
// AVISO DE GPS DESACTIVADO
tvocultoCA.setText("GPS Desactivado");
}
@Override
public void onProviderEnabled(String provider) {
// AVISO DE GPS ACTIVO
tvocultoCA.setText("GPS Activado");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.AVAILABLE:
Log.d("debug", "LocationProvider.AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.d("debug", "LocationProvider.OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.d("debug", "LocationProvider.TEMPORARILY_UNAVAILABLE");
break;
//PROTOCOLO PARA OBTENER DIRECCION ▲
}
}
}
//PROTOCOLO AUTOCOMPLETE
private void init() {
Log.d(TAG, "init: initializing");
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
mPlaceAutocompleteAdapter = new PlaceAutocompleteAdapter(this, mGoogleApiClient,
LAT_LNG_BOUNDS, null);
etdireccionnegocioAutoCA.setAdapter(mPlaceAutocompleteAdapter);
etdireccionnegocioAutoCA.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {
}
return false;
}
});
hideSoftKeyboard();
}
private void hideSoftKeyboard(){
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
//ADAPTER
package com.example.fl.trabajomapa;
public class PlaceAutocompleteAdapter extends ArrayAdapter implements Filterable {
private static final String TAG = "PlaceAutoCompleteAd";
private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
private ArrayList<AutocompletePrediction> mResultList;
private GoogleApiClient mGoogleApiClient;
private LatLngBounds mBounds;
private AutocompleteFilter mPlaceFilter;
public PlaceAutocompleteAdapter(Context context, GoogleApiClient googleApiClient,
LatLngBounds bounds, AutocompleteFilter filter) {
super(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1);
mGoogleApiClient = googleApiClient;
mBounds = bounds;
mPlaceFilter = filter;
}
public void setBounds(LatLngBounds bounds) {
mBounds = bounds;
}
@Override
public int getCount() {
return mResultList.size();
}
@Override
public AutocompletePrediction getItem(int position) {
return mResultList.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
AutocompletePrediction item = getItem(position);
TextView textView1 = (TextView) row.findViewById(android.R.id.text1);
TextView textView2 = (TextView) row.findViewById(android.R.id.text2);
textView1.setText(item.getPrimaryText(STYLE_BOLD));
textView2.setText(item.getSecondaryText(STYLE_BOLD));
return row;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<AutocompletePrediction> filterData = new ArrayList<>();
if (constraint != null) {
filterData = getAutocomplete(constraint);
}
results.values = filterData;
if (filterData != null) {
results.count = filterData.size();
} else {
results.count = 0;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
mResultList = (ArrayList<AutocompletePrediction>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
@Override
public CharSequence convertResultToString(Object resultValue) {
if (resultValue instanceof AutocompletePrediction) {
return ((AutocompletePrediction) resultValue).getFullText(null);
} else {
return super.convertResultToString(resultValue);
}
}
};
}
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
if (mGoogleApiClient.isConnected()) {
Log.i(TAG, "Starting autocomplete query for: " + constraint);
PendingResult<AutocompletePredictionBuffer> results =
Places.GeoDataApi
.getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
mBounds, mPlaceFilter);
AutocompletePredictionBuffer autocompletePredictions = results
.await(60, TimeUnit.SECONDS);
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
autocompletePredictions.release();
return null;
}
Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
+ " predictions.");
return DataBufferUtils.freezeAndClose(autocompletePredictions);
}
Log.e(TAG, "Google API client is not connected for autocomplete query.");
return null;
}
List<Address> list = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
ya lo haceis. No sé qué mas quereis obtener. Latitud y longitud son de Location.