我成功创建了谷歌地图。我可以检查mylocation,我写了代码女巫可以在谷歌地图(触摸听众)中添加点,并在开始位置和点之间画线。现在我想检查距离。我不知道我怎么能这样 我用谷歌搜索了一个例子,但这段代码不能正常工作?我总是有一个距离 这是我的代码,如果有人知道解决方案,请帮助我 感谢
public class GPS extends Activity implements
OnMyLocationChangeListener, OnMapClickListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Circle myCircle;
TextView tvLocInfo, GPSLocation;
LatLng latLng;
boolean markerClicked;
ArrayList<LatLng> markerPoints;
double Startlatitude, Startlongitude, Endlatitude, Endlongitude;
public Button gpssize;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gps);
markerPoints = new ArrayList<LatLng>();
gpssize = (Button) findViewById(R.id.gpssize);
tvLocInfo = (TextView) findViewById(R.id.GpsTxt);
GPSLocation = (TextView) findViewById(R.id.GPSLocation);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment = (MapFragment) myFragmentManager
.findFragmentById(R.id.GpsMap);
myMap = myMapFragment.getMap();
myMap.getUiSettings().setZoomControlsEnabled(true);
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true);
myMap.setMyLocationEnabled(true);
myMap.setOnMyLocationChangeListener(this);
gpssize.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
double distance;
Location locationA = new Location("");
locationA.setLatitude(Startlatitude);
locationA.setLongitude(Startlongitude);
Location locationB = new Location("");
locationB.setLatitude(Endlatitude);
locationB.setLongitude(Endlongitude);
distance = locationA.distanceTo(locationB) / 1000;
Toast.makeText(getApplicationContext(), "" + distance,
Toast.LENGTH_LONG).show();
}
});
myMap.setOnMapClickListener(this);
myMap.setTrafficEnabled(true);
markerClicked = false;
}
@Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_LONG)
.show();
} else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}
@Override
public void onMyLocationChange(Location location) {
Startlatitude = location.getLatitude();
Startlongitude = location.getLongitude();
latLng = new LatLng(Startlatitude, Startlongitude);
myMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
GPSLocation.setText(Startlatitude + " " + Startlongitude);
// myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng locLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
double accuracy = location.getAccuracy();
if (myCircle == null) {
CircleOptions circleOptions = new CircleOptions().center(locLatLng)
.radius(accuracy)
.fillColor(Color.RED).strokeColor(Color.BLACK).strokeWidth(5);
myCircle = myMap.addCircle(circleOptions);
} else {
myCircle.setCenter(locLatLng);
myCircle.setRadius(accuracy);
}
myMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
String str_origin = "origin=" + Startlatitude + "," + Startlongitude;
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String sensor = "sensor=false";
String parameters = str_origin + "&" + str_dest + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
@Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
tvLocInfo.setText(lat + " " + lng);
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(7);
lineOptions.geodesic(true);
lineOptions.color(getResources().getColor(R.color.mapColor));
}
myMap.addPolyline(lineOptions);
}
}
@Override
public void onMapClick(LatLng point) {
if (markerPoints.size() > 0) {
markerPoints.clear();
myMap.clear();
}
markerPoints.add(point);
MarkerOptions options = new MarkerOptions();
options.position(point);
if (markerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}
myMap.addMarker(options);
if (markerPoints.size() >= 1) {
LatLng dest = markerPoints.get(0);
LatLng origin = new LatLng(Endlatitude, Endlongitude);
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
}
}
答案 0 :(得分:2)
尝试通过这种方式将Distance
提升到LatLng
点之间:
float[] distances = new float[1];
Location.distanceBetween(locationA.latitude, locationA.longitude,
locationB.latitude, locationB.longitude,
distances);
System.out.println("Distance: " + distances[0]);