Android получить название текущего местоположения - PullRequest
5 голосов
/ 14 февраля 2012

Эй, ребята, я хочу получить текущее местоположение с именем.Я сделал код для получения текущего местоположения (лат, ланг), как я могу показать относительное название места

(т.е.) 13.006389 - 80.2575: Адьяр, Ченнай, Индия

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // called when the location provider status changes. Possible status: OUT_OF_SERVICE, TEMPORARILY_UNAVAILABLE or AVAILABLE.
    }
    public void onProviderEnabled(String provider) {
        // called when the location provider is enabled by the user
    }
    public void onProviderDisabled(String provider) {
        // called when the location provider is disabled by the user. If it is already disabled, it's called immediately after requestLocationUpdates
    }

    public void onLocationChanged(Location location) {
        double latitute = location.getLatitude();
        double longitude = location.getLongitude();
        // do whatever you want with the coordinates
    }
});

Ответы [ 6 ]

7 голосов
/ 09 марта 2012

Это преобразует lat & lng в String Address, и я установил его в текстовом поле для вашего примера.Это делается с помощью концепции обратного геокодирования, и в Android есть класс Geocoder.

    //  Write the location name.
    //

    try {

        Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
        List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
        if (addresses.isEmpty()) {
            yourtextboxname.setText("Waiting for Location");
        }
        else {
            if (addresses.size() > 0) {
                yourtextboxname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
            }
        }
    }
2 голосов
/ 08 декабря 2012

Вот код, чтобы получить текущее местоположение и нарисовать его на Google Maps

public class Showmap 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.showmap);
        LocationManager 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);
    }

    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));
                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) + " ";
                    Log.i(address, address);
                }
            } 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.marker);
            // 24 is the height of image
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
            return true;
        }
    }
}
1 голос
/ 08 августа 2012

Используйте обратное геокодирование, введите широту и долготу и получите адрес.

Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
    try {
        List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);

        if(addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
            for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
            }
            myAddress.setText(strReturnedAddress.toString());

        }
        else{
            myAddress.setText("No Address returned!");
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        myAddress.setText("Canont get Address!");
    }
0 голосов
/ 10 июля 2019
public class MainActivity extends AppCompatActivity {
    double latitude, longitude;
    private TextView tvLocation;
    private Button btnGetLocation;
    private FusedLocationProviderClient locationProviderClient;
    private Geocoder geocoder;
    private List<Address> addresses;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        requestPermission();

        locationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        tvLocation = findViewById(R.id.tv_location);

        geocoder = new Geocoder(MainActivity.this, Locale.getDefault());

        btnGetLocation = findViewById(R.id.btn_location);
        btnGetLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                    return;
                }
                locationProviderClient.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {

                        if (location != null) {
                            tvLocation.setText(location.toString());
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();

                            try {

                                addresses = geocoder.getFromLocation(latitude, longitude, 1);

                                String addressLine1 = addresses.get(0).getAddressLine(0);
                                Log.e("line1", addressLine1);

                                String city = addresses.get(0).getLocality();
                                Log.e("city", city);

                                String state = addresses.get(0).getAdminArea();
                                Log.e("state", state);

                                String pinCode = addresses.get(0).getPostalCode();
                                Log.e("pinCode", pinCode);

                                String fullAddress = addressLine1 + ",  " + city + ",  " + state + ",  " + pinCode;
                                tvLocation.setText(fullAddress);

                            } catch (IOException e) {
                                e.printStackTrace();
                                Log.e("MainActivity", e.getMessage());
                            }

                        }
                    }
                });

            }
        });

    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
    }
}
0 голосов
/ 06 марта 2012

Это только для подсказки добавить свой код!

public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
    if (location != null) {
        System.out.println("in onlocationchanged");
         String locationString=location.convert(location.getLatitude(),1);
         Toast.makeText(this,"locationString=="+locationString, Toast.LENGTH_LONG).show();
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        String currentLocation = "The location is changed to Lat: " + lat + " Lng: " + lng;
        Toast.makeText(this,currentLocation, Toast.LENGTH_LONG).show();

используйте этот два метода

public double getLattitude() {
    return lattitude;
}

}
public double getLongitude() {
    return longitude;
0 голосов
/ 14 февраля 2012

Фраза, которую вы ищете - «Обратное геокодирование». Другой вопрос в StackOverflow обсуждает ту же тему. Вы можете использовать этот ответ:)

...