定期获取位置并绘制标记以映射
Posted
技术标签:
【中文标题】定期获取位置并绘制标记以映射【英文标题】:Getting the location periodically and plotting markers to map 【发布时间】:2015-07-14 23:07:21 【问题描述】:我正在寻找在 android 中创建一个应用程序,该应用程序基本上跟踪手机位置并定期向 google maps api 添加一个标记,以便显示路线,我遇到的问题是我不知道如何定期在后台获取位置。
这是我的代码:
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)
任何帮助将不胜感激。
【问题讨论】:
您是否在 Google 上搜索过如何定期获取位置更新?这是您需要搜索的第一件事,当您找到解决方案时,使用获取的位置放置标记非常容易。我希望你明白我的意思。不要要求完整的解决方案。告诉我们你在实现你的功能时遇到了什么困难。我们很乐意为您提供帮助... 这是您的第一个查询,关于获取位置更新:developer.android.com/training/location/… 【参考方案1】:检查下面的代码,它可以帮助您获取按钮单击时的当前位置以及@some timeInterval。
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();
【讨论】:
以上是关于定期获取位置并绘制标记以映射的主要内容,如果未能解决你的问题,请参考以下文章
Workmanager(定期)获取位置并上传数据(Asynctask)被杀死
随着用户的移动,定期将地图上的所有标记移动到其更新/新的当前位置