2016-09-14 113 views
0

因此,我已經四處尋找了在Google地圖上繪製路線的示例。然而,我的障礙是我必須去url/route.coords才能獲得路線的經緯度。當我手動轉到該網址時,它會下載包含所有路線信息的文本文件。所以,如果任何人都可以幫助我從哪裏開始,將不勝感激。我已經爲地圖顯示了當前位置的一個點,以及其他一些列出的類。我的最終目標是爲每個驅動器繪製一條不同的彩色路線,每個驅動器都有其特定的URL。通過URL在谷歌地圖片段上繪製路線

對我顯示我的谷歌地圖,其中片段:

public class ThirdFragment extends Fragment implements OnMapReadyCallback { 
    View myView; 
    private GoogleMap mMap; 
    MapFragment mapFrag; 

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     myView = inflater.inflate(R.layout.third_layout, container, false); 
     return myView; 

    } 

    @Override 
    public void onViewCreated(View view, Bundle savedInstanceState) { 
     super.onViewCreated(view, savedInstanceState); 

     mapFrag = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map); 
     mapFrag.getMapAsync(this); 
     //mapFrag.onResume(); 

    } 


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


     if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
      mMap.setMyLocationEnabled(true); 
      Criteria criteria = new Criteria(); 
      LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE); 
      String provider = locationManager.getBestProvider(criteria, false); 
      Location location = locationManager.getLastKnownLocation(provider); 
      double lat = location.getLatitude(); 
      double lng = location.getLongitude(); 
      LatLng coordinate = new LatLng(lat, lng); 
      CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 13); 
      mMap.animateCamera(yourLocation); 

     } else { 
      final AlertDialog alertDialogGPS = new AlertDialog.Builder(getActivity()).create(); 

      alertDialogGPS.setTitle("Info"); 
      alertDialogGPS.setMessage("Looks like you have not given GPS permissions. Please give GPS permissions and return back to the app."); 
      alertDialogGPS.setIcon(android.R.drawable.ic_dialog_alert); 
      alertDialogGPS.setButton("OK", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 

        Intent intentSettings = new Intent(Settings.ACTION_APPLICATION_SETTINGS); 
        startActivity(intentSettings); 
        alertDialogGPS.dismiss(); 
       } 

      }); 

      alertDialogGPS.show(); 
     } 

    } 
    @Override 
    public void onResume() { 
     super.onResume(); 
     if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 

      mapFrag.getMapAsync(this); 
     } 
     else { 
     } 
    } 
} 

RouteCoord.java

public class RouteCoord { 
    private String lat, dist, lng, speed, index; 
    public String getLat() { 
     return lat; 
    } 

    public void setLat(String lat) {this.lat = lat;} 

    public String getLng(){return lng;} 

    public void setLng(String lng) {this.lng = lng;} 
} 

RouteAdapter.java

public class RouteAdapter extends ArrayAdapter<Map.Entry> { 

    private final Activity context; 
    // you may need to change List to something else (whatever is returned from drives.entrySet()) 
    private final List<Map.Entry> drives; 
    public static String DriveURL; 
    public static String routeLat; 
    public static String routeLng; 


    SharedPreferences sharedPref; 
    // may also need to change List here (above comment) 
    public RouteAdapter(Activity context, List<Map.Entry> drives) { 
     super(context, R.layout.drive_url_list, drives); 
     this.context = context; 
     this.drives = drives; 
     sharedPref = context.getPreferences(Context.MODE_PRIVATE); 
    } 


    @Override 
    public View getView(int position, View view, ViewGroup parent) { 
     LayoutInflater inflater = context.getLayoutInflater(); 
     View rowView = inflater.inflate(R.layout.third_layout, null, true); 

     Map.Entry drive = this.drives.get(position); 

     // position is the index of the drives.entrySet() array 
     int driveNum = position + 1; 

     // need to import your Route class 
     Route route = (Route) drive.getValue(); 
     RouteCoord routeCoord = (RouteCoord) drive.getValue(); 
     routeLat = routeCoord.getLat(); 
     routeLng = routeCoord.getLng(); 

     // need to import your URL class 
     DriveURL = route.getUrl(); 

     return rowView; 
    } 
} 

回答

1

你需要在谷歌繪製Polyline使用路線的座標映射。

請參見下面的示例代碼:

/** 
* To show map with this activity add ORIGIN, DESTINATION lat double arrays in 
* intent. 
* 
* </br> For specifying origin, put latitude and longitude in an array of double 
* with key = {@link #ORIGIN} in the intent </br >For specifying destination, 
* put latitude and longitude in an array of double with key = 
* {@link #DESTINATION} in the intent 
* 
* @author Shridutt.Kothari 
* 
*/ 
public class MapsActivity extends BaseActivity { 

    private static final String TAG = "MapsActivity"; 

    /** 
    * String key for specifying array of long containing origin latitude and 
    * longitude . 
    */ 
    public static final String ORIGIN = "ORIGIN"; 
    private double[] destinationLocation; 
    private GoogleMap map; 
    private PathUpdateReceiver pathUpdateReceiver; 
    private PolylineOptions lineOptions; 
    private Marker marker; 
    private MarkerOptions ambulanceMarkerOption; 
    private Polyline polyline; 
    private List<LatLng> points; 
    private static final int ZOOM_LEVEL = 15; 
    private static final int POLYLINE_WIDTH = 5; 
    private static final String AMBULANCE_MARKER_NAME = "Ambulance"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_map); 
     // Intent launchIntent = getIntent(); 
     // originLocation = new double[2]; 
     // originLocation = launchIntent.getDoubleArrayExtra(ORIGIN); 
     // originLocation[0] = 28.628525; 
     // originLocation[1] = 77.22219016666666; 
     destinationLocation = new double[2]; 

     map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)) 
       .getMap(); 
     if (null == map) { 
      try { 
       MapsInitializer.initialize(getApplicationContext()); 
      } catch (Exception e) { 
       Toast.makeText(getApplicationContext(), 
         "Google play services not available, can't show map!", 
         Toast.LENGTH_LONG).show(); 
       e.printStackTrace(); 
       this.finish(); 
      } 
     } 

    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     if (null == pathUpdateReceiver) { 
      pathUpdateReceiver = new PathUpdateReceiver(); 
     } 
     IntentFilter intentFilter = new IntentFilter(); 
     intentFilter.addAction(AppConstants.VEHICLE_DATA_SAMPLE_ID); 
     registerReceiver(pathUpdateReceiver, intentFilter); 
    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     unregisterReceiver(pathUpdateReceiver); 
    } 

    /** 
    * PathUpdate 
    * 
    * 
    */ 
    private class PathUpdateReceiver extends BroadcastReceiver {   

     @Override 
     public void onReceive(Context context, Intent intent) { 
      if (map != null 
        && intent.getAction().equalsIgnoreCase(
          AppConstants.VEHICLE_DATA_SAMPLE_ID)) { 
       map.getUiSettings().setZoomControlsEnabled(true); 
       map.getUiSettings().setTiltGesturesEnabled(true); 
       map.getUiSettings().setAllGesturesEnabled(true); 

       VehicleDataSample vehicleDataSample = ((GoldenHourTrackerApp) getApplication()).getVehicleDataSample(); 
       destinationLocation[0] = vehicleDataSample.getLatitude(); 
       destinationLocation[1] = vehicleDataSample.getLongitude(); 

       Log.e(TAG, "received location update:"+destinationLocation[0]+", "+destinationLocation[1]); 
       LatLng newPoint = new LatLng(destinationLocation[0], 
         destinationLocation[1]); 
       if (null != destinationLocation) { 
        map.setTrafficEnabled(false); 
        map.setBuildingsEnabled(true); 
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
        LatLng originlatlng = new LatLng(destinationLocation[0], 
          destinationLocation[1]); 
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(
          originlatlng, ZOOM_LEVEL)); 
        [email protected]("unused") 
        MarkerOptions traumaLoacationMarkerOption = new MarkerOptions() 
          .position(originlatlng) 
          .title(TRAUMA_LOCATION_MARKER_NAME) 
          .icon(BitmapDescriptorFactory 
            .defaultMarker(BitmapDescriptorFactory.HUE_RED)); 
        if (ambulanceMarkerOption == null) { 
         ambulanceMarkerOption = new MarkerOptions() 
           .position(originlatlng) 
           .title(AMBULANCE_MARKER_NAME) 
           .icon(BitmapDescriptorFactory 
             .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); 
         // TODO: Currently Not adding 
         // TRAUMA_LOCATION_MARKER_NAME on Map 
         // map.addMarker(traumaLoacationMarkerOption); 
         marker = map.addMarker(ambulanceMarkerOption); 
         marker.showInfoWindow(); 
        } 

        if (null == lineOptions) { 
         lineOptions = new PolylineOptions(); 
         lineOptions.add(newPoint); 
         // A 5 width Polyline 
         lineOptions.width(POLYLINE_WIDTH); 
         lineOptions.color(context.getResources().getColor(
           R.color.blue)); 
         polyline = map.addPolyline(lineOptions); 
        } 

        marker.setPosition(newPoint); 
        marker.setVisible(true); 
        marker.showInfoWindow(); 
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(
          newPoint, ZOOM_LEVEL)); 
        points = polyline.getPoints(); 
        points.add(newPoint); 
        polyline.setPoints(points); 
       } 
      } 
     } 
    } 
} 
+0

所以我基本上取代了我在我的片段與該放的代碼?我看到它有'List ',我將從'RouteAdapter.java'獲得'或者如果我需要使不同的類正確嗎? –

+0

是的,你是對的 –