如何以编程方式获取设备的当前地理位置
Posted
技术标签:
【中文标题】如何以编程方式获取设备的当前地理位置【英文标题】:How I can get current geographical location of the device programatically 【发布时间】:2011-11-28 05:06:06 【问题描述】:我需要获取设备的当前地理位置。
场景:如果我在US
..:
my device location should be US
和我在UK
的情况一样:
my device location should be UK
我需要查找此地理位置的示例代码。(location determined by Network Location Provider
)
【问题讨论】:
您没有尝试查看相关问题吗:***.com/questions/3145089/… @Frankenstein 这个问题可能应该改写,但似乎是如何获得与经纬度略有不同的当前国家代码 @Craigy yeh 你是对的..但我想...如果 manu 调查过相关的内容会找到答案和另一件事..如果看到其他..会知道如何获得纬度/经度然后他会问如何从纬度/经度知道国家名称..然后..同时提出问题以获取地址行..相关链接也可以解决..因为这些是常见问题并且回答得很好已经在 SO...所以 Manu 只需要查看其他 SO 问题,他的所有疑虑都会被清除.. 【参考方案1】:如果您想获取当前的国家/地区代码,您需要查看Geocoder
,您可以使用它来获取提供getCountryCode
方法的Address
。像这样的
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();
就获取当前的纬度和经度而言,有很多关于如何做到这一点的信息
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【讨论】:
我们如何获得位置? 我还需要找到网络位置提供商确定的位置 执行addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1)时出现java.lang.NullPointerException; 您的位置变量为空。你将不得不调试它。使用用于获取位置的代码发布一个新问题【参考方案2】:这里是代码
主地图活动
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】:有很多可用的教程,在这里我已经阅读了Fedor
关于获取用户当前位置的好答案,试试这个What is the simplest and most robust way to get the user's current location in Android?。用代码回答你的问题有点冗长,在那个答案中他解释得很好..
还可以通过 Android 开发者指南 Obtaining User Location 了解位置管理器如何在 android 中工作的基本信息。
谢谢。
【讨论】:
【参考方案4】:上述解决方案也是正确的,但有时如果位置为空,则会导致应用程序崩溃或无法正常工作。获取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();
【讨论】:
【参考方案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...
【讨论】:
以上是关于如何以编程方式获取设备的当前地理位置的主要内容,如果未能解决你的问题,请参考以下文章
如何以编程方式在 Android 的 API 23 及更高版本中获取位置(纬度、经度)?