问题
I need to get the device's current geographical location.
Scenario : if I am in US
..:
my device location should be US
Same as in the case, when I am in UK
:
my device location should be UK
I need the sample code for finding this geographical location.(location determined by Network Location Provider
)
回答1:
If you want to get the current country code, you want to look into Geocoder which you can use to get an Address which provides a getCountryCode method. Something like this
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();
}
As far as getting the current latitude and longitude, there is plenty of information out there on how to do that
- How do I get the current GPS location programmatically in Android?
- What is the simplest and most robust way to get the user's current location on Android?
- http://developer.android.com/guide/topics/location/index.html
回答2:
Here is the code
Main 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;
}
Another MyPositionOverlay class
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:
There are many tutorial available for this, Here on SO i have read nice answer by Fedor
on get current location of the user, try this What is the simplest and most robust way to get the user's current location in Android?. To give answer of your question in code is some lengthy, also in that answer he explain nice way..
Also go through Android developer guide Obtaining User Location for basic information how location manager works in android..
Thanks.
回答4:
Above solutions is also correct, but some time if location is null then it crash the app or not working properly. The best way to get Latitude and Longitude of android is:
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();
}
}
回答5:
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...
}
}
}
来源:https://stackoverflow.com/questions/8291728/how-i-can-get-current-geographical-location-of-the-device-programatically