2011-12-23 20 views
6

Quiero mostrar mi ubicación actual, pero me muestra la latitud y la longitud que establecí en la línea de comandos. Si no configuro los parámetros en la línea de comando, ¡me muestra la latitud y la longitud incluidas en Eclipse!android gps ubicación actual

¿Hay alguien que tenga una idea al respecto? Estoy probando con AVD.

Hice una prueba para ver si mi ubicación está habilitada, pero no es así. No estoy seguro de por qué ese es el caso.

Este es mi código:

package com.manita.mapuse; 


import java.io.InputStream; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 

import android.content.Context; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.KeyEvent; 
import android.widget.Toast; 

import com.google.android.maps.GeoPoint; 
import com.google.android.maps.MapActivity; 
import com.google.android.maps.MapController; 
import com.google.android.maps.MapView; 
import com.google.android.maps.MyLocationOverlay; 



public class MapuseActivity extends MapActivity implements LocationListener { 

    private MapView mapView = null; 
     private LocationManager lm = null; 
     private double lat = 0; 
     private double lng = 0; 
     private double alt = 0; 
     private MapController mc = null; 
     private MyLocationOverlay myLocation = null; 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     mapView = (MapView) this.findViewById(R.id.mapView); 
     mapView.setBuiltInZoomControls(true); 

     lm = (LocationManager) this.getSystemService(LOCATION_SERVICE); 
     lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this); 
     lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, 
      this); 

     mc = mapView.getController(); 
     mc.setZoom(10); 

     myLocation = new MyLocationOverlay(getApplicationContext(), mapView); 
     myLocation.runOnFirstFix(new Runnable() { 
      public void run() { 
      mc.animateTo(myLocation.getMyLocation()); 
      mc.setZoom(10); 
      } 
     }); 


     LocationManager locationManager; 
     String context = Context.LOCATION_SERVICE; 
     locationManager = (LocationManager)getSystemService(context); 
     String provider = LocationManager.GPS_PROVIDER; 
     lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this); 
     Location location = locationManager.getLastKnownLocation(provider); 
     locationManager.getProvider(provider); 
     if(!locationManager.isProviderEnabled(provider)){ 
      locationManager.setTestProviderEnabled(provider, true); 
      } 
      boolean enabled = locationManager.isProviderEnabled(provider); 
      if(enabled){ 

       Toast.makeText(getBaseContext(), 
         "provide enabled : Latitude = " + lat + " Longitude = " + lng+" Altitude = " + alt, 
         Toast.LENGTH_SHORT).show(); 

      } 
      else{ 
       Toast.makeText(getBaseContext(), 
         "provider disabled : Latitude = " + lat + " Longitude = " + lng+" Altitude = " + alt, 
         Toast.LENGTH_SHORT).show(); 

      } 
      if(location!=null){ 
       lat = location.getLatitude(); 
       lng = location.getLongitude(); 
       alt = location.getAltitude(); 
       Toast.makeText(getBaseContext(), 
         "providerrr enabled : Latitude = " + lat + " Longitude = " + lng+" Altitude = " + alt, 
         Toast.LENGTH_SHORT).show(); 
      } 
      else{ 
       Toast.makeText(getBaseContext(), 
         "location not found : Latitude = " + lat + " Longitude = " + lng+" Altitude = " + alt, 
         Toast.LENGTH_SHORT).show(); 
      } 



     mapView.getOverlays().add(myLocation); 
     if (myLocation.isMyLocationEnabled()!=false) 
     { 
      GeoPoint p =myLocation.getMyLocation(); 
      lat= p.getLatitudeE6(); 
      lng= p.getLongitudeE6(); 
      alt = location.getAltitude(); 
      Toast.makeText(getBaseContext(), 
        "geolocalisation activé lat: "+lat+ " long: " +lng +" Altitude = " + alt, 
        Toast.LENGTH_SHORT).show(); 
     } 
     else 
     { 

      Toast.makeText(getBaseContext(), 
        "geolocalisation desactivée" , 
        Toast.LENGTH_SHORT).show(); 
     } 

     // appel de la fonction insert values 
     insertvalues(lat, lng); 
     } 

     @Override 
     protected void onResume() { 
     super.onResume(); 
     myLocation.enableMyLocation(); 
     myLocation.enableCompass(); 
     } 

     @Override 
     protected boolean isRouteDisplayed() { 
     return false; 
     } 

     @Override 
     public boolean onKeyDown(int keyCode, KeyEvent event) { 
     if (keyCode == KeyEvent.KEYCODE_S) { 
      mapView.setSatellite(!mapView.isSatellite()); 
      return true; 
     } 
     if (keyCode == KeyEvent.KEYCODE_T) { 
      mapView.setSatellite(!mapView.isTraffic()); 
      return true; 
     } 
     return super.onKeyDown(keyCode, event); 
     } 

     @Override 
     public void onLocationChanged(Location location) { 
     lat = location.getLatitude(); 
     lng = location.getLongitude(); 
     Toast.makeText(
      getBaseContext(), 
      "Location change to : Latitude = " + lat + " Longitude = " 
       + lng, Toast.LENGTH_SHORT).show(); 
     GeoPoint p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)); 
     mc.animateTo(p); 
     mc.setCenter(p); 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
     } 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
     } 


     ///// insert valeurs .... 
     public void insertvalues(double lat, double lng){ 




      //http post c à d envoi des données 
      try{ 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new 

       HttpPost("http://www.pizza-paris.com/clic/marwa/test/form.php?latitude="+lat+"&longitude="+lng); 

       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity entity = response.getEntity(); 
       InputStream is = entity.getContent(); 
       Log.i("postData", response.getStatusLine().toString()); 

      } 

      catch(Exception e) 
      { 
       Log.e("log_tag", "Error in http connection "+e.toString()); 
      }  


      } 
} 

Gracias!

+0

gps no funcionará en un emulador. Pruebe su código en un dispositivo real. – Snicolas

+0

Por favor, consulte este enlace que puede serle útil. [Ubicación GPS en Android Emulator] (http://stackoverflow.com/questions/2279647/how-to-emulate-gps-location-in-the-android-emulator) –

+0

gracias Snicolas mybe tu respuesta es lo que estoy buscando pero ¿cómo puedo obtener el archivo apk? –

Respuesta

1

A menos que su PC/Mac tenga GPS, AVD no tiene capacidad para detectar su ubicación. Pruebe su programa con un dispositivo real o ingrese valores manualmente.

+0

Muchas gracias :) –

+0

O usa 'geo fix' http://stackoverflow.com/questions/2279647/how-to-emulate-gps-location-in-the-android-emulator –

4

Abra su administrador de Dispositivos virtuales y haga clic en Editar. En la sección Hardware, haga clic en Nuevo y agregue soporte GPS y cambie el valor a verdadero. Ahora inicia el emulador y abre una consola. Si el emulador está completamente encendido, escriba en la consola telnet localhost 5554. Cuando se establece la conexión de telnet, puede colocar en ubicaciones como esta: geo fix 21.42 42

+0

sí, consigue la ubicación que ¡Configuré en localhost pero quiero que muestre mi ubicación actual que significa dónde estoy ahora! –

+0

Averigua cuáles son tus coordenadas actuales e ingrésalas usando 'geo fix' o ve y compra un android. –

3

Para agregar a las respuestas existentes, si realmente necesita probar la funcionalidad en su emulador, puede usar ubicaciones simuladas. Más puede encontrar aquí http://developer.android.com/guide/topics/location/obtaining-user-location.html#MockData.

Tenga en cuenta que debe agregar los permisos necesarios para esto (ACCESS_MOCK_LOCATION).

Espero que esto ayude!

+0

sí, lo hice, pero quiero que muestre mi ubicación actual, no la locatiob en el simulacro. –

+0

Luego necesita un teléfono inteligente con gps o un gps con su PC. –

+0

sí! la versión de mi aplicación es 7 !! ¿Puedo probarlo con iphone? –

Cuestiones relacionadas