2014-02-28 183 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