Android 定期获取位置并绘制要映射的标记
我想在安卓系统中创建一个应用程序,基本上跟踪手机的位置,并定期在谷歌地图api中添加一个标记,以便显示路线。我的问题是,我不知道如何在后台定期获取位置 这是我的密码:Android 定期获取位置并绘制要映射的标记,android,google-maps,location,Android,Google Maps,Location,我想在安卓系统中创建一个应用程序,基本上跟踪手机的位置,并定期在谷歌地图api中添加一个标记,以便显示路线。我的问题是,我不知道如何在后台定期获取位置 这是我的密码: public class MapsActivity extends FragmentActivity implements LocationListener { private GoogleMap mMap; // Might be null if Google Play services APK is not availabl
public class MapsActivity extends FragmentActivity implements LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
Button btnCurrent, btnPrevious;
ArrayList<Double> latitude = new ArrayList<>();
ArrayList<Double> longitude = new ArrayList<>();
LocationManager lm;
LocationListener ll;
Location networkLocation;
Location gpsLocation;
double LONG;
double LAT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
networkLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 10, 0, new android.location.LocationListener() {
@Override
public void onLocationChanged(Location location) {
LONG = networkLocation.getLongitude();
LAT = networkLocation.getLatitude();
latitude.add(LAT);
longitude.add(LONG);
Log.d("COORDS", LAT+" , "+LONG);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
});
setUpMapIfNeeded();
btnCurrent = (Button)findViewById(R.id.btn_currentLoc);
btnPrevious = (Button) findViewById(R.id.btn_prevLoc);
btnCurrent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMap.clear();
double curLong, curLat;
String test = lm.getAllProviders().toString();
LatLng CurrentLoc;
Log.d("PROVIDERS ", test);
if((lm.isProviderEnabled("gps"))==true)
{
curLong = gpsLocation.getLongitude();
curLat = gpsLocation.getLatitude();
CurrentLoc = new LatLng(curLat,curLong);
Log.d("GPS", "true");
}else
{
curLong = networkLocation.getLongitude();
curLat = networkLocation.getLatitude();
CurrentLoc = new LatLng(curLat,curLong);
Log.d("GPS", "false");
}
mMap.addMarker(new MarkerOptions().position(new LatLng(curLat,curLong)).title("LOCATION "+ curLat + ", " + curLong));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(CurrentLoc,15));
Log.d("LOCATION", curLat + "," + curLong);
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i = 0;i<latitude.size();i++)
{
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude.get(i),longitude.get(i))).title("LOCATION "+ latitude.get(i) + ", " + longitude.get(i)));
Log.d("LOCATION", latitude.get(i)+ "," + longitude.get(i));
}
}
});
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
}
private void getCurrentLocation(){
}
private void seeAllLocations(){
}
@Override
public void onLocationChanged(Location location) {
}
}
公共类MapsActivity扩展FragmentActivity实现LocationListener{
私有GoogleMap mMap;//如果Google Play services APK不可用,则可能为空。
按钮btnCurrent,btnPrevious;
ArrayList纬度=新ArrayList();
ArrayList经度=新的ArrayList();
位置经理lm;
地点:L;
位置网络位置;
定位;
双倍长;
双LAT;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
lm=(LocationManager)getSystemService(Context.LOCATION\u服务);
networkLocation=lm.getLastKnownLocation(LocationManager.NETWORK\u提供程序);
gpsLocation=lm.getLastKnownLocation(LocationManager.GPS\U提供程序);
lm.requestLocationUpdates(lm.GPS_PROVIDER,10,0,新的android.location.LocationListener(){
@凌驾
已更改位置上的公共无效(位置){
LONG=networkLocation.getLongitude();
LAT=networkLocation.getLatitude();
纬度加(纬度);
经度。添加(长);
对数d(“坐标”,纬度+“,”+长);
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
}
});
setupmapifneed();
btn电流=(按钮)findViewById(R.id.btn\U currentLoc);
btnPrevious=(按钮)findViewById(R.id.btn\u prevLoc);
btncCurrent.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
mMap.clear();
双卷发,卷发;
字符串测试=lm.getAllProviders().toString();
LatLng-CurrentLoc;
Log.d(“供应商”,测试);
如果((lm.isProviderEnabled(“gps”))==真)
{
curLong=gpsLocation.getLongitude();
curLat=gpsLocation.getLatitude();
CurrentLoc=新板条(卷边、卷边);
日志d(“GPS”、“真实”);
}否则
{
curLong=networkLocation.getLongitude();
curLat=networkLocation.getLatitude();
CurrentLoc=新板条(卷边、卷边);
日志d(“GPS”、“假”);
}
mMap.addMarker(新MarkerOptions().position(新LatLng(curLat,curLong)).title(“位置“+curLat+”,“+curLong”);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(当前位置,15));
Log.d(“位置”,curLat+,“+curLong”);
}
});
btnPrevious.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
对于(int i=0;i请检查下面的代码,它可以帮助您在单击按钮时获取当前位置,并在某个时间间隔内获取
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
// Location updates intervals in sec
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
private static int DISPLACEMENT = 10; // 10 meters
// UI elements
private TextView lblLocation;
private Button btnShowLocation, btnStartLocationUpdates;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblLocation = (TextView) findViewById(R.id.lblLocation);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
}
// Show location button click listener
btnShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayLocation();
}
});
// Toggling the periodic location updates
btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
togglePeriodicLocationUpdates();
}
});
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onResume() {
super.onResume();
checkPlayServices();
// Resuming the periodic location updates
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
/**
* Method to display the location on UI
* */
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longitude);
} else {
lblLocation
.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
/**
* Method to toggle periodic location updates
* */
private void togglePeriodicLocationUpdates() {
if (!mRequestingLocationUpdates) {
// Changing the button text
btnStartLocationUpdates
.setText(getString(R.string.btn_stop_location_updates));
mRequestingLocationUpdates = true;
// Starting the location updates
startLocationUpdates();
Log.d(TAG, "Periodic location updates started!");
} else {
// Changing the button text
btnStartLocationUpdates
.setText(getString(R.string.btn_start_location_updates));
mRequestingLocationUpdates = false;
// Stopping the location updates
stopLocationUpdates();
Log.d(TAG, "Periodic location updates stopped!");
}
}
/**
* Creating google api client object
* */
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Creating location request object
* */
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
/**
* Method to verify google play services on the device
* */
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
/**
* Starting the location updates
* */
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Stopping location updates
*/
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
/**
* Google api callback methods
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
@Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
Toast.makeText(getApplicationContext(), "Location changed!",
Toast.LENGTH_SHORT).show();
// Displaying the new location on UI
displayLocation();
}
}
你有没有在谷歌上搜索过如何定期获取位置更新?这是你需要搜索的第一件事,当你找到解决方案时,使用获取的位置放置标记非常简单。我希望你明白我的意思。不要问完整的解决方案。告诉我们你在实现功能方面遇到了什么困难。我们很乐意帮助你这是您的第一个查询,关于获取位置更新: