Android-谷歌地图路由

Android-谷歌地图路由,android,google-maps,routing,Android,Google Maps,Routing,我已经在我的应用程序中添加了谷歌地图功能,现在我问你,有没有办法,我如何添加这个地图视图路由功能。我将有我的GPS坐标(如开始)和我的目的地坐标。我想画一条到达终点的路线。可能吗 谢谢Hmyzak看到了Max Gontar给出的最有希望的解决方案……它对我很有效 完整源代码:这就是我要做的 在监听位置变化时,首先将坐标记录到数据库中 public void startRouteTracking(){ // Acquire a reference to the system Lo

我已经在我的应用程序中添加了谷歌地图功能,现在我问你,有没有办法,我如何添加这个地图视图路由功能。我将有我的GPS坐标(如开始)和我的目的地坐标。我想画一条到达终点的路线。可能吗


谢谢

Hmyzak看到了Max Gontar给出的最有希望的解决方案……它对我很有效

完整源代码:

这就是我要做的 在监听位置变化时,首先将坐标记录到数据库中

     public void startRouteTracking(){
    // Acquire a reference to the system Location Manager
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // Define a listener that responds to location updates
    locationListener = new LocationListener() {
        LocationOpenHelper myLocationDb = new LocationOpenHelper(Main.this);
        SQLiteDatabase locationDb = myLocationDb.getWritableDatabase();


    public void onStatusChanged(String provider, int status, Bundle extras) {}

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}

        @Override
        public void onLocationChanged(Location location) {

            //if last location is known and the current location is newer than last location
            //if ((lastLocation != null) && (location.getTime() > lastLocation.getTime())){
            if ((lastLocation != null)){
                ContentValues values = new ContentValues();
                values.put(COLUMN_LATITUDE, location.getLatitude());
                values.put(COLUMN_LONGITUDE, location.getLongitude());
                values.put(COLUMN_TIME, location.getTime());
                values.put(COLUMN_SPEED, location.getSpeed());
                values.put(COLUMN_DISTANCE_TO_LAST_LOC, location.distanceTo(lastLocation));                 

                locationDb.insert(LOCATION_TABLE_NAME, null, values);

                statusTextView.setText("provider " + location.getProvider() + location.getLatitude() + " " + location.getLongitude() + "speed:" + location.getSpeed() + "distance: " + location.distanceTo(lastLocation));

            } 

            lastLocation = location;

            }
      };

    // Register the listener with the Location Manager to receive location updates
    // Update every 5 seconds or 5 meters, whichever comes first
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

}
其次,从数据库中检索坐标,并将数据传递到map fragment对话框

public int showMapFragment(int year, int month, int day){       
        GoogleMap mMap;
        SupportMapFragment mMapFragment;            

        //myMapFragment = SupportMapFragment.newInstance(mapOptions);
        ArrayList<LatLng> latLongArray = new ArrayList<LatLng> ();
        ArrayList<Long> timeArray = new ArrayList<Long> ();
        ArrayList<Integer> distanceToLastArray = new ArrayList<Integer> ();
        ArrayList<Integer> speedArray = new ArrayList<Integer> ();          

        LocationOpenHelper myLocationDb = new LocationOpenHelper(this);
        myLocationDb.printsomething();
        SQLiteDatabase locationDb = myLocationDb.getReadableDatabase();         

        Calendar startDate = new GregorianCalendar();
        // reset hour, minutes, seconds and millis
        startDate.set(Calendar.HOUR_OF_DAY, 0);
        startDate.set(Calendar.MINUTE, 0);
        startDate.set(Calendar.SECOND, 0);
        startDate.set(Calendar.MILLISECOND, 0);
        //startDate.add(Calendar.DAY_OF_MONTH, -4);
        startDate.set(Calendar.YEAR, year);
        startDate.set(Calendar.MONTH, month);
        startDate.set(Calendar.DAY_OF_MONTH, day);

        Calendar endDate = new GregorianCalendar();
        // reset hour, minutes, seconds and millis
        endDate.set(Calendar.HOUR_OF_DAY, 0);
        endDate.set(Calendar.MINUTE, 0);
        endDate.set(Calendar.SECOND, 0);
        endDate.set(Calendar.MILLISECOND, 0);

        endDate.set(Calendar.YEAR, year);
        endDate.set(Calendar.MONTH, month);
        endDate.set(Calendar.DAY_OF_MONTH, day);            
        endDate.add(Calendar.DAY_OF_MONTH, 1);

        String orderBy = COLUMN_TIME + " ASC";

        Cursor cur = locationDb.query(LOCATION_TABLE_NAME, new String[] {COLUMN_ID, COLUMN_LATITUDE, COLUMN_LONGITUDE, COLUMN_TIME, COLUMN_SPEED, COLUMN_DISTANCE_TO_LAST_LOC}, 
                COLUMN_TIME + " >= " + startDate.getTimeInMillis() + " AND " + COLUMN_TIME + " < " + endDate.getTimeInMillis(), null, null, null, orderBy);

        int counter = 0;
        cur.moveToFirst();
        int nodeAdded = 1;
        double latSum = 0;
        double lngSum = 0;

        double[] lastThreeLats = {0, 0, 0} ;
        double[] lastThreeLngs = {0, 0, 0} ;
        int ind = 0;    

        int points = 0;

        double preLat = 0;
        double preLng = 0;
        double prePreLat = 0;
        double prePreLng = 0;
        double prePrePreLat = 0;
        double prePrePreLng = 0;

        if (cur.getCount() == 1){
            prePrePreLat = cur.getDouble(1);
            prePrePreLng = cur.getDouble(2);

            prePreLat = cur.getDouble(1);
            prePreLng = cur.getDouble(2);

            preLat = cur.getDouble(1);
            preLng = cur.getDouble(2);

        } else if (cur.getCount() == 2){
            prePrePreLat = cur.getDouble(1);
            prePrePreLng = cur.getDouble(2);

            cur.moveToNext();
            prePreLat = cur.getDouble(1);
            prePreLng = cur.getDouble(2);

            preLat = cur.getDouble(1);
            preLng = cur.getDouble(2);

        } if (cur.getCount() == 3){
            prePrePreLat = cur.getDouble(1);
            prePrePreLng = cur.getDouble(2);
            cur.moveToNext();
            prePreLat = cur.getDouble(1);
            prePreLng = cur.getDouble(2);
            cur.moveToNext();
            preLat = cur.getDouble(1);
            preLng = cur.getDouble(2);

        } else if (cur.getCount() > 3){
            prePrePreLat = cur.getDouble(1);
            prePrePreLng = cur.getDouble(2);
            cur.moveToNext();
            prePreLat = cur.getDouble(1);
            prePreLng = cur.getDouble(2);
            cur.moveToNext();
            preLat = cur.getDouble(1);
            preLng = cur.getDouble(2);
            cur.moveToNext();
        }

        while (cur.isAfterLast() == false) 
        {   
            double currentLat = cur.getDouble(1);
            double currentLng = cur.getDouble(2);

            latLongArray.add(new LatLng((prePrePreLat + prePreLat + preLat + currentLat)/ 4, (prePrePreLng + prePreLng + preLng + currentLng)/4));

            timeArray.add(cur.getLong(3));
            distanceToLastArray.add(cur.getInt(5));
            speedArray.add(cur.getInt(4));

            prePrePreLat = prePreLat;
            prePrePreLng = prePreLng;
            prePreLat = preLat;
            prePreLng = preLng;
            preLat = cur.getDouble(1);
            preLng = cur.getDouble(2);
            cur.moveToNext();
            nodeAdded++;                
        }   

        cur.close();            

        int rows = cur.getCount();

        //shows the map only when there's records available
        if (rows > 0){          
            DialogFragment mapFragment =  MapDialogFragment.newInstance(latLongArray, timeArray, distanceToLastArray, speedArray);
            mapFragment.setStyle(DialogFragment.STYLE_NORMAL, 1);           
            mapFragment.show(getFragmentManager(), "Dialog");
        }       

        return rows;
}
public int showMapFragment(int年、int月、int日){
谷歌地图;
支持mappfragma片段;
//myMapFragment=SupportMapFragment.newInstance(mapOptions);
ArrayList latLongArray=新的ArrayList();
ArrayList timeArray=新的ArrayList();
ArrayList distanceToLastArray=新的ArrayList();
ArrayList speedArray=新的ArrayList();
LocationOpenHelper myLocationDb=新的LocationOpenHelper(此);
myLocationDb.printsomething();
SQLiteDatabase locationDb=myLocationDb.getReadableDatabase();
日历开始日期=新的GregorianCalendar();
//重置小时、分钟、秒和毫秒
startDate.set(日历小时,0);
开始日期设置(日历分钟,0);
开始日期设置(日历秒,0);
startDate.set(日历毫秒,0);
//startDate.add(日历.月日,-4);
起始日期(日历年、年份);
startDate.set(日历.月,月);
startDate.set(日历日,月日);
日历结束日期=新的GregorianCalendar();
//重置小时、分钟、秒和毫秒
endDate.set(日历小时,天的小时数,0);
endDate.set(日历分钟,0);
endDate.set(日历秒,0);
endDate.set(日历毫秒,0);
endDate.set(日历年、年份);
endDate.set(日历.月,月);
endDate.set(日历.日期/月/日,天);
endDate.add(日历.月日,1);
字符串orderBy=列时间+“ASC”;
Cursor cur=locationDb.query(位置表名称,新字符串[]{COLUMN\u ID,COLUMN\u纬度,COLUMN\u经度,COLUMN\u时间,COLUMN\u速度,COLUMN\u距离\u LAST\u LOC},
列时间+“>=”+startDate.getTimeInMillis()+”和“+COLUMN时间+”<”+endDate.getTimeInMillis(),null,null,orderBy);
int计数器=0;
cur.moveToFirst();
int nodeaded=1;
双latSum=0;
双lngSum=0;
double[]lastThreeLats={0,0,0};
double[]lastThreeLngs={0,0,0};
int ind=0;
积分=0;
双预拉特=0;
双重预处理=0;
双预拉伸=0;
双预涂=0;
双预相关=0;
双预压=0;
if(cur.getCount()==1){
prepreprelate=cur.getDouble(1);
prePrePreLng=cur.getDouble(2);
Preprelate=当前getDouble(1);
preprepreng=cur.getDouble(2);
preLat=当前getDouble(1);
preLng=当前getDouble(2);
}else if(cur.getCount()==2){
prepreprelate=cur.getDouble(1);
prePrePreLng=cur.getDouble(2);
cur.moveToNext();
Preprelate=当前getDouble(1);
preprepreng=cur.getDouble(2);
preLat=当前getDouble(1);
preLng=当前getDouble(2);
}if(cur.getCount()==3){
prepreprelate=cur.getDouble(1);
prePrePreLng=cur.getDouble(2);
cur.moveToNext();
Preprelate=当前getDouble(1);
preprepreng=cur.getDouble(2);
cur.moveToNext();
preLat=当前getDouble(1);
preLng=当前getDouble(2);
}else if(cur.getCount()>3){
prepreprelate=cur.getDouble(1);
prePrePreLng=cur.getDouble(2);
cur.moveToNext();
Preprelate=当前getDouble(1);
preprepreng=cur.getDouble(2);
cur.moveToNext();
preLat=当前getDouble(1);
preLng=当前getDouble(2);
cur.moveToNext();
}
while(cur.isAfterLast()==false)
{   
double currentLat=cur.getDouble(1);
双电流lng=cur.getDouble(2);
latLongArray.add(新板条((预拉伸+预拉伸+预拉伸+当前板条)/4,(预拉伸+预拉伸+预拉伸+当前板条)/4);
timeArray.add(cur.getLong(3));
距离astarray.add(cur.getInt(5));
add(cur.getInt(4));
prepreprelate=prepreprelate;
预涂=预涂;
preprelate=preLat;
预涂=预涂;
preLat=当前getDouble(1);
preLng=当前getDouble(2);
cur.moveToNext();
nodead++;
}   
cur.close();
int rows=cur.getCount();
//仅当有可用记录时才显示地图
如果(行>0){
DialogFragment mapFragment=MapDialogFragment.newInstance(latLongArray、timeArray、distanceToLastArray、speedArray);
mapFragment.setStyle(DialogFragment.STYLE_NORMAL,1);
show(getFragmentManager(),“Dialog”);
}       
返回行;
}
第三,显示地图

public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);        

    int arraySize = inputLatLng.size();
    final LatLng startPoint = inputLatLng.get(0);  
    final LatLng endPoint = inputLatLng.get(arraySize - 1);

    GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map2)).getMap();      
    map.addMarker(new MarkerOptions().position(startPoint).title("Starting point"));        
    map.addMarker(new MarkerOptions().position(endPoint).title("Ending point"));

        double latSum = 0;
        double lngSum = 0;

        for (int j=0; j<arraySize; j++){
            latSum = inputLatLng.get(j).latitude + latSum;
            lngSum = inputLatLng.get(j).longitude + lngSum;
        }           

        LatLng center = new LatLng(latSum/arraySize, lngSum/arraySize);                     
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(center, 15));          
        map.animateCamera(CameraUpdateFactory.zoomTo(18), 2000, null);                      
        ArrayList<Integer> Colors =new ArrayList<Integer> (); 

        Colors.add(Color.RED);
        Colors.add(Color.BLACK);
        Colors.add(Color.BLUE);
        Colors.add(Color.GREEN);
        Colors.add(Color.YELLOW);                   

        for (int i=0; i<inputLatLng.size(); i++){
            PolylineOptions plOptions = new PolylineOptions();
            if ((i+1) == inputLatLng.size())
                break;

            //draw line every two points
            plOptions.add(inputLatLng.get(i));
            plOptions.add(inputLatLng.get(i+1));

            plOptions.width(5);

            float currentSpeed = speed.get(i);
            if (currentSpeed == 0.0)
                plOptions.color(Color.rgb(22, 139, 22));
            else if (currentSpeed > 0.0 && currentSpeed < 1.0)
                plOptions.color(Color.GREEN);
            else if (currentSpeed >= 1.0 && currentSpeed < 2.0)
                plOptions.color(Color.YELLOW);
            else if (currentSpeed >= 2.0)
                plOptions.color(Color.RED);

            map.addPolyline(plOptions);                                         
            map.setMyLocationEnabled(true);             
            map.setMapType(GoogleMap.MAP_TYPE_NORMAL);                  

        }

        double travelledDistance = distanceTravelled(distanceToLast);
        double travelledTime = timeTravelled(time);

        travelledTime = Math.round(travelledTime * 100);
        travelledTime = travelledTime/100;

        double averageSpeed = travelledDistance / travelledTime;;
        double highestSpeed = highestSpeed(speed);


        setTextSize();
        tvSpeed.setTextSize(averageSpeedTv);
        tvDistance.setTextSize(distanceTv);
        tvTime.setTextSize(timeTv);
        tvHighestSpeed.setTextSize(highestSpeedTv);

        tvSpeed.setText(getResources().getString(R.string.av_speed) + " " + String.format("%.2f", averageSpeed) + " km/h");
        tvDistance.setText(getResources().getString(R.string.distance_travelled)+ " " + travelledDistance + " km");
        tvTime.setText(getResources().getString(R.string.time_travelled) + " " + travelledTime + " h");
        tvHighestSpeed.setText(getResources().getString(R.string.highest_speed) + " " + highestSpeed + " km/h");

}
activitycreated上的公共void(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
int arraySize=inputLatLng.size();
最终LatLng startPoint=输入LatLng.get(0);
最终LatLng端点=inputLatLng.get(arraySize-1);
谷歌地图=((