我正在开发一个Android应用程序,它使用当前用户位置获取结果.
我使用以下代码来获取位置:
LocationManager locationManager =
(LocationManager) getSystemService(LOCATION_SERVICE);
Location currentLocation =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Run Code Online (Sandbox Code Playgroud)
当我在设备上运行它时,它给我一个位置的空值.
但是,当我使用NETWORK_PROVIDER它工作正常时,设备是否有额外的设置使用GPS?
我的设备是Galaxy Tab P-1000.
调用getLastKnownLocation()与GPS_PROVIDER返回缓存值.如果没有最近的位置,它将返回null.使用LocationListener的onLocationChanged()回调来代替.
这可能需要一段时间,但你会获得一个新的定位.
NETWORK_PROVIDER位置并不总是准确的,因为它基于细胞位点三角测量
使用:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
Run Code Online (Sandbox Code Playgroud)
对于 locationListener 你可以使用这个:
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location
// provider.
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
if (location != null) {
GeoPoint point2 = new GeoPoint(
(int) (location.getLatitude() * 1E6), (int) (location
.getLongitude() * 1E6));
// Toast.makeText(getBaseContext(),
// "Latitude: " + location.getLatitude() +
// " Longitude: " + location.getLongitude(),
// Toast.LENGTH_SHORT).show();
//
mapView.getController().animateTo(point2);
mapView.getController().setZoom(15);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = LbsGeocodingActivity.this.getResources()
.getDrawable(R.drawable.new3pin);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(
drawable, LbsGeocodingActivity.this);
point = new GeoPoint((int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
String address = convertPointToLocation(point);
String delims = ",";
String[] tokens = address.split(delims);
OverlayItem overlayitem = null;
if(tokens.length==1)
{
overlayitem = new OverlayItem(point,
"New Location", "Locality:"+"\nCity:"+"\nCountry: "+tokens[0]);
}
else if(tokens.length==2)
{
overlayitem = new OverlayItem(point,
"New Location", "Locality:"+"\nCity: "+tokens[0]+"\nCountry: "+tokens[1]);
}
else if(tokens.length==3)
{
overlayitem = new OverlayItem(point,
"New Location", "Locality: "+tokens[0]+"\nCity: "+tokens[1]+"\nCountry: "+tokens[2]);
}
else
{
overlayitem = new OverlayItem(point,
"New Location", address);
}
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.clear();
mapOverlays.add(itemizedoverlay);
// mapView.invalidate();
}
}
Run Code Online (Sandbox Code Playgroud)
我已经在我的代码中使用了它并且效果很好。
| 归档时间: |
|
| 查看次数: |
4103 次 |
| 最近记录: |