2017-03-02 11 views
-1

メインルートと代替ルートが接続されていることに気付いたので、onclickを設定すると、メインルートの色を青に変更したい場合、代替ルートも青に変わります。どのように別のルートとメインルートの色を変更できるようにそれらを分離するのですか?メインルートと代替ルートのポリラインGoogleマップアンドロイドを分ける方法は?

これは私のFragment.java

public class ThirdFragment extends Fragment implements OnMapReadyCallback, 
     GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, 
     LocationListener,DirectionFinderListener,AdapterView.OnItemClickListener { 

    /**************************************************************/ 
    // private GoogleMap mMap; 

    private ImageButton btnFindPath; 
    private AutoCompleteTextView etOrigin; 
    private AutoCompleteTextView etDestination; 
    private List<Marker> originMarkers = new ArrayList<>(); 
    private List<Marker> destinationMarkers = new ArrayList<>(); 
    private List<Polyline> polylinePaths = new ArrayList<>(); 
    private ProgressDialog progressDialog; 
    private static final String LOG_TAG = "Google Places Autocomplete"; 
    private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place"; 
    private static final String TYPE_AUTOCOMPLETE = "/autocomplete"; 
    private static final String OUT_JSON = "/json"; 

    private static final String API_KEY = "AIzaSyAYyvjDnsqEFVhnDflaruaTAChEzkPxpsA"; 

    /**************************************************************/ 
//FOR COLLAPSING TOOLBAR 
    private CollapsingToolbarLayout collapsingToolbarLayout = null; 

/***************************************************************/ 

    //**********For changing colors in the directions************************************************************/ 


    /**************************************************************************************************************/ 
    double latitude; 
    double longitude; 

    GoogleMap mMap; 

    MapView mapView; 
    View Myview; 

    GoogleApiClient mGoogleApiClient; 
    Location mLastLocation; 
    Marker mCurrLocationMarker; 
    LocationRequest mLocationRequest; 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
     Myview = inflater.inflate(R.layout.activity_third_fragment, container, false); 

     mapView = (MapView) Myview.findViewById(R.id.mapview); 
     mapView.onCreate(savedInstanceState); 
     mapView.getMapAsync(this); 
/********************************************************************/ 
     collapsingToolbarLayout = (CollapsingToolbarLayout) Myview.findViewById(R.id.collapsing_toolbar); 

     /****************************************************************************************/ 

     btnFindPath = (ImageButton) Myview.findViewById(R.id.btnFindPath); 
     etOrigin = (AutoCompleteTextView) Myview.findViewById(R.id.etOrigin); 
     etDestination = (AutoCompleteTextView) Myview.findViewById(R.id.etDestination); 
     btnFindPath.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       sendRequest(); 
      } 
     }); 

     etOrigin.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item)); 
     etOrigin.setOnItemClickListener(this); 
     etDestination.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item)); 
     etDestination.setOnItemClickListener(this); 

     return Myview; 
    } 

    //**********For changing colors in the directions************************************************************/ 


    /**************************************************************************************************************/ 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 

     goToLocationZoom(9.3068, 123.3054, 15); 
     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

     //Initialize Google Play Services 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (ContextCompat.checkSelfPermission(getActivity(), 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       buildGoogleApiClient(); 
       mMap.setMyLocationEnabled(true); 
      } 
     } else { 
      buildGoogleApiClient(); 
      mMap.setMyLocationEnabled(true); 
     } 

     LatLngBounds Dumaguete = new LatLngBounds(new LatLng(9.267, 123.264), new LatLng(9.33, 123.311)); 
     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
     mMap.setMinZoomPreference(15.0f); 
     mMap.setMaxZoomPreference(20.0f); 
     mMap.setLatLngBoundsForCameraTarget(Dumaguete); 
     mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Dumaguete.getCenter(), 15)); 
     if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      return; 
     } 
     mMap.setMyLocationEnabled(true); 

    } 

    private void goToLocationZoom(double lat, double lng, int zoom) { 
     LatLng ll = new LatLng(lat, lng); 
     CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom); 
     mMap.moveCamera(update); 

    } 

    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     mGoogleApiClient.connect(); 

    } 

    @Override 
    public void onConnected(@Nullable Bundle bundle) { 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(1000); 
     mLocationRequest.setFastestInterval(1000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
     if (ContextCompat.checkSelfPermission(getActivity(), 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

    } 

    @Override 
    public void onLocationChanged(Location location) { 
     Log.d("onLocationChanged", "entered"); 

     mLastLocation = location; 
     if (mCurrLocationMarker != null) { 
      mCurrLocationMarker.remove(); 
     } 

     //Place current location marker 
     latitude = location.getLatitude(); 
     longitude = location.getLongitude(); 
     LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 


     //move map camera 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     //mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); 
     Toast.makeText(getActivity(), "Your Current Location", Toast.LENGTH_LONG).show(); 

     Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f", latitude, longitude)); 

     //stop location updates 
     if (mGoogleApiClient != null) { 
      LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
      Log.d("onLocationChanged", "Removing Location Updates"); 
     } 
     Log.d("onLocationChanged", "Exit"); 

    } 

    private void sendRequest() { 
     String origin = etOrigin.getText().toString(); 
     String destination = etDestination.getText().toString(); 
     if (origin.isEmpty()) { 
      Toast.makeText(getActivity(), "Please enter origin address!", Toast.LENGTH_SHORT).show(); 
      return; 
     } 
     if (destination.isEmpty()) { 
      Toast.makeText(getActivity(), "Please enter destination address!", Toast.LENGTH_SHORT).show(); 
      return; 
     } 

     try { 
      new DirectionFinder(this, origin, destination).execute(); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void onDirectionFinderStart() { 
     progressDialog = ProgressDialog.show(getActivity(), "Please wait.", 
       "Finding direction..!", true); 

     if (originMarkers != null) { 
      for (Marker marker : originMarkers) { 
       marker.remove(); 
      } 
     } 

     if (destinationMarkers != null) { 
      for (Marker marker : destinationMarkers) { 
       marker.remove(); 
      } 
     } 

     if (polylinePaths != null) { 
      for (Polyline polyline : polylinePaths) { 
       polyline.remove(); 
      } 
     } 
    } 


    @Override 
    public void onDirectionFinderSuccess(List<Route> routes) { 
     progressDialog.dismiss(); 

     List<Route> gRoute = new ArrayList<Route>(); 
     Route rr = new Route(); 
     gRoute.add(rr); 

     List<Route> nRoute; 
     nRoute = routes; 

     polylinePaths = new ArrayList<>(); 
     originMarkers = new ArrayList<>(); 
     destinationMarkers = new ArrayList<>(); 

     for (int i = 0; i < gRoute.size(); i++) 
     { 
      Toast.makeText(getActivity(), "" +gRoute.size()+ "Shortest Route Found...", Toast.LENGTH_SHORT).show(); 
      Toast.makeText(getActivity(), "" +nRoute.size()+ "Route Found...", Toast.LENGTH_SHORT).show(); 
     } 

     for (final Route distance : routes) 
     { 
      Toast.makeText(getActivity(), "Distance: " + distance.distance.text, Toast.LENGTH_SHORT).show(); 
     } 


     Toast.makeText(getActivity(), "Directions found!", Toast.LENGTH_SHORT).show(); 
     for (Route route : routes) { 


      mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16)); 
      // ((TextView) Myview.findViewById(R.id.tvDuration)).setText(route.duration.text); 
      ((TextView) Myview.findViewById(R.id.tvDistance)).setText(route.distance.text); 

      originMarkers.add(mMap.addMarker(new MarkerOptions() 
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue)) 
        .title(route.startAddress) 
        .position(route.startLocation))); 
      destinationMarkers.add(mMap.addMarker(new MarkerOptions() 
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green)) 
        .title(route.endAddress) 
        .position(route.endLocation))); 


      /******************For Changing color ********************************************************/ 
      mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() { 
       @Override 
       public void onPolylineClick(Polyline polyline) { 
        // Flip the values of the red, green and blue components of the polyline's color. 
        polyline.setColor(polyline.getColor()^0x00ffffff); 

       } 
      }); 

      /*************************************************************************************************/ 

      Random rnd = new Random(); 

      //int color = Coor.argb(255, 112, 112, 112); 
      //int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(257), rnd.nextInt(258)); 

      int color = Color.parseColor("blue"); 
      // #999999 grey 

     /**/ 
      PolylineOptions polylineOptions = new PolylineOptions(). 
        geodesic(true).color(color).width(15).clickable(true); 


      for (int i = 0; i < route.points.size(); i++) 
       polylineOptions.add(route.points.get(i)); 


      polylinePaths.add(mMap.addPolyline(polylineOptions)); 

     } 


    } 

マイdirectionfinder.java

public class DirectionFinder { 
    private static final String DIRECTION_URL_API = "https://maps.googleapis.com/maps/api/directions/json?"; 
    private static final String GOOGLE_API_KEY = "AIzaSyC1E8NU2jjoQF7dN37bIOz_1fy0fe98YhI"; 
    private DirectionFinderListener listener; 
    private String origin; 
    private String destination; 




    public DirectionFinder(DirectionFinderListener listener, String origin, String destination) { 
     this.listener = listener; 
     this.origin = origin; 
     this.destination = destination; 
    } 

    public void execute() throws UnsupportedEncodingException { 
     listener.onDirectionFinderStart(); 
     new DownloadRawData().execute(createUrl()); 
    } 

    private String createUrl() throws UnsupportedEncodingException { 
     String urlOrigin = URLEncoder.encode(origin, "utf-8"); 
     String urlDestination = URLEncoder.encode(destination, "utf-8"); 

     return DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination +"&alternatives=true" +"&key=" + GOOGLE_API_KEY; 
    } 

    private class DownloadRawData extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... params) { 
      String link = params[0]; 
      try { 
       URL url = new URL(link); 
       InputStream is = url.openConnection().getInputStream(); 
       StringBuffer buffer = new StringBuffer(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 

       String line; 
       while ((line = reader.readLine()) != null) { 
        buffer.append(line + "\n"); 
       } 

       return buffer.toString(); 

      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(String res) { 
      try { 
       parseJSon(res); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    private void parseJSon(String data) throws JSONException { 
     if (data == null) 
      return; 

     List<Route> routes = new ArrayList<Route>(); 
     JSONObject jsonData = new JSONObject(data); 
     JSONArray jsonRoutes = jsonData.getJSONArray("routes"); 
     for (int i = 0; i < jsonRoutes.length(); i++) { 
      JSONObject jsonRoute = jsonRoutes.getJSONObject(i); 
      Route route = new Route(); 

      JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline"); 
      JSONArray jsonLegs = jsonRoute.getJSONArray("legs"); 
      JSONObject jsonLeg = jsonLegs.getJSONObject(0); 
      JSONObject jsonDistance = jsonLeg.getJSONObject("distance"); 
      JSONObject jsonDuration = jsonLeg.getJSONObject("duration"); 
      JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location"); 
      JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location"); 

      route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value")); 
      route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value")); 
      route.endAddress = jsonLeg.getString("end_address"); 
      route.startAddress = jsonLeg.getString("start_address"); 
      route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng")); 
      route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng")); 
      route.points = decodePolyLine(overview_polylineJson.getString("points")); 

      routes.add(route); 
     } 

     listener.onDirectionFinderSuccess(routes); 
    } 

    private List<LatLng> decodePolyLine(final String poly) { 
     int len = poly.length(); 
     int index = 0; 
     List<LatLng> decoded = new ArrayList<LatLng>(); 
     int lat = 0; 
     int lng = 0; 

     while (index < len) { 
      int b; 
      int shift = 0; 
      int result = 0; 
      do { 
       b = poly.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 = poly.charAt(index++) - 63; 
       result |= (b & 0x1f) << shift; 
       shift += 5; 
      } while (b >= 0x20); 
      int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); 
      lng += dlng; 

      decoded.add(new LatLng(
        lat/100000d, lng/100000d 
      )); 
     } 

     return decoded; 
    } 
} 

Route.java

public class Route { 

    public Distance distance; 
    public Duration duration; 
    public String endAddress; 
    public LatLng endLocation; 
    public String startAddress; 
    public LatLng startLocation; 

    public List<LatLng> points; 
} 

Duration.java

public class Duration { 

    public String text; 
    public int value; 

    public Duration(String text, int value) { 
     this.text = text; 
     this.value = value; 
    } 
} 
です

for (Route route : routes) { 

あなたがここに色を設定します:

int color = Color.parseColor("blue"); 

このint型doesnのforループで

Distance.java

public class Distance { 

    public String text; 
    public int value; 

    public Distance(String text, int value) { 
     this.text = text; 
     this.value = value; 
    } 
} 

DirectionFinderListener.java

public interface DirectionFinderListener { 
    void onDirectionFinderStart(); 
    void onDirectionFinderSuccess(List<Route> route); 
} 
+0

現在作業しているコードを投稿できますか?現在作業していることの最小限で完全で検証可能な例を提供できる場合は、より簡単に手助けすることができます。 –

+0

@Stephen大丈夫です。私は自分のコードを更新します。 –

+0

@Stephen Sir質問を更新してコードを掲載しました。あなたが答えた私の他の投稿に関連しています。 –

答えて

0

't chあなたのアプリケーションが各ルートのポリラインを描画しているときの値です。ポリラインごとに異なる色を使用する場合は、この変数の値が変更されるように変更する必要があります。たとえば、forループで最初にカウンタを0に設定すると、ポリラインが描画されるたびにインクリメントされます。カウントが何であるかに応じて色を設定する条件を追加することができます。私はこれが役に立てば幸い

@Override 
public void onDirectionFinderSuccess(List<Route> routes) { 
    progressDialog.dismiss(); 

    int count = 0; //counter for your for each loop 
    int color = Color.parseColor("blue"); //moving this here to the beginning of your function 

    List<Route> gRoute = new ArrayList<Route>(); 
    Route rr = new Route(); 
    gRoute.add(rr); 

    List<Route> nRoute; 
    nRoute = routes; 

    polylinePaths = new ArrayList<>(); 
    originMarkers = new ArrayList<>(); 
    destinationMarkers = new ArrayList<>(); 

    for (int i = 0; i < gRoute.size(); i++) 
    { 
     Toast.makeText(getActivity(), "" +gRoute.size()+ "Shortest Route Found...", Toast.LENGTH_SHORT).show(); 
     Toast.makeText(getActivity(), "" +nRoute.size()+ "Route Found...", Toast.LENGTH_SHORT).show(); 
    } 

    for (final Route distance : routes) 
    { 
     Toast.makeText(getActivity(), "Distance: " + distance.distance.text, Toast.LENGTH_SHORT).show(); 
    } 


    Toast.makeText(getActivity(), "Directions found!", Toast.LENGTH_SHORT).show(); 
    for (Route route : routes) { 


     mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16)); 
     // ((TextView) Myview.findViewById(R.id.tvDuration)).setText(route.duration.text); 
     ((TextView) Myview.findViewById(R.id.tvDistance)).setText(route.distance.text); 

     originMarkers.add(mMap.addMarker(new MarkerOptions() 
       .icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue)) 
       .title(route.startAddress) 
       .position(route.startLocation))); 
     destinationMarkers.add(mMap.addMarker(new MarkerOptions() 
       .icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green)) 
       .title(route.endAddress) 
       .position(route.endLocation))); 


     /******************For Changing color ********************************************************/ 
     mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() { 
      @Override 
      public void onPolylineClick(Polyline polyline) { 
       // Flip the values of the red, green and blue components of the polyline's color. 
       polyline.setColor(polyline.getColor()^0x00ffffff); 

      } 
     }); 

     /*************************************************************************************************/ 

     Random rnd = new Random(); 

     //int color = Coor.argb(255, 112, 112, 112); 
     //int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(257), rnd.nextInt(258)); 

     if(count == 0) 
      color = Color.parseColor("blue"); 
     else if(count == 1) 
      color = Color.parseColor("red"); 
     else 
      color = Color.parseColor("green"); 

     //I only did this for 3 routes, but you can continue to follow this logic to color each route differently.  

     // #999999 grey 

    /**/ 
     PolylineOptions polylineOptions = new PolylineOptions(). 
       geodesic(true).color(color).width(15).clickable(true); 


     for (int i = 0; i < route.points.size(); i++) 
      polylineOptions.add(route.points.get(i)); 


     polylinePaths.add(mMap.addPolyline(polylineOptions)); 
     count++; 

    } 


} 

:私はあなたのonDirectionsFinderSuccess機能を書き換えますよ!

関連する問題