我想知道如何实现在一部手机上获取位置并显示手机位置。
就像超级驾驶室应用程序一样。当我们要求从一个地方到另一个地方的车程。他们为我们分配一个出租车同时应用程序还显示出租车司机的位置。我想知道他们如何实施,如果一些机构指导我们或为此提供相关文件。在此先感谢,它非常适合
答案 0 :(得分:0)
您可以使用以下代码跟踪位置事件的变化
DeviceLocation.java
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class DeviceLocation extends Service {
private GPSTracker gpsTracker;
private Handler handler = new Handler();
private Timer timer = new Timer();
private Distance pastDistance = new Distance();
private Distance currentDistance = new Distance();
public static double DISTANCE;
boolean flag = true;
private double totalDistance;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.v("Location1", "********* " + Thread.currentThread().getId());
gpsTracker = new GPSTracker(this);
// below code is to track change in past and present location events
// TimerTask timerTask = new TimerTask() {
//
// @Override
// public void run() {
// Log.v("Location2", "********* " + Thread.currentThread().getId());
// handler.post(new Runnable() {
//
// @Override
// public void run() {
// Log.v("Location3", "********* " + Thread.currentThread().getId());
// if (flag) {
// pastDistance.setLatitude(gpsTracker.getLocation().getLatitude());
// pastDistance.setLongitude(gpsTracker.getLocation().getLongitude());
// flag = false;
// } else {
// currentDistance.setLatitude(gpsTracker.getLocation().getLatitude());
// currentDistance.setLongitude(gpsTracker.getLocation().getLongitude());
// flag = comapre_LatitudeLongitude();
// }
// }
// });
// }
// };
// timer.schedule(timerTask, 0, 5000);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
Log.v("Location2", "********* " + Thread.currentThread().getId());
handler.post(new Runnable() {
@Override
public void run() {
// send to server or device you need to send via GCM
SendMessage(String.valueOf(gpsTracker.getLocation().getLatitude())
String.valueOf(gpsTracker.getLocation().getLongitude()));
}
});
}
};
timer.schedule(timerTask, 0, 5000);
return START_STICKY;
}
public void Track(String lat, String lng) {
Sender sender = new Sender("AIzaSyAlXGdj3TGPAnKBiuhn4yxXgLKxwmHJnMY");
String GcmId = new TrackPref(this).getTrackId();
Message message = new Message.Builder()
.collapseKey("and_app")
.delayWhileIdle(true)
.addData("action", "location")
.addData("Lat", lat)
.addData("Long", lng)
.timeToLive(600)
.build();
Result result = null;
try {
result = sender.send(message, GcmId, 2);
} catch (IOException e) {
e.printStackTrace();
}
if (result.getMessageId() != null) {
String canonicalRegId = result.getCanonicalRegistrationId();
Log.d("abc", result.toString());
} else {
String error = result.getErrorCodeName();
}
}
private void SendMessage(final String lat, final String lng) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
Track(lat, lng);
return null;
}
@Override
protected void onPostExecute(String msg) {
}
}.execute();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("--------------------------------onDestroy -stop service ");
timer.cancel();
DISTANCE = totalDistance ;
}
private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
public boolean comapre_LatitudeLongitude() {
Log.v("Location4", "********* " + Thread.currentThread().getId());
if (pastDistance.getLatitude() == currentDistance.getLatitude() && pastDistance.getLongitude() == currentDistance.getLongitude()) {
return false;
} else {
final double distance = distance(pastDistance.getLatitude(), pastDistance.getLongitude(), currentDistance.getLatitude(), currentDistance.getLongitude());
System.out.println("Distance in mile :" + distance);
handler.post(new Runnable() {
@Override
public void run() {
float kilometer = 1.609344f;
Log.v("Location5", "********* " + Thread.currentThread().getId());
totalDistance = totalDistance + distance * kilometer;
DISTANCE = totalDistance;
}
});
return true;
}
}
}
有关详细信息,请按照以下库中的代码进行操作。 https://github.com/raviteja06/TrackMyClient
这是在返回时完成的,请确保将库更新为最新版本。
答案 1 :(得分:0)
尝试使用以下代码:
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{
GoogleApiClient googleApiClient;
int REQUEST_CHECK_SETTINGS = 1;
Location mLastLocation;
LocationRequest locationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
checkForGPS();
}
public void checkForGPS(){
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
if(!((LocationManager)getSystemService(Context.LOCATION_SERVICE)).isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//prompt user to enable gps
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(3000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates states = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
MainActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
}
}
@Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
// put your code here to play with Location object
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
以下是您可能需要的一些有用的导入:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
不要忘记在Manifest中声明这些权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />