Java 在 Android 中获取地图地址或位置地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2084065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:22:01  来源:igfitidea点击:

Get Map address or Location Address in Android

javaandroidgoogle-maps

提问by Yassin

I am writing an app that requires to get the current map location. My Map file works fine by it self, but I need to get the address (see addressStringbelow at the buttom) from another Activity. I tried getAddress/setAddress(setters/getters). They do not work. They always return 'no address' (the default).

我正在编写一个需要获取当前地图位置的应用程序。我的地图文件自己工作正常,但我需要addressString从另一个Activity. 我试过getAddress/ setAddress(setter/getter)。它们不起作用。他们总是返回“无地址”(默认)。

Here is my code...

这是我的代码...

How can I make this a standalone Java class??? Or get the address from another activity?

我怎样才能使它成为一个独立的 Java 类???或者从其他活动中获取地址?

Thanks a lot.

非常感谢。

This code works by itself.

这段代码自己工作。

Mat



import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class GetMapAddress extends MapActivity {

    MapController mapController;

    MyPositionOverlay positionOverlay;

    MapController mc;

    GeoPoint p;

    String addressString = "No address found";

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.map);

        MapView myMapView = (MapView) findViewById(R.id.myMapView);
        mapController = myMapView.getController();

        // Configure the map display options
        myMapView.setSatellite(true);
        myMapView.setStreetView(true);

        // Zoom in
        mapController.setZoom(17);

        myMapView.setBuiltInZoomControls(true);

        // Add the MyPositionOverlay
        positionOverlay = new MyPositionOverlay();
        List<Overlay> overlays = myMapView.getOverlays();
        overlays.add(positionOverlay);

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

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(criteria, true);

        Location location = locationManager.getLastKnownLocation(provider);

        updateWithNewLocation(location);

        locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);

        mc = myMapView.getController();
        String coordinates[] = {
            "1.352566007", "103.78921587"
        };
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);

        p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

        mc.animateTo(p);
        mc.setZoom(17);
        myMapView.invalidate();

    }

    private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            updateWithNewLocation(location);
        }

        public void onProviderDisabled(String provider) {
            updateWithNewLocation(null);
        }

        public void onProviderEnabled(String provider) {
        }

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

    /** Update the map with a new location */
    private void updateWithNewLocation(Location location) {
        TextView myLocationText = (TextView) findViewById(R.id.myLocationText);

        String latLongString;

        if (location != null) {
            // Update my location marker
            positionOverlay.setLocation(location);

            // Update the map location.
            Double geoLat = location.getLatitude() * 1E6;
            Double geoLng = location.getLongitude() * 1E6;
            GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue());

            mapController.animateTo(point);

            double lat = location.getLatitude();
            double lng = location.getLongitude();
            latLongString = "Lat:" + lat + "\nLong:" + lng;

            Geocoder gc = new Geocoder(this, Locale.getDefault());

            try {

                List<Address> addresses = gc.getFromLocation(lat, lng, 1);
                StringBuilder sb = new StringBuilder();

                if (addresses.size() > 0) {
                    Address address = addresses.get(0);

                    for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                        sb.append(address.getAddressLine(i)).append("\n");

                    sb.append(address.getCountryName());
                }
                addressString = sb.toString();
            } catch (IOException e) {
            }
        } else {

            // Place the CellID here
            latLongString = "No location found";

        }
        // This commented out line will include latitute and longtitute
        // myLocationText.setText("Your Phone is Currently at.. \n" + latLongString + "\n" +
        // addressString);

        myLocationText.setText("Your Phone is Currently at.. \n" + addressString);
        setAddress(addressString);

        ;

    }

    public void setAddress(String add) {
        this.addressString = add;
    }

    public String getAddress() {

        return addressString;
    }

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

回答by Christopher Orr

Either pass the address to your second Activityin the Intent, or if you need to do lookups from your second Activity, just call Geocoderfrom there.

要么将地址传递给您Activity在 中的第二个Intent,或者如果您需要从您的第二个中查找Activity,只需Geocoder从那里调用。

If you're somehow instantiating the above class (GetMapActivity) from your second Activityand calling the getAddressmethod, that won't work.

如果您以某种方式GetMapActivity从第二个实例化上述类 ( )Activity并调用该getAddress方法,那将不起作用。

回答by Shreesh

The following might work [move the code from onCreate and put it in a method]

以下可能有效[从 onCreate 移动代码并将其放入方法中]

public String getAddressString() {
        if (addressString.equals("default") {
          LocationManager lm = (LocationManager)act.getSystemService(Context.LOCATION_SERVICE);
          Criteria crit = new Criteria();
          crit.setAccuracy(Criteria.ACCURACY_FINE);
          String provider = lm.getBestProvider(crit, true);
          updateWithNewLocation(lm.getLastKnownLocation(provider));              
        }
        return addressString;
    }

回答by Scorpion

I have used the following code in my app and its working absolutely fine for me. Try this. Hope this will help you.

我在我的应用程序中使用了以下代码,它对我来说非常好。尝试这个。希望这会帮助你。

    //
    //  Write the location name.
    //

    try {

        Geocoder geo = new Geocoder(youractivityclassname.this.getApplicationContext(), Locale.getDefault());
        List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
        if (addresses.isEmpty()) {
            yourtextfieldname.setText("Waiting for Location");
        }
        else {
            if (addresses.size() > 0) {
                yourtextfieldname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
                //Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace(); // getFromLocation() may sometimes fail
    }