如何获取安卓GPS位置

2022-09-01 06:32:54

干杯,我正在尝试通过Android获取当前的GPS位置。我也遵循了本教程Vogellas文章。虽然它不起作用。使用LocationManager.NETWORK_PROVIDER我总是得到51的纬度和9的经度 - 无论我站在哪里。使用LocationManager.GPS_PROVIDER时,我什么也没得到。

虽然使用GMaps时一切都有效:S不知道为什么。如何像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

}

}

答案 1

这是您的问题:

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

纬度和经度是 -值,因为它们以度为单位表示位置。double

通过将它们转换为 ,您将丢弃逗号后面的所有内容,这会产生很大的不同。参见“十进制度 - 维基百科”int


答案 2

试一试:

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

推荐