2015-10-06 39 views
3

我正在使用大量谷歌地图交互的应用程序。在一个活动中,我展示了两点之间的路线。我希望这些路线可以选择,根据用户的选择秀请帮助我。 在这里,我attatching活动的图像:As you can see the paths如何在android中的谷歌地图中选择不同的路线?

,这里是上面所示的活动的代码:

public class RouteActivity extends FragmentActivity { 
private GoogleMap mMap; // Might be null if Google Play services APK is not available. 
double sl1,sl2,el1,el2; 
FrameLayout fl; 
TextView distTextView,timeTextView; 
String routeArray[]; 
List<LatLng> list; 
List<Polyline> polylineList; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_route); 
    setUpMapIfNeeded(); 
    mMap.getUiSettings().setZoomControlsEnabled(true); 
    polylineList=new ArrayList<Polyline>(); 
    fl=(FrameLayout)findViewById(R.id.frame_layout); 
    distTextView=(TextView)findViewById(R.id.distance_textView); 
    timeTextView=(TextView)findViewById(R.id.time_textView); 
    String start = getIntent().getStringExtra("start"); 
    String end = getIntent().getStringExtra("end"); 
    Geocoder coder = new Geocoder(this); 
    List<Address> address; 
    try { 
     address = coder.getFromLocationName(start, 5); 
     if (address == null) { 
     } 
     Address location = address.get(0); 
     sl1=location.getLatitude(); 
     sl2=location.getLongitude(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    try { 
     address = coder.getFromLocationName(end, 5); 
     if (address == null) { 
     } 
     Address location = address.get(0); 
     el1=location.getLatitude(); 
     el2=location.getLongitude(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.from); 
    markers[0]=mMap.addMarker(new MarkerOptions().position(new LatLng(sl1, sl2)).title(start).icon(icon)); 
    markers[1]=mMap.addMarker(new MarkerOptions().position(new LatLng(el1, el2)).title(end).icon(icon)); 
    LatLngBounds.Builder builder = new LatLngBounds.Builder(); 
    for (Marker marker : markers) { 
     builder.include(marker.getPosition()); 
    } 
    LatLngBounds bounds = builder.build(); 

    CameraUpdate cu=CameraUpdateFactory.newLatLngBounds(bounds,500,500,0); 
    mMap.moveCamera(cu); 
    mMap.animateCamera(cu); 
    String url=makeURL(sl1,sl2,el1,el2); 
    Log.e("Generated URL ",url); 
    new MyAsyncTask().execute(url); 
    fl.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      finish(); 
     } 
    }); 
    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { 
     @Override 
     public void onMapClick(LatLng latLng) { 
      int x=0; 
      for (Polyline polyline : polylineList) 
      { 
       for (LatLng polyCoords : polyline.getPoints()) { 
        float[] results = new float[1]; 
        Location.distanceBetween(latLng.latitude, latLng.longitude, 
          polyCoords.latitude, polyCoords.longitude, results); 


        if (results[0] < 100) { 
         mMap.clear(); 
         for(Polyline pl:polylineList) 
         { 
          if(pl!=polyline) { 
           mMap.addPolyline(new PolylineOptions().color(Color.GRAY).addAll(pl.getPoints())); 
           } 
          else if(pl==polyline) 
          { 
           mMap.addPolyline(new PolylineOptions() 
             .color(Color.BLUE) 
             .addAll(pl.getPoints())); 
          } 
         } 





        } 


       } 

      } 
      Log.e("PolyLine ",polylineList.toString()); 



     } 
    }); 


} 

    @Override 
protected void onResume() { 
    super.onResume(); 

} 

private void setUpMapIfNeeded() { 
    // Do a null check to confirm that we have not already instantiated the map. 
    if (mMap == null) { 
     // Try to obtain the map from the SupportMapFragment. 
     mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
       .getMap(); 
     // Check if we were successful in obtaining the map. 
     if (mMap != null) { 
      setUpMap(); 
     } 
    } 
} 

public class MyAsyncTask extends AsyncTask<String,Void,String> { 
    ProgressDialog progressDialog; 

    @Override 
    protected void onPreExecute() { 
     progressDialog=new ProgressDialog(RouteActivity.this); 
     progressDialog.setMessage("Finding Route ..."); 
     progressDialog.setCancelable(false); 
     progressDialog.setIndeterminate(false); 

     progressDialog.show(); 
    } 

    @Override 
    protected String doInBackground(String... str) { 
     ParserClass parser = new ParserClass(); 
     String json_str = parser.getJSON(str[0], 2000); 
     Log.e("JSON Data", json_str); 
     return json_str; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     try { 
      progressDialog.dismiss(); 
      JSONObject jsonRootObject = new JSONObject(s); 
      JSONArray routeArray=jsonRootObject.getJSONArray("routes"); 
      Log.e("ROUTES ",routeArray.toString()); 
      for(int i=routeArray.length()-1;i>=0;i--) { 
       JSONObject routes = routeArray.getJSONObject(i); 
       JSONObject overviewPolylines = routes.getJSONObject("overview_polyline"); 
       JSONArray legs=routes.getJSONArray("legs"); 
       for(int j=0;j<legs.length();j++) 
       { 
        JSONObject distObj=legs.getJSONObject(j); 
        JSONObject distance =distObj.getJSONObject("distance"); 
        String dist=distance.getString("text"); 
        JSONObject duration=distObj.getJSONObject("duration"); 
        String time=duration.getString("text"); 
        Log.e("Route"+i+" DISTANCE ",dist); 
        Log.e("Route"+i+" TIME ",time); 
        distTextView.setText("Distance "+dist); 
        timeTextView.setText("Time "+time); 
       } 
       String encodedString = overviewPolylines.getString("points"); 
       Log.e("Waypoint "+i,encodedString); 
       list = decodePoly(encodedString); 
       Log.e("List "+i,list.toString()); 
       if(i==0) { 
        Polyline line = mMap.addPolyline(new PolylineOptions() 
            .addAll(list) 
            .width(12) 
            .color(Color.BLUE) 
            .geodesic(true) 
          ); 
        Log.e("PolyLine ",line.toString()); 
        polylineList.add(line); 
       } 
       else{ 
        Polyline line = mMap.addPolyline(new PolylineOptions() 
            .addAll(list) 
            .width(12) 
            .color(Color.DKGRAY) 
            .geodesic(true) 
        ); 
        polylineList.add(line); 



        Log.e("PolyLine ",line.toString()); 

        } 

      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     super.onPostExecute(s); 
    } 
} 

private void setUpMap() { 
    mMap.clear(); 
} 
public void showMap(Double l1,Double l2,String str) 
{ 
    LatLng position=new LatLng(l1,l2); 
    SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map); 
    GoogleMap googleMap = fm.getMap(); 
    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.from); 
    mMap.addMarker(new MarkerOptions().position(new LatLng(l1, l2)).title(str).icon(icon)); 
    CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position); 
    CameraUpdate updateZoom=CameraUpdateFactory.zoomTo(15); 
    googleMap.moveCamera(updatePosition); 
    googleMap.animateCamera(updateZoom); 
} 
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog){ 
    StringBuilder urlString = new StringBuilder(); 
    urlString.append("https://maps.googleapis.com/maps/api/directions/json"); 
    urlString.append("?origin=");// from 
    urlString.append(Double.toString(sourcelat)); 
    urlString.append(","); 
    urlString.append(Double.toString(sourcelog)); 
    urlString.append("&destination=");// to 
    urlString.append(Double.toString(destlat)); 
    urlString.append(","); 
    urlString.append(Double.toString(destlog)); 
    urlString.append("&sensor=false&mode=driving&alternatives=true&units=imperial"); 
    urlString.append("&key=AIzaSyD5NOOpYKObjlZbt_-4CUOMi14mObzbGNo"); 
    return urlString.toString(); 
} 

private List<LatLng> decodePoly(String encoded) { 
    List<LatLng> poly = new ArrayList<LatLng>(); 
    int index = 0, len = encoded.length(); 
    int lat = 0, lng = 0; 
    while (index < len) { 
     int b, shift = 0, result = 0; 
     do { 
      b = encoded.charAt(index++) - 63; 
      result |= (b & 0x1f) << shift; 
      shift += 5; 
     } while (b >= 0x20); 
     int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); 
     lat += dlat; 
     shift = 0; 
     result = 0; 
     do { 
      b = encoded.charAt(index++) - 63; 
      result |= (b & 0x1f) << shift; 
      shift += 5; 
     } while (b >= 0x20); 
     int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); 
     lng += dlng; 
     LatLng p = new LatLng((((double) lat/1E5)), 
       (((double) lng/1E5))); 
     poly.add(p); 
    } 
    return poly; 
} 
} 

在abouce代码我创建使用谷歌方向API

这些路径

请帮助选择不同的路线。谢谢

+1

找到X/Y点击屏幕,然后使用数学http://stackoverflow.com/questions/20887806/does-a-line-contain-a-point/20888285#20888285 – tyczj

+0

谢谢作为回应,但有任何其他方式,以便我可以轻松地让他们选择..因为我们在iOS – Brucode

+1

“可点击”属性没有点击监听器或任何折线 – tyczj

回答

0

伙计们我已经实现了所需的功能,只是对现有代码进行了一些更改,现在它正在工作。感谢您的指导:)

+0

大家好,希望你们都做得很好。球员我再次在代码中存在问题.. 代码适用于较小的距离,如10 -20英里,但当两点之间的距离增加,难以检测到线..你们可以请帮助 – Brucode