¿Cómo puedo encontrar la latitud y la longitud de la dirección?
Quiero mostrar la ubicación de una dirección en Google Maps.
¿Cómo obtengo la latitud y la longitud de una dirección utilizando la API de Google Maps?
- TextView no se muestra en la parte superior del mapa de Google
- Android Maps v2 rotar mapaVer con brújula
- Redibujar / refrescar Itemizedoverlay? (Android / google maps api)
- Google Map se está cargando con parches cuadrados
- Marcadores de mapa con texto en Google Maps Android API v2
- Dibujo de la ruta del autobús al mapa de Google
- MapView lanzar IllegalArgumentException - Tamaño de imagen incorrecto: 192 192
- Obtenga el certificado de huella digital SHA1 en Android Studio para Google Maps
- Actualizar polilínea de acuerdo con el usuario que se mueve android googleMaps v2
- ¿Cómo implementar Google Maps dentro de un fragmento y usar el objeto GoogleMap?
- Fragmento dinámico de Android Google Maps en el soporte de RecyclerView
- ¿Cómo agregar título, fragmento e icono a ClusterItem?
- Hacer referencia a la biblioteca de google-play-services
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 de address
contiene las direcciones convertidas.
Si desea colocar su dirección en Google Maps, entonces es fácil de usar
Intent searchAddress = new Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+address)); startActivity(searchAddress);
O
Si necesitas obtener lat largo de tu dirección a continuación, utilice Google Place Api siguiente
Cree un método que devuelva un JSONObject con la respuesta de la llamada HTTP como 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; }
Ahora pasar 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 ti nd otros .. !! Gracias..!!
La solución de Ud_an con API actualizada
Nota : la clase LatLng forma parte de los Servicios de Google Play.
Obligatorio :
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.INTERNET"/>
Actualización: Si tiene SDK de destino 23 y superior, asegúrese de que se encarga del permiso de tiempo 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; }
El siguiente código funcionará 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 Testing Rd City State zip) que desea convertir a LatLng.
Así es como se puede encontrar la latitud y longitud de donde tenemos 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.
Una respuesta al problema de Kandha arriba:
Se lanza el "servicio de java.io.IOException no disponible" que ya dio los permisos e incluyen la biblioteca … puedo obtener vista del mapa … que lanza IOException en geocoder …
Acabo de agregar una captura IOException después de la prueba y se resolvió el problema
catch(IOException ioEx){ return null; }
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(); }
- Añadir sombra a la forma personalizada en Android
- No se puede encontrar AVD o SDK manager en Eclipse