2014-02-28 154 views
0
之间的距离

我成功创建了谷歌地图.i可以检查地理位置,我写的代码女巫可以在谷歌地图(触摸侦听器)中添加点并在起始位置和点之间画线。现在我想检查距离。我不知道我怎么可以这样 我GOOGLE了一个例子,但是这个代码不工作的权利?我总是有一个距离 这是我的代码,如果有人知道的解决方案,请帮助我 感谢Android谷歌地图查找

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

location.distanceBetween(双startLatitude,双startLongitude,双endLatitude,双层电子ndLongitude,float []结果); –

回答

2

试试这个方式来获得之间DistanceLatLng点:

float[] distances = new float[1]; 
Location.distanceBetween(locationA.latitude, locationA.longitude, 
       locationB.latitude, locationB.longitude, 
       distances); 

System.out.println("Distance: " + distances[0]); 
+0

谢谢你完成工作 – user3345767