2010-08-26 15 views

Respuesta

114
public GeoPoint getLocationFromAddress(String strAddress){ 

Geocoder coder = new Geocoder(this); 
List<Address> address; 
GeoPoint p1 = null; 

try { 
    address = coder.getFromLocationName(strAddress,5); 
    if (address==null) { 
     return null; 
    } 
    Address location=address.get(0); 
    location.getLatitude(); 
    location.getLongitude(); 

    p1 = new GeoPoint((double) (location.getLatitude() * 1E6), 
         (double) (location.getLongitude() * 1E6)); 

    return p1; 
    } 
} 

strAddress es una cadena que contiene la dirección. La variable address contiene las direcciones convertidas.

+1

Se lanza el "servicio no disponible java.io.IOException" Usted – Kandha

+3

necesita los permisos correctos para poder acceder al servicio. # Flo

+1

Necesita conexión a Internet para usar el Geocoder. – Flo

3

Así es como puede encontrar la latitud y la longitud de donde hemos hecho clic en el mapa.

public boolean onTouchEvent(MotionEvent event, MapView mapView) 
{ 
    //---when user lifts his finger--- 
    if (event.getAction() == 1) 
    {     
     GeoPoint p = mapView.getProjection().fromPixels(
      (int) event.getX(), 
      (int) event.getY()); 

     Toast.makeText(getBaseContext(), 
      p.getLatitudeE6()/1E6 + "," + 
      p.getLongitudeE6() /1E6 , 
      Toast.LENGTH_SHORT).show(); 
    }        
    return false; 
} 

funciona bien.

Para obtener la dirección de la ubicación podemos usar la clase geocoder.

51

Si desea colocar su dirección en Google Map continuación manera fácil de usar después de

Intent searchAddress = new Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+address)); 
startActivity(searchAddress); 

O

si necesitaba para obtener lat largo de su dirección a continuación, utilizar lugar de Google Api siguiente

crear un método que devuelve un JSONObject con la respuesta de la llamada HTTP li ke siguiente

public static JSONObject getLocationInfo(String address) { 
     StringBuilder stringBuilder = new StringBuilder(); 
     try { 

     address = address.replaceAll(" ","%20");  

     HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false"); 
     HttpClient client = new DefaultHttpClient(); 
     HttpResponse response; 
     stringBuilder = new StringBuilder(); 


      response = client.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      InputStream stream = entity.getContent(); 
      int b; 
      while ((b = stream.read()) != -1) { 
       stringBuilder.append((char) b); 
      } 
     } catch (ClientProtocolException e) { 
     } catch (IOException e) { 
     } 

     JSONObject jsonObject = new JSONObject(); 
     try { 
      jsonObject = new JSONObject(stringBuilder.toString()); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     return jsonObject; 
    } 

pasar ahora que JSONObject a getLatLong() método como el siguiente

public static boolean getLatLong(JSONObject jsonObject) { 

     try { 

      longitute = ((JSONArray)jsonObject.get("results")).getJSONObject(0) 
       .getJSONObject("geometry").getJSONObject("location") 
       .getDouble("lng"); 

      latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0) 
       .getJSONObject("geometry").getJSONObject("location") 
       .getDouble("lat"); 

     } catch (JSONException e) { 
      return false; 

     } 

     return true; 
    } 

Espero que esto ayude a que encontrar otros .. !! ¡¡Gracias .. !!

+0

¿Cómo pasar esto? –

+1

desafortunadamente esta solución no funciona con la conexión móvil de algunos operadores móviles: la solicitud siempre devuelve ** OVER_QUERY_LIMIT **. Esos operadores móviles usan sobrecarga NAT, asignando la misma IP a muchos dispositivos ... – UmbySlipKnot

+4

¡Buena solución! gracias – zozelfelfo

6

El siguiente código trabajará para Google apiv2:

public void convertAddress() { 
    if (address != null && !address.isEmpty()) { 
     try { 
      List<Address> addressList = geoCoder.getFromLocationName(address, 1); 
      if (addressList != null && addressList.size() > 0) { 
       double lat = addressList.get(0).getLatitude(); 
       double lng = addressList.get(0).getLongitude(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } // end catch 
    } // end if 
} // end convertAddress 

donde dirección es la cadena (123 Pruebas Rd Ciudad Estado postal) que desea convertir a LatLng.

1

Una respuesta al problema Kandha arriba:

Se lanza el "servicio no disponible java.io.IOException" yo ya di permiso y los incluyo la biblioteca ... puedo conseguir ver mapa .. .it tiros que IOException al geocodificador ...

simplemente he añadido una captura IOException después de la prueba y se solucionó el problema

catch(IOException ioEx){ 
     return null; 
    } 
54

Solución de Ud_an con API actualizadas

Nota: LatLng clase es parte de Google Play Services.

obligatoria:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 

<uses-permission android:name="android.permission.INTERNET"/> 

Actualización: Si tiene objetivo SDK 23 y por encima, asegúrese de tomar el cuidado de permiso de ejecución para la ubicación.

public LatLng getLocationFromAddress(Context context,String strAddress) { 

    Geocoder coder = new Geocoder(context); 
    List<Address> address; 
    LatLng p1 = null; 

    try { 
     // May throw an IOException 
     address = coder.getFromLocationName(strAddress, 5); 
     if (address == null) { 
      return null; 
     } 
     Address location = address.get(0); 
     location.getLatitude(); 
     location.getLongitude(); 

     p1 = new LatLng(location.getLatitude(), location.getLongitude()); 

    } catch (IOException ex) { 

     ex.printStackTrace(); 
    } 

    return p1; 
} 
+1

Gracias, funcionó para mí, la solución anterior no funcionaba. –

+0

Al crear instancias del Geocoder, debe pasar el contexto Geocoder coder = new Geocoder (this); o nuevo Geocoder (getApplicationContext) no getActivity() como se indica en la respuesta. –

+1

El código anterior @Quantumdroid está escrito en fragmento. De lo contrario, tienes toda la razón. Es contexto –

0
Geocoder coder = new Geocoder(this); 
     List<Address> addresses; 
     try { 
      addresses = coder.getFromLocationName(address, 5); 
      if (addresses == null) { 
      } 
      Address location = addresses.get(0); 
      double lat = location.getLatitude(); 
      double lng = location.getLongitude(); 
      Log.i("Lat",""+lat); 
      Log.i("Lng",""+lng); 
      LatLng latLng = new LatLng(lat,lng); 
      MarkerOptions markerOptions = new MarkerOptions(); 
      markerOptions.position(latLng); 
      googleMap.addMarker(markerOptions); 
      googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,12)); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
+0

Esa comprobación nula no está haciendo nada. – AjahnCharles

Cuestiones relacionadas