Java 如何获取 Android GPS 位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16498450/
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
How to get Android GPS location
提问by Sebastian
Cheers, I'm trying to get the current GPS-Location via Android. I followed this Tutorialand Vogellas articleaswell. Though it ain't working. When using LocationManager.NETWORK_PROVIDER I'm always getting a latitude of 51 and longitude of 9 - no matter where I stand. When using LocationManager.GPS_PROVIDER, I'm getting nothing at all.
干杯,我正在尝试通过 Android 获取当前的 GPS 位置。我也跟着这个教程和Vogellas 文章。虽然它不起作用。使用 LocationManager.NETWORK_PROVIDER 时,我总是得到 51 纬度和 9 经度 - 无论我站在哪里。使用 LocationManager.GPS_PROVIDER 时,我什么也没得到。
Though Everything works when using GMaps :S No idea why. How can I get the current GPS Location like GMaps does?
虽然使用 GMaps 时一切正常:S 不知道为什么。如何像 GMaps 一样获取当前的 GPS 位置?
Here's my code:
这是我的代码:
package com.example.gpslocation;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
public class GPS_Location extends Activity implements LocationListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps__location);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.gps__location, menu);
return true;
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
采纳答案by Lukas Knuth
Here's your problem:
这是你的问题:
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
Latitude and Longitude are double
-values, because they represent the location in degrees.
纬度和经度是 - 值double
,因为它们以度数表示位置。
By casting them to int
, you're discarding everything behind the comma, which makes a big difference. See "Decimal Degrees - Wiki"
通过将它们强制转换为int
,您将丢弃逗号后面的所有内容,这会产生很大的不同。请参阅“十进制度 - Wiki”
回答by Sercan Ozdemir
Give it a try :
试一试 :
public LatLng getLocation()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
Double lat,lon;
try {
lat = location.getLatitude ();
lon = location.getLongitude ();
return new LatLng(lat, lon);
}
catch (NullPointerException e){
e.printStackTrace();
return null;
}
}
回答by azatserzhan
This code have one problem:
这段代码有一个问题:
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
You can change int
to double
您可以更改int
为double
double latitude = location.getLatitude();
double longitude = location.getLongitude();
回答by Alexei Martianov
The initial issue is solved by changing lat
and lon
to double.
最初的问题是通过改变lat
和lon
加倍来解决的。
I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider);
It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).
我想在解决方案中添加评论,Location location = locationManager.getLastKnownLocation(bestProvider);
它可以在其他应用程序为此查找时找出最后一个已知位置。例如,如果自设备启动以来没有应用程序这样做,代码将返回零(我最近花了一些时间来弄清楚)。
Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);
此外,在不需要时停止聆听是一个好习惯 locationManager.removeUpdates(this);
Also, even with permissions in manifest
, the code works when location service is enabled in Android settings on a device.
此外,即使具有 中的权限manifest
,当在设备的 Android 设置中启用位置服务时,代码也能正常工作。
回答by Animesh Shrivastav
Excerpt:-
摘抄:-
try
{
cnt++;scnt++;now=System.currentTimeMillis();r=rand.nextInt(6);r++;
loc=lm.getLastKnownLocation(best);
if(loc!=null){lat=loc.getLatitude();lng=loc.getLongitude();}
Thread.sleep(100);
handler.sendMessage(handler.obtainMessage());
}
catch (InterruptedException e)
{
Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
}
As you can see above, a thread is running alongside main thread of user-interface activity which continuously displays GPS lat,long alongwith current time and a random dice throw.
正如您在上面看到的,一个线程与用户界面活动的主线程一起运行,该线程持续显示 GPS 纬度、长度以及当前时间和随机掷骰子。
IF you are curious then just check the full code: GPS Location with a randomized dice throw & current time in separate thread
如果您很好奇,那么只需查看完整代码: GPS 位置与随机掷骰子和当前时间在单独的线程中
回答by phnghue
Worked a day for this project. It maybe useful for u. I compressed and combined both Network and GPS. Plug and play directly in MainActivity.java (There are some DIY function for display result)
为这个项目工作了一天。它可能对你有用。我压缩并结合了网络和 GPS。直接在MainActivity.java中即插即用(显示结果有一些DIY功能)
///////////////////////////////////
////////// LOCATION PACK //////////
//
// locationManager: (LocationManager) for getting LOCATION_SERVICE
// osLocation: (Location) getting location data via standard method
// dataLocation: class type storage locztion data
// x,y: (Double) Longtitude, Latitude
// location: (dataLocation) variable contain absolute location info. Autoupdate after run locationStart();
// AutoLocation: class help getting provider info
// tmLocation: (Timer) for running update location over time
// LocationStart(int interval): start getting location data with setting interval time cycle in milisecond
// LocationStart(): LocationStart(500)
// LocationStop(): stop getting location data
//
// EX:
// LocationStart(); cycleF(new Runnable() {public void run(){bodyM.text("LOCATION \nLatitude: " + location.y+ "\nLongitude: " + location.x).show();}},500);
//
LocationManager locationManager;
Location osLocation;
public class dataLocation {double x,y;}
dataLocation location=new dataLocation();
public class AutoLocation extends Activity implements LocationListener {
@Override public void onLocationChanged(Location p1){}
@Override public void onStatusChanged(String p1, int p2, Bundle p3){}
@Override public void onProviderEnabled(String p1){}
@Override public void onProviderDisabled(String p1){}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,0,0,this);
if (locationManager != null) {
osLocation = locationManager.getLastKnownLocation(provider);
return osLocation;
}
}
return null;
}
}
Timer tmLocation=new Timer();
public void LocationStart(int interval){
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
final AutoLocation autoLocation = new AutoLocation();
tmLocation=cycleF(new Runnable() {public void run(){
Location nwLocation = autoLocation.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
location.y = nwLocation.getLatitude();
location.x = nwLocation.getLongitude();
} else {
//bodym.text("NETWORK_LOCATION is loading...").show();
}
Location gpsLocation = autoLocation.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
location.y = gpsLocation.getLatitude();
location.x = gpsLocation.getLongitude();
} else {
//bodym.text("GPS_LOCATION is loading...").show();
}
}}, interval);
}
public void LocationStart(){LocationStart(500);};
public void LocationStop(){stopCycleF(tmLocation);}
//////////
///END//// LOCATION PACK //////////
//////////
/////////////////////////////
////////// RUNTIME //////////
//
// Need library:
// import java.util.*;
//
// delayF(r,d): execute runnable r after d millisecond
// Halt by execute the return: final Runnable rn=delayF(...); (new Handler()).post(rn);
// cycleF(r,i): execute r repeatedly with i millisecond each cycle
// stopCycleF(t): halt execute cycleF via the Timer return of cycleF
//
// EX:
// delayF(new Runnable(){public void run(){ sig("Hi"); }},2000);
// final Runnable rn=delayF(new Runnable(){public void run(){ sig("Hi"); }},3000);
// delayF(new Runnable(){public void run(){ (new Handler()).post(rn);sig("Hello"); }},1000);
// final Timer tm=cycleF(new Runnable() {public void run(){ sig("Neverend"); }}, 1000);
// delayF(new Runnable(){public void run(){ stopCycleF(tm);sig("Ended"); }},7000);
//
public static Runnable delayF(final Runnable r, long delay) {
final Handler h = new Handler();
h.postDelayed(r, delay);
return new Runnable(){
@Override
public void run(){h.removeCallbacks(r);}
};
}
public static Timer cycleF(final Runnable r, long interval) {
final Timer t=new Timer();
final Handler h = new Handler();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {h.post(r);}
}, interval, interval);
return t;
}
public void stopCycleF(Timer t){t.cancel();t.purge();}
public boolean serviceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
//////////
///END//// RUNTIME //////////
//////////