如何获取安卓GPS定位

35

大家好,我正在尝试通过Android获取当前GPS位置。我按照这个教程Vogella的文章去做,但是好像不起作用。当我使用LocationManager.NETWORK_PROVIDER时,无论我在哪里,我都得到纬度为51,经度为9。而当我使用LocationManager.GPS_PROVIDER时,我什么也没有得到。

然而,在使用GMaps时一切正常,但我不知道为什么。我该如何像GMaps一样获取当前的GPS位置呢?以下是我的代码:

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

}

}

2
为了更高级和更简单地获取GPS位置,您可以使用此库:https://github.com/delight-im/Android-SimpleLocation - caw
请参考以下链接,了解如何在Android中以编程方式获取当前GPS位置:https://dev59.com/UHI_5IYBdhLWcg3wJPZu#38897436 - Syed Raza Mehdi
6个回答

31

这是您的问题:

int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());

纬度和经度是双精度数值,因为它们代表以度为单位的位置。

将它们强制转换为整数会舍弃小数点后的所有内容,这会造成很大的差异。请参见“十进制度数-维基”


1
已经想到这可能是一些愚蠢的事情。你已经证明了它;P 谢谢。 - Sebastian

23

试一试:

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

4
谢谢回答,虽然我已经尝试过你上面的代码,并且只是将我的代码简化到最简单的解决方案来向你展示问题;P。无论如何还是谢谢。 - Sebastian

13

这段代码存在一个问题:

int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
你可以将 `int` 改为 `double`。
double latitude = location.getLatitude();
double longitude = location.getLongitude();

9

通过将latlon更改为double,解决了最初的问题。

我想在使用Location location = locationManager.getLastKnownLocation(bestProvider);解决方案时添加注释。当其他应用正在监听位置信息时,它可以找到上次已知的位置。例如,如果自设备启动以来没有任何应用这样做,代码将返回零(最近花了一些时间才弄清楚)。

此外,通过使用locationManager.removeUpdates(this);停止监听位置信息也是一个不错的实践。

即使在manifest中授予权限,只有在设备的Android设置中启用了位置服务时,代码才能正常工作。


0

摘录:

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

如您所见,一个线程正在用户界面活动的主线程旁边运行,不断显示GPS经纬度、当前时间和随机骰子投掷结果。
如果您感兴趣,请查看完整代码: 在单独线程中显示带有随机骰子投掷和当前时间的GPS位置

0

为这个项目工作了一天。它可能对你有用。 我压缩并结合了网络和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 //////////
//////////

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接