我正在看其他帖子,但我无法做到。我想更新我的位置,并在我" x"我的targetLocation的米。
我使用过这段代码:
private TextView m1TextMessage, m2TextMessage, m3TextMessage;
private LocationManager locationManager;
private Location targetLocation;
double longitude, latitude;
private float distancia;
ProgressDialog pd;
LocationListener listener;
这是我的LocationListener:
public class MyLocationListener implements LocationListener {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
float dist=0;
float error=0;
//Escribir posición actual en m1TextMessage
latitude =location.getLatitude();
longitude = location.getLongitude();
//calcular distancia al destino y error estimado
//Escribir distancia al destino y error en m3TextMessage
Location loc2= new Location(LocationManager.GPS_PROVIDER);
if (loc2 != null)
{
dist=location.distanceTo(targetLocation);
error = location.getAccuracy();
if(dist < distancia){
Toast.makeText(getApplicationContext(), "Distancia menor a 10 metros, "+dist+" metros.",Toast.LENGTH_SHORT).show();
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
}
}else
Toast.makeText(getApplicationContext(), "location actual es null!!",Toast.LENGTH_SHORT).show();
m1TextMessage.setText("Posición actual: "+longitude+", "+latitude+"\n");
m2TextMessage.setText("Posición objetivo: "+targetLocation.getLatitude()+", "+targetLocation.getLongitude()+"\n");
m3TextMessage.setText("Distancia al objetivo: "+dist+"\nError estimado: "+error);
//Lanzar un Toast si la distancia al destino es inferior a 10 metros
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m1TextMessage=(TextView) findViewById(R.id.actualPos);
m2TextMessage=(TextView) findViewById(R.id.destino);
m3TextMessage=(TextView) findViewById(R.id.distanciaa);
Button localiza = (Button)findViewById(R.id.button1);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
localiza.setOnClickListener(this);
}
public class GPSLocation extends AsyncTask<Void, Void, Void>
{
boolean running =true;
@Override
protected void onPreExecute()
{
super.onPreExecute();
pd = new ProgressDialog(PracticaGPS.this);
pd.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
pd.cancel();
}
});
longitude=0;
latitude =0;
getLonLat();
pd.setCancelable(true);
pd.setMessage("Getting GPS Location...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.show();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
@Override
protected void onPostExecute(Void result)
{
pd.dismiss();
}
@Override
protected Void doInBackground(Void... params) {
boolean isDataSubmitted = false;
while(!isDataSubmitted)
{
if(longitude !=0 && latitude!=0)
{
isDataSubmitted = true;
Log.d("LONGITUD", ""+longitude);
Log.d("LATITUDE", ""+latitude);
}
}
return null;
}
}
public void getLonLat(){
listener = new MyLocationListener();
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
(locationManager).requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,listener);
new GPSLocation().execute();
}else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, listener);
Log.d("Long", ""+longitude);
} else
enableLocationSettings();
}
@Override
public void onStart(){
//Crear servicio de localización LocationManager
//Determinar si el GPS está encendido
//Caso esté apagado, permitir al usuario activarlo mediante método enableLocationSettings()
//Solicitar actualizaciones de posición al proveedor de GPS (opcionalmente también al proveedor de red)
//Nota: el LocationListener ya ha sido creado: listener
super.onStart();
}
private void enableLocationSettings() { //enable Location services is necessary
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
@Override
public void onStop(){
locationManager.removeUpdates(listener);
super.onStop();
}
public void onClick(View v) {
EditText lat, lon, distan;
lat = (EditText)findViewById(R.id.latitud);
lon = (EditText)findViewById(R.id.longitud);
targetLocation = new Location("Target Position");
targetLocation.setLatitude(Double.valueOf(lat.getText().toString())); //punto pre-definido,
targetLocation.setLongitude(Double.valueOf(lon.getText().toString())); //no cambiar el valor
targetLocation.setAltitude(0);
distan = (EditText)findViewById(R.id.distancia);
distancia = Float.valueOf(distan.getText().toString());
new GPSLocation().execute();
}
}
这是我的xml代码:
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitud: " />
<EditText
android:id="@+id/longitud"
android:layout_width="101dp"
android:layout_height="wrap_content"
android:ems="10" />
<TextView
android:id="@+id/texto2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitud: " />
<EditText
android:id="@+id/latitud"
android:layout_width="105dp"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Distancia mínima alarma" />
<EditText
android:id="@+id/distancia"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enviar Localizacion" />
<TextView
android:id="@+id/actualPos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
/>
<TextView
android:id="@+id/destino"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
/>
<TextView
android:id="@+id/distanciaa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
/>
我觉得很简单,但我可以管理它。谢谢。
答案 0 :(得分:0)
阅读本文。
http://developer.android.com/reference/android/location/Location.html
使用此功能
public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)
从函数中获取结果,并在循环中将目标位置减去它。
答案 1 :(得分:0)
如果您希望获得从当前位置到目标位置的距离,则可以正确调用此方法..这将根据Google服务提供距离.. simpley它会返回值...它会很好地工作。希望它会对你有所帮助。
package com.google.map;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Distance {
public String getDistance(String Source,String Destination) {
StringBuilder stringBuilder = new StringBuilder();
String duration_final_value = "";
try {
Source = Source.replaceAll(" ", "%20");
Destination = Destination.replaceAll(" ", "%20");
HttpPost httppost = new HttpPost(
"http://maps.google.com/maps/api/directions/json?origin="
+ Source + "&destination=" + Destination
+ "&sensor=false&units=metric&mode=driving");//&mode=walking,driving
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString()); // first we need to get the full json object which google returns
JSONArray routes_Array = jsonObject.getJSONArray("routes"); // in that first we need to go into the routes array
JSONObject routes_object = (JSONObject) routes_Array.get(0); // in that we need first item
JSONArray legs_Array = routes_object.getJSONArray("legs"); // then go into the legs array
JSONObject legs_object = (JSONObject) legs_Array.get(0); // in that we need first item.
JSONObject duration_object = legs_object.getJSONObject("distance"); // go into the distance object
// pull out the "duration" object
duration_final_value = duration_object.getString("text"); // this should be the duration text value (20 hours 40 mins)
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return duration_final_value;
}
}