|
Página 1 de 1
|
[ 1 Mensagem ] |
|
Pegar o endereço pela minha localização - (RESOLVIDO)
Autor |
Mensagem |
GEO
Anatomy of an App
Data de registro: 24 Mai 2011, 13:48 Mensagens: 146
|
 Pegar o endereço pela minha localização - (RESOLVIDO)
Bom Dia, preciso capturar o endereço da minha atual localização, mas sem abrir o mapa. Ao clicar em um botão, acha a minha localização e me retorna o endereço. Quem pode me ajudar Por Favor. PS: Uso o Eclipse. Grata Carla SEGUE: // CLASSE ONDE VOU MOSTRAR O ENDEREÇO double longitude; double latitude; // checa se o GPS está habilitado GPS_Localizacao gps = new GPS_Localizacao (Notificacao. this); if (gps. canGetLocation()) { latitude = gps. getLatitude(); longitude = gps. getLongitude(); } else { gps. showSettingsAlert(); } // fim checa se o GPS está habilitado btn_busca_end. setOnClickListener(new OnClickListener () { @Override public void onClick (View v ) { latitude = 0.0; longitude = 0.0; Busca_Coordenadas (); } }); public void Busca_Coordenadas () { pd = ProgressDialog. show(Notificacao. this, " * . * Aguarde * . * ", ".*.*.*. LOCALIZANDO ENDEREÇO .*.*.*."); Handler h = new Handler (); h. postDelayed(Notificacao. this, 7500); @Override public void run () { GPS_Localizacao gps = new GPS_Localizacao (Notificacao. this); if (gps. canGetLocation()) { pd. dismiss(); latitude = gps. getLatitude(); longitude = gps. getLongitude(); } else { gps. showSettingsAlert(); } if (conectado == true) { new Conexao (). execute(latitude + "", longitude + ""); } else { msg. setText("Não é possível pesquisar o Endereço sem conexão com a Internet."); aviso. show(); } }}//POPULANDO OS CAMPOS QDO O ENDERE"CO É ENCONTRADOclass Conexao extends AsyncTask<String, String, String> { @Override protected void onPreExecute () { pb_gps. setVisibility(View. VISIBLE); Limpa_Campos_Endereco_Local (); pb_gps. setMax(60); pb_gps. setProgress(90); } @Override protected String doInBackground (String... params) { try { pb_gps. setVisibility(View. VISIBLE); while (i < 60) { i += 1; handler. post(new Runnable() { public void run () { pb_gps. setProgress(i ); } }); try { Thread. sleep(60); } catch (InterruptedException e ) { e. printStackTrace(); } } String url = "https://maps.googleapis.com/maps/api/geocode/xml?latlng="+ params [0] + "," + params [1]+ "&key=AIzaSyDYeRYXdlCb9iq3PB4VbQl0nI0MUsVFfyk"; Log. i("MAPA", "URL => " + url ); HttpClient httpclient = new DefaultHttpClient (); HttpGet request = new HttpGet (url ); InputStream in = (InputStream) httpclient. execute(request ). getEntity(). getContent(); BufferedReader br = null; StringBuilder sb = new StringBuilder (); br = new BufferedReader(new InputStreamReader(in )); String line = br. readLine(); while (line != null) { sb. append(line ); line = br. readLine(); } String resposta = sb. toString(); String result_one = resposta. substring(resposta. indexOf("<formatted_address>") + 19,resposta. indexOf("</formatted_address>")). replace("-", ","); Log. i("MAPA", "result => " + result_one ); String resultado [] = result_one. split(","); if ((resultado [1]. toString() != null) && (!resultado [1]. toString(). equals(""))) { numero = resultado [1]. toString(); } if ((resultado [2]. toString() != null) && (!resultado [2]. toString(). equals(""))) { bairro = resultado [2]. toString(); } if ((resultado [3]. toString() != null) && (!resultado [3]. toString(). equals(""))) { cidade = resultado [3]. toString(); } if ((resultado [4]. toString() != null) && (!resultado [4]. toString(). equals(""))) { uf = resultado [4]. toString(). toString(). replace(" ", ""); } Log. w("MAPA", "UF => " + resultado [4]. trim(). replace(" ", "")); if ((resultado [5]. toString() != null) && (!resultado [5]. toString(). equals(""))) { cep = resultado [5]. toString(). trim() + "-" + resultado [6]. toString(). trim(); } return resultado [0]. toString(); } catch ( IOException e ) { return "Erro: " + e. getMessage(); } } @Override protected void onPostExecute (String msg_result ) { if (!msg_result. substring(0, 4). equals("Erro")) { edit_rua. setText(msg_result ); edit_numero. setText(numero ); edit_bairro. setText(bairro ); edit_cidade. setText(cidade ); edit_uf. setText(uf ); edit_cep. setText(cep ); pb_gps. setVisibility(View. GONE); i = 0; } else { edit_rua. setText(""); pb_gps. setVisibility(View. GONE); i = 0; } Log. w("MAPA", "Descricao = " + descricao_end ); } } //CLASSE QUE GPS_Localizacao public class GPS_Localizacao extends Service implements LocationListener { private final Context mContext; boolean isGPSEnabled = false; // flag para o status do GPS boolean isNetworkEnabled = false; //flag para status da rede boolean canGetLocation = false; // flag para o status do GPS Location location; //localização double latitude; double longitude; // A distância mánima, em metros, para mudar as atualizações private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 metros // O tempo mínimo, em milissegundos, entre as atualizações private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minuto protected LocationManager locationManager; public GPS_Localizacao (Context context ) { this. mContext = context; getLocation (); } public Location getLocation () { try { locationManager = (LocationManager ) mContext . getSystemService(LOCATION_SERVICE ); // pegando o status do GPS isGPSEnabled = locationManager . isProviderEnabled(LocationManager. GPS_PROVIDER); Log. i("NOTIFICACAO", "GPS ENABLED = " + isGPSEnabled ); // pegando o status da rede isNetworkEnabled = locationManager . isProviderEnabled(LocationManager. NETWORK_PROVIDER); Log. i("NOTIFICACAO", "NETWORK ENABLED = " + isNetworkEnabled ); if (!isGPSEnabled && !isNetworkEnabled ) { // nenhum provedor de rede est� habilitado } else { this. canGetLocation = true; // Primeira obten��o da localiza��o pelo provedor de rede if (isNetworkEnabled ) { locationManager. requestLocationUpdates( LocationManager. NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log. d("Network", "Network"); if (locationManager != null) { location = locationManager . getLastKnownLocation(LocationManager. NETWORK_PROVIDER); if (location != null) { latitude = location. getLatitude(); longitude = location. getLongitude(); } } } // se GPS habilitado pega lat/long usando os servi�os do GPS if (isGPSEnabled ) { if (location == null) { locationManager. requestLocationUpdates( LocationManager. GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log. d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager . getLastKnownLocation(LocationManager. GPS_PROVIDER); if (location != null) { latitude = location. getLatitude(); longitude = location. getLongitude(); } } } } } } catch (Exception e ) { e. printStackTrace(); } return location; } public void stopUsingGPS (){ if(locationManager != null){ locationManager. removeUpdates(GPS_Localizacao. this); } } /** * M�todo para obter a latitude * */ public double getLatitude (){ if(location != null){ latitude = location. getLatitude(); } // return latitude return latitude; } /** * M�todo para pegar a longitude * */ public double getLongitude (){ if(location != null){ longitude = location. getLongitude(); } // return longitude return longitude; } /** * M�todo para checar se o GPS/Wi-Fi est� habilitado * @return boolean * */ public boolean canGetLocation () { return this. canGetLocation; } /** * M�todo para mostrar as configura��es me um AlertDialog * Pressionando Configura��es o bot�o vai mostrar Op��es de Configura��o * */ public void showSettingsAlert (){ AlertDialog. Builder alertDialog = new AlertDialog. Builder(mContext ); // Definindo Dialog Title alertDialog. setTitle("GPS is settings"); // Definindo Dialog Message alertDialog. setMessage("GPS não está habilitado. VocÊ deseja ir em configurações?"); Log. i("NOTIFICACAO", "GPS não está habilitado. Você deseja ir em configurações?"); // Ao pressionar o bot�o Configura��es alertDialog. setPositiveButton("Settings", new DialogInterface. OnClickListener() { public void onClick (DialogInterface dialog, int which ) { Intent intent = new Intent (Settings. ACTION_LOCATION_SOURCE_SETTINGS); mContext. startActivity(intent ); } }); // Ao pressionar o bot�o cancelar alertDialog. setNegativeButton("Cancel", new DialogInterface. OnClickListener() { public void onClick (DialogInterface dialog, int which ) { dialog. cancel(); } }); // Mostrando Alert Message alertDialog. show(); } @Override public void onLocationChanged (Location location ) { // TODO Auto-generated method stub } @Override public void onStatusChanged (String provider, int status, Bundle extras ) { // TODO Auto-generated method stub } @Override public void onProviderEnabled (String provider ) { // TODO Auto-generated method stub } @Override public void onProviderDisabled (String provider ) { // TODO Auto-generated method stub } @Override public IBinder onBind (Intent intent ) { // TODO Auto-generated method stub return null; }} Se existe uma maneira mais simples de fazer não encontrei, essa deu certo...
|
14 Jan 2021, 13:05 |
|
|
|
Página 1 de 1
|
[ 1 Mensagem ] |
|
Quem está online |
Usuários vendo este fórum: adelar, alex.abrantes, alineri, allart, aluclinux, andi, andreluzz, Antonio Carlos, Aparec, ARAKINIDIO, ariostorecco, arkanjo, azero, Biggs Darklighter, BloggerCaOS, blurkness, BornSlip, carlos rodrigues, carlos.macleod, cesao, cesschneider, cezaraf, cfranca, charly, Clauber, cyzko, dannieltec, Darkluna, Darth Plagueis, DAVINCE, dfreitas, digiwise, dnakamashi, ederson_4, eXagon, fabric01, Felipe Marcondes, fraga, FVB, Gomes, guilhermepilotti, gusrp, gutem25, gutomilani, helder84, hugomarinho, HyagoRules, ismaelbpaiva, jacksaum, jaydson, jefficojava, Jenius, jhonguitar, jijo, jmarcos14, JMurray, jorgecardoso, jorgeFernandes, JuniorE, juniorfranca, Katia, klausenner, kleberperea, leanderdulac, leonardodamata, levita, lhdiassilva, Lincoln, lisbao, Liviosousa, lucasmadeira, luizcesar, Luke Skywalker, Machado000, Maiquell, maolveira, MarceloMC, marinho5, Marini, MauNunes, MBetioli, mendes_lu, mrangel, mrkensley, n3t0, neosun, nightwatch, onaiggac, otpor, PAMinhoto, paulokiller, pgbatera, PicsearchDroid, rafsantos, ramonsiebra, rananfu, rbenatti, renatocoliveira, rerp7, retardad0, Ricardo Chikasawa, ricardoogliari, rodrigo_mg, romuloff, shadow, Shinigami, SidneiCP, Snappy [Bot], sobrinho, suissa, tassiovirginio, Thelemita, tiagocordeiro, ubiratan, Velhinho, viniciusllima, viniciusluiz, vps_rj, wingdoido, YaCy, zorba, zorieuq e 48 visitantes |
|
Você não pode criar novos tópicos neste fórum Você não pode responder tópicos neste fórum Você não pode editar suas mensagens neste fórum Você não pode excluir suas mensagens neste fórum Você não pode enviar anexos neste fórum
|
|