android 获取当前位置名称

发布于 2025-01-05 05:10:54 字数 1083 浏览 3 评论 0原文

我想获取当前位置和名称。我编码获取当前位置(纬度,朗),如何显示相对地名?

(即)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
    }
});

I want to get the current location with name. I did coding for get current location (lat,lang), how can I show the relative place name?

(ie) 13.006389 - 80.2575 : Adyar,Chennai,India

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
    }
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

暖风昔人 2025-01-12 05:10:54

这会将纬度和纬度转换为lng 输入字符串地址,我已将其设置在示例的文本字段中。这是通过使用反向地理编码和地理编码的概念来完成的。 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 {
            yourtextboxname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
        }
    }

This will convert the lat & lng into String Address and i have set it in the text field for your example. This is done by using the concept of Reverse Geocoding & there is a class called Geocoder in Android.

    //  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 {
            yourtextboxname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
        }
    }
慢慢从新开始 2025-01-12 05:10:54

这是获取当前位置并将其绘制在 Google 地图上的代码

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;
        }
    }
}

Here is code to get current location and draw it on 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;
        }
    }
}
王权女流氓 2025-01-12 05:10:54

使用反向地理编码,输入纬度和经度并获取地址。

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!");
    }

Use reverse geocoding,feed the latitude and longitude and get the address.

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!");
    }
北风几吹夏 2025-01-12 05:10:54

您要查找的短语是“反向地理编码”。 StackOverflow 上的另一个问题讨论了相同的主题 - 您可以使用该人选择的答案:)

The phrase you're looking for is "Reverse Geocoding". Another question on StackOverflow discusses the same topic- You can use that one's selected answer :)

平定天下 2025-01-12 05:10:54

这仅用于提示添加您的代码!

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;

This is only for Hint add your code !

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();

use this two method

public double getLattitude() {
    return lattitude;
}

}
public double getLongitude() {
    return longitude;
暗恋未遂 2025-01-12 05:10:54
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);
    }
}
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);
    }
}
长途伴 2025-01-12 05:10:54

这是我获取当前国家/地区名称的代码。

private String getCountry() {
        String country_name = null;
        LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        Geocoder geocoder = new Geocoder(getApplicationContext());
        for(String provider: lm.getAllProviders()) {
            @SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
            if(location!=null) {
                try {
                    List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                    if(addresses != null && addresses.size() > 0) {
                        country_name =addresses.get(0).getCountryName();
                        return country_name;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
        return null;
    }

但不要忘记在清单文件中添加此权限。

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

Here Is my code to get the current country Name.

private String getCountry() {
        String country_name = null;
        LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        Geocoder geocoder = new Geocoder(getApplicationContext());
        for(String provider: lm.getAllProviders()) {
            @SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
            if(location!=null) {
                try {
                    List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                    if(addresses != null && addresses.size() > 0) {
                        country_name =addresses.get(0).getCountryName();
                        return country_name;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
        return null;
    }

But don't forget to add this permission in the manifest file.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文