如何以编程方式获取设备的当前地理位置

时间:2011-11-28 05:06:07

标签: android geolocation

我需要获取设备当前的地理位置。

情景:如果我在US ..:

my device location should be US

与我在UK时的情况相同:

my device location should be UK

我需要示例代码来查找此地理位置。(location determined by Network Location Provider

5 个答案:

答案 0 :(得分:7)

如果您想获取当前的国家/地区代码,可以查看Geocoder,您可以使用Address来获取getCountryCode方法How do I get the current GPS location programmatically in Android?。像这样的东西

Geocoder geocoder = new Geocoder(this);
List<Address> addresses = null;

try {
    addresses = geocoder.getFromLocation(
        location.getLatitude(),
        location.getLongitude(), 1);
} catch (IOException e) {
    e.printStackTrace();
}

if (addresses != null && addresses.size() > 0) {
    Address address = addresses.get(0);
    String countryCode = address.getCountryCode();
}

就目前的纬度和经度而言,有很多关于如何做到这一点的信息

答案 1 :(得分:3)

有很多可用的教程,在这里,我已经阅读Fedor获取用户当前位置的不错答案,试试这个What is the simplest and most robust way to get the user's current location in Android?。在代码中回答你的问题有点冗长,在答案中他也解释得很好..

另请参阅 Android开发人员指南 Obtaining User Location,了解位置管理器在Android中的工作原理..

感谢。

答案 2 :(得分:3)

这是代码

主要MapActivity

  public class WhereIam extends MapActivity {
MapController mapController;
MyPositionOverlay positionOverlay;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    MapView myMapView=(MapView)findViewById(R.id.myMapView);

    myMapView.setSatellite(true);


    myMapView.setBuiltInZoomControls(true);
    mapController=myMapView.getController();
    mapController.setZoom(17);
    positionOverlay = new MyPositionOverlay();
    List<Overlay> overlays = myMapView.getOverlays();
    overlays.add(positionOverlay);

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

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

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

        updateWithNewLocation(location);
        locationManager.requestLocationUpdates(provider, 2000, 10,
                locationListener);  
}
private void updateWithNewLocation(Location location) {
    if(location!=null)  {
        // Update the map location.
        positionOverlay.setLocation(location);
        Double geoLat = location.getLatitude()*1E6;
        Double geoLng = location.getLongitude()*1E6;
        GeoPoint point = new GeoPoint(geoLat.intValue(),
        geoLng.intValue());
        mapController.animateTo(point);

    }
}   
@Override
protected boolean isRouteDisplayed() {

    return true;
}

另一个MyPositionOverlay类

public class MyPositionOverlay extends Overlay {
Location location;
private final int mRadius = 5;
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
  Projection projection = mapView.getProjection();
  if (shadow == false) {
  // Get the current location
  Double latitude = location.getLatitude()*1E6;
  Double longitude = location.getLongitude()*1E6;
  GeoPoint geoPoint;
  geoPoint = new GeoPoint(latitude.intValue(),longitude.intValue());
  // Convert the location to screen pixels
  Point point = new Point();
  projection.toPixels(geoPoint, point);
  RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
  point.x + mRadius, point.y + mRadius);
  // Setup the paint
  Paint paint = new Paint();
  paint.setARGB(250, 255, 0, 0);
  paint.setAntiAlias(true);
  paint.setFakeBoldText(true);
  Paint backPaint = new Paint();
  backPaint.setARGB(175, 50, 50, 50);
  backPaint.setAntiAlias(true);
  RectF backRect = new RectF(point.x + 2 + mRadius,
  point.y - 3*mRadius,
  point.x + 65, point.y + mRadius);
  // Draw the marker
  canvas.drawOval(oval, paint);
  canvas.drawRoundRect(backRect, 5, 5, backPaint);
  canvas.drawText("Here I Am", point.x + 2*mRadius, point.y, paint);
  }
  super.draw(canvas, mapView, shadow);
  }
  @Override
 public boolean onTap(GeoPoint point, MapView mapView) {
 return false;
}
 public Location getLocation() {
  return location;
  }
  public void setLocation(Location location) {
  this.location = location;
  }
}

答案 3 :(得分:1)

以上解决方案也是正确的,但是如果location为null,则会崩溃应用程序或无法正常工作。获得Android的纬度和经度的最佳方法是:

 Geocoder geocoder;
     String bestProvider;
     List<Address> user = null;
     double lat;
     double lng;

    LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

     Criteria criteria = new Criteria();
     bestProvider = lm.getBestProvider(criteria, false);
     Location location = lm.getLastKnownLocation(bestProvider);

     if (location == null){
         Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show();
      }else{
        geocoder = new Geocoder(activity);
        try {
            user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        lat=(double)user.get(0).getLatitude();
        lng=(double)user.get(0).getLongitude();
        System.out.println(" DDD lat: " +lat+",  longitude: "+lng);

        }catch (Exception e) {
                e.printStackTrace();
        }
    }

答案 4 :(得分:0)

public class LocationHelper {
LocationManager locationManager;

public boolean getLocation(Context context)
{
    if(locationManager==null)
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    List<String> providers = locationManager.getAllProviders();
    Location location;

    for(String provider: providers) {
    try {
        if(locationManager.isProviderEnabled(provider)) {
            //dont use listener, it sometimes does not work             
            location = locationManager.getLastKnownLocation(provider);  
            if(location != null) {
                getDeviceInfo(location, context);
                break;
            }
            }
    } catch (Exception e) {

    }
    }

    return true;
}

private void getDeviceInfo(Location location, Context context) {
     Geocoder geocoder = new Geocoder(context);
     List<Address> addresses = null;

     try {
         addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
     } catch (Exception e) {
         e.printStackTrace();
     }

     if (addresses != null && addresses.size() > 0) {
         Address address = addresses.get(0);
         String countryCode = address.getCountryCode();
     //any other data...
     }
}

}