2012-01-19 2 views
1

J'ai écrit le code suivant pour obtenir le nom du lieu:Obtenez Lieu Nom en passant Latitude et Longitude dans Android

UseGpsActivity.java

public class UseGpsActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     /* Use the LocationManager class to obtain GPS locations */ 
     boolean gps_is_enabled = false; 
     LocationManager mlocManager = (LocationManager) this 
       .getSystemService(Context.LOCATION_SERVICE); 
     List<String> accessibleProviders = mlocManager.getProviders(true); 
     gps_is_enabled = accessibleProviders != null 
       && accessibleProviders.size() > 0; 
     Log.v("gps enabled", gps_is_enabled + ""); 
     LocationListener mlocListener = new MyLocationListener(); 
     // mlocManager.requestLocationUpdates(mlocManager.GPS_PROVIDER, 0, 0, 
     // mlocListener); 
     mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, 
       mlocListener); 
     // mlocManager.set 
    } 

    /* Class My Location Listener */ 

    public class MyLocationListener implements LocationListener { 
     @Override 
     public void onProviderDisabled(String provider) { 
      Toast.makeText(getApplicationContext(), "Gps Disabled", 5000) 
        .show(); 
      Log.v("gps", "gps disabled"); 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
      Toast.makeText(getApplicationContext(), "Gps Enabled", 5000).show(); 
      Log.v("gps", "gps enabled"); 
     } 

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

     } 

     @Override 
     public void onLocationChanged(Location loc) { 
      // TODO Auto-generated method stub 
      loc.getLatitude(); 
      loc.getLongitude(); 
      String Text = "My current location is: " + "Latitud = " 
        + loc.getLatitude() + "Longitud = " + loc.getLongitude(); 
      Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT) 
        .show(); 
      Geocoder gcd = new Geocoder(UseGpsActivity.this, 
        Locale.getDefault()); 
      List<Address> addresses = null; 
      try { 
       addresses = gcd.getFromLocation(loc.getLatitude(), 
         loc.getLongitude(), 1); 

      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      if (addresses != null) { 
       if (addresses.size() > 0) { 
        Log.v("Addresses : ", addresses.get(0).getLocality() + ""); 
        Toast.makeText(
          getApplicationContext(), 
          "Addresses : " + addresses.get(0).getLocality() 
            + "", Toast.LENGTH_LONG).show(); 
        Log.v("gps", Text + " " + addresses.get(0).getLocality() 
          + ""); 
       } 
      } else { 
       Log.v("addresses ", "NULL"); 
      } 
     } 
    }/* End of Class MyLocationListener */ 

Code de Manifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="demo.usegps" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk android:minSdkVersion="4" /> 

    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_GPS" /> 
    <uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" /> 
    <uses-permission android:name="android.permission.SET_TIME_ZONE" /> 

    <application 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" > 
     <activity 
      android:name=".UseGpsActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

Lorsque j'utilise la correction géographique (geo fix -122.084094 37.422006), j'obtiens un toast affiché avec lat et lng, mais je reçois le message suivant sur logcat:

01-19 13:32:48.991: W/System.err(751): java.io.IOException: Service not Available 
01-19 13:32:48.991: W/System.err(751): at android.location.Geocoder.getFromLocation(Geocoder.java:117) 
01-19 13:32:49.001: W/System.err(751): at demo.usegps.UseGpsActivity$MyLocationListener.onLocationChanged(UseGpsActivity.java:74) 
01-19 13:32:49.001: W/System.err(751): at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:191) 
01-19 13:32:49.001: W/System.err(751): at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:124) 
01-19 13:32:49.001: W/System.err(751): at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:140) 
01-19 13:32:49.001: W/System.err(751): at android.os.Handler.dispatchMessage(Handler.java:99) 
01-19 13:32:49.001: W/System.err(751): at android.os.Looper.loop(Looper.java:123) 
01-19 13:32:49.001: W/System.err(751): at android.app.ActivityThread.main(ActivityThread.java:4627) 
01-19 13:32:49.001: W/System.err(751): at java.lang.reflect.Method.invokeNative(Native Method) 
01-19 13:32:49.001: W/System.err(751): at java.lang.reflect.Method.invoke(Method.java:521) 
01-19 13:32:49.001: W/System.err(751): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 
01-19 13:32:49.011: W/System.err(751): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 
01-19 13:32:49.011: W/System.err(751): at dalvik.system.NativeStart.main(Native Method) 
01-19 13:32:49.011: V/addresses(751): NULL 

Quel service dois-je ajouter ou appeler dans mon code ??

+0

Si vous essayez dans Emulator alors son un bug http://stackoverflow.com/questions/3619924/android-geocoder-why-do-i-get-the-service-is-not-available –

+0

oui je suis en train d'essayer l'émulateur 2.2 mais sur un vrai appareil il ne montre même pas de pain grillé – Shruti

Répondre

0

Je l'usage qui code et maintenant je suis en mesure d'obtenir le nom du lieu:

public class GPSLocatorActivity extends MapActivity { 
    private MapView mapView; 
    private MapController mapController; 

    private LocationManager locationManager; 
    private LocationListener locationListener; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  

     locationListener = new GPSLocationListener(); 

     locationManager.requestLocationUpdates(
      LocationManager.GPS_PROVIDER, 
      0, 
      0, 
      locationListener); 

     mapView = (MapView) findViewById(R.id.mapView); 

     // enable Street view by default 
     mapView.setStreetView(true); 

     // enable to show Satellite view 
     // mapView.setSatellite(true); 

     // enable to show Traffic on map 
     // mapView.setTraffic(true); 
     mapView.setBuiltInZoomControls(true); 

     mapController = mapView.getController(); 
     mapController.setZoom(16); 
    } 

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

    private class GPSLocationListener implements LocationListener 
    { 
     @Override 
     public void onLocationChanged(Location location) { 
      if (location != null) { 
       GeoPoint point = new GeoPoint(
         (int) (location.getLatitude() * 1E6), 
         (int) (location.getLongitude() * 1E6)); 

       /* Toast.makeText(getBaseContext(), 
         "Latitude: " + location.getLatitude() + 
         " Longitude: " + location.getLongitude(), 
         Toast.LENGTH_SHORT).show();*/ 

       mapController.animateTo(point); 
       mapController.setZoom(16); 

       // add marker 
       MapOverlay mapOverlay = new MapOverlay(); 
       mapOverlay.setPointToDraw(point); 
       List<Overlay> listOfOverlays = mapView.getOverlays(); 
       listOfOverlays.clear(); 
       listOfOverlays.add(mapOverlay); 
       String address = ConvertPointToLocation(point); 
       Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show(); 
       mapView.invalidate(); 
      } 
     } 

     public String ConvertPointToLocation(GeoPoint point) { 
      String address = ""; 
      Geocoder geoCoder = new Geocoder(
        getBaseContext(), Locale.getDefault()); 
      try { 
       List<Address> addresses = geoCoder.getFromLocation(
        point.getLatitudeE6()/1E6, 
        point.getLongitudeE6()/1E6, 1); 

       if (addresses.size() > 0) { 
        for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++) 
         address += addresses.get(0).getAddressLine(index) + " "; 
       } 
      } 
      catch (IOException e) {     
       e.printStackTrace(); 
      } 

      return address; 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
     } 

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

    class MapOverlay extends Overlay 
    { 
     private GeoPoint pointToDraw; 

     public void setPointToDraw(GeoPoint point) { 
      pointToDraw = point; 
     } 

     public GeoPoint getPointToDraw() { 
      return pointToDraw; 
     } 

     @Override 
     public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { 
      super.draw(canvas, mapView, shadow);     

      // convert point to pixels 
      Point screenPts = new Point(); 
      mapView.getProjection().toPixels(pointToDraw, screenPts); 

      // add marker 
      Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.red); 
      canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null); // 24 is the height of image   
      return true; 
     } 
    } 
} 
0

Utilisez le code ci-dessous pour obtenir l'adresse

String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+ ","+ lon+ "&sensor=true"; 
      String res = IOUtils.MakeRequest(url); 
      Log.e("result", res); 
      if (res != null && !res.equalsIgnoreCase("")) { 
       JSONObject jObject = new JSONObject(res); 
//    if (jObject.getString("status").equalsIgnoreCase("ok")) { 
        JSONArray jArray = jObject.getJSONArray("results"); 
        if(jArray.length() > 0){ 
         JSONObject geo = jArray.getJSONObject(0); 
         address = geo.getString("formatted_address"); 
         String[] splite = address.split(","); 
         if(splite.length > 3){ 
          String temp = splite[2]; 
          temp = temp.substring(0,3); 
          address = ""; 
          address+=splite[0]+","+splite[1]+","+temp+","+splite[3]; 
         } 
         else 
         { 
          address="No Address"; 
         } 
         Log.e("address", address); 


        } 

//    } 
+0

Il ne fait pas une demande d'URL pour une adresse, il utilise le GPS. Aussi, le simple fait de poster du code n'est pas une réponse ... – JoxTraex

Questions connexes