Java android谷歌地图路线更新

Java android谷歌地图路线更新,java,android,google-maps-api-3,Java,Android,Google Maps Api 3,首先,我是android和JAVA新手,也是stackoverflow的注册用户,但它多次帮助我找到了一个好的答案,所以,感谢这个社区,让我在学校的项目中多次摆脱困境 我在这里是因为我被困在这个小项目中,是一个大学项目,所以不涉及资金 我正在尝试使用android谷歌地图api在城市中移动时显示并更新路线。直到现在,我都能找到我的位置,我可以显示两点之间的路线,但问题是,当我想从我的当前位置获取起点时,我似乎无法将其保存到变量(或者我不知道如何保存),我使用谷歌示例作为地图显示的基础。 我将发布

首先,我是android和JAVA新手,也是stackoverflow的注册用户,但它多次帮助我找到了一个好的答案,所以,感谢这个社区,让我在学校的项目中多次摆脱困境 我在这里是因为我被困在这个小项目中,是一个大学项目,所以不涉及资金

我正在尝试使用android谷歌地图api在城市中移动时显示并更新路线。直到现在,我都能找到我的位置,我可以显示两点之间的路线,但问题是,当我想从我的当前位置获取起点时,我似乎无法将其保存到变量(或者我不知道如何保存),我使用谷歌示例作为地图显示的基础。 我将发布整个代码,也许有人也会发现它很有用。因为这是一个大学的小项目,我没有秘密要隐藏,我在这里学习,所以很高兴发布完整的代码。 如果有人对我的问题有任何提示,我将不胜感激。非常感谢。 注意:问题是让这个婴儿显示从我当前位置到第二个固定位置的路线。 主要代码如下:

public class mapDisplay extends ActionBarMapActivity {

 private LocationManager myLocationManager;
 private LocationListener myLocationListener;
 private MapController myMapController;
 private MapView myMapView;
 private MyLocationOverlay myLocation;


 private void CenterLocatio(GeoPoint centerGeoPoint)
 {
  myMapController.animateTo(centerGeoPoint);
 };

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_screen);

    myMapView = (MapView) findViewById(R.id.mapview);
    //mapView.setBuiltInZoomControls(true);

    myMapView.setSatellite(false); //Set satellite view
    myMapController = myMapView.getController();
    myMapController.setZoom(15); //Fixed Zoom Level

    myLocationManager = (LocationManager)getSystemService(
      Context.LOCATION_SERVICE);

    //For enable location services dialogue
    if (!myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){  
          createGpsDisabledAlert();  
     }  
    // see createGpsDisabledAlert function below

    myLocationListener = new MyLocationListener();

    myLocationManager.requestLocationUpdates(
      LocationManager.GPS_PROVIDER,
      0,
      0,
      myLocationListener);

    //Get the current location in start-up
    GeoPoint initGeoPoint = new GeoPoint(
     (int)(myLocationManager.getLastKnownLocation(
      LocationManager.GPS_PROVIDER)
      .getLatitude()*1000000),
     (int)(myLocationManager.getLastKnownLocation(
      LocationManager.GPS_PROVIDER)
      .getLongitude()*1000000));
     CenterLocatio(initGeoPoint);

     //draw the sample route
    MapView mv = (MapView) findViewById(R.id.mapview);
    mv.setBuiltInZoomControls(true);
    MapController mc = mv.getController();

    ArrayList all_geo_points = getDirections(50.0536, 8.69339, 50.021973, 8.69584);

    GeoPoint moveTo = (GeoPoint) all_geo_points.get(0);
    mc.animateTo(moveTo);
    mc.setZoom(12);
    mv.getOverlays().add(new MyOverlay(all_geo_points));


    //Adding position icon for current location
 // Add the MyLocationOverlay
    myLocation = new MyLocationOverlay(this, myMapView);
    myMapView.getOverlays().add(myLocation);
    myLocation.enableMyLocation();

    myLocation.runOnFirstFix(new Runnable() {
        public void run() {
            myMapController.animateTo(myLocation.getMyLocation());


        }
     });

   }

   private class MyLocationListener implements LocationListener{

    public void onLocationChanged(Location argLocation) {
     // TODO Auto-generated method stub
     GeoPoint myGeoPoint = new GeoPoint(
      (int)(argLocation.getLatitude()*1000000),
      (int)(argLocation.getLongitude()*1000000));

     CenterLocatio(myGeoPoint);
    }

    public void onProviderDisabled(String provider) {
     // TODO Auto-generated method stub

        //toast shown if GPS is disabled
        Context context = getApplicationContext();
        CharSequence text = "GPS is disabled! If you want to take full advantage of map please enable the GPS!";
        int duration = Toast.LENGTH_LONG;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }

    public void onProviderEnabled(String provider) {
     // TODO Auto-generated method stub
    }

    public void onStatusChanged(String provider,
      int status, Bundle extras) {
     // TODO Auto-generated method stub
    } 
}

   @Override
    protected void onResume() {
        super.onResume();
        myLocation.enableMyLocation();
    }

    @Override 
    protected void onPause() {
        super.onPause();
        myLocation.disableMyLocation();
    }

    //Back button press returns to first activity (selection screen)
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        //super.onBackPressed();
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }


    //rest of functions for GPS alert
   private void createGpsDisabledAlert(){  
      AlertDialog.Builder builder = new AlertDialog.Builder(this);  
      builder.setMessage("Your GPS is disabled! Would you like to enable it?")  
           .setCancelable(false)  
           .setPositiveButton("Enable GPS",  
                new DialogInterface.OnClickListener(){  
                public void onClick(DialogInterface dialog, int id){  
                     showGpsOptions();  
                }  
           });  
           builder.setNegativeButton("Do nothing",  
                new DialogInterface.OnClickListener(){  
                public void onClick(DialogInterface dialog, int id){  
                     dialog.cancel();  
                }  
           });  
      AlertDialog alert = builder.create();  
      alert.show();  
      }  

      private void showGpsOptions(){  
              Intent gpsOptionsIntent = new Intent(  
                      android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
              startActivity(gpsOptionsIntent);  
      }  

     //Testing - directions

     public static ArrayList getDirections(double lat1, double lon1, double lat2, double lon2) {
                String url = "http://maps.googleapis.com/maps/api/directions/xml?origin=" +lat1 + "," + lon1  + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
                String tag[] = { "lat", "lng" };
                ArrayList list_of_geopoints = new ArrayList();
                HttpResponse response = null;
                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpContext localContext = new BasicHttpContext();
                    HttpPost httpPost = new HttpPost(url);
                    response = httpClient.execute(httpPost, localContext);
                    InputStream in = response.getEntity().getContent();
                    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                    Document doc = builder.parse(in);
                    if (doc != null) {
                        NodeList nl1, nl2;
                        nl1 = doc.getElementsByTagName(tag[0]);
                        nl2 = doc.getElementsByTagName(tag[1]);
                        if (nl1.getLength() > 0) {
                            list_of_geopoints = new ArrayList();
                            for (int i = 0; i < nl1.getLength(); i++) {
                                Node node1 = nl1.item(i);
                                Node node2 = nl2.item(i);
                                double lat = Double.parseDouble(node1.getTextContent());
                                double lng = Double.parseDouble(node2.getTextContent());
                                list_of_geopoints.add(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)));
                            }
                        } else {
                            // No points found
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return list_of_geopoints;
            }}
公共类mapDisplay扩展了ActionBarMapActivity{
私人位置经理myLocationManager;
私有位置侦听器myLocationListener;
私有映射控制器myMapController;
私有地图视图myMapView;
私人我的位置高于私人我的位置;
专用空心中心位置(地质点中心地质点)
{
myMapController.animateTo(中心点);
};
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.map_屏幕);
myMapView=(MapView)findViewById(R.id.MapView);
//mapView.SetBuilTinZoomControl(真);
myMapView.setSatellite(false);//设置卫星视图
myMapController=myMapView.getController();
myMapController.setZoom(15);//固定缩放级别
myLocationManager=(LocationManager)getSystemService(
上下文、位置和服务);
//用于启用位置服务对话
如果(!myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
createGPSDisableAlert();
}  
//请参见下面的CreateGPSDisableAlert函数
myLocationListener=新建myLocationListener();
myLocationManager.RequestLocationUpdate(
LocationManager.GPS\u提供程序,
0,
0,
myLocationListener);
//获取启动中的当前位置
地质点初始地质点=新地质点(
(int)(myLocationManager.GetLastKnown位置(
LocationManager.GPS_提供商)
.getLatitude()*1000000),
(int)(myLocationManager.GetLastKnown位置(
LocationManager.GPS_提供商)
.getLongitude()*1000000));
中心位置(初始地质点);
//绘制示例路线
MapView mv=(MapView)findViewById(R.id.MapView);
mv.SetBuiltinzoomControl(真);
MapController mc=mv.getController();
ArrayList all_geo_points=getDirections(50.0536,8.69339,50.021973,8.69584);
地理点移动到=(地理点)所有地理点。获取(0);
动画师(moveTo);;
mc.setZoom(12);
mv.getOverlays().add(新的MyOverlay(所有地理点));
//为当前位置添加位置图标
//添加MyLocationOverlay
myLocation=新的MyLocationOverlay(这是myMapView);
myMapView.getOverlays().add(myLocation);
myLocation.enableMyLocation();
myLocation.runOnFirstFix(新的Runnable(){
公开募捐{
myMapController.animateTo(myLocation.getMyLocation());
}
});
}
私有类MyLocationListener实现LocationListener{
已更改位置上的公共void(位置argLocation){
//TODO自动生成的方法存根
地质点myGeoPoint=新地质点(
(int)(argLocation.getLatitude()*1000000),
(int)(argLocation.getLongitude()*1000000));
中心位置(myGeoPoint);
}
公共无效onProviderDisabled(字符串提供程序){
//TODO自动生成的方法存根
//如果GPS被禁用,则显示toast
Context=getApplicationContext();
CharSequence text=“GPS已禁用!如果您想充分利用地图,请启用GPS!”;
int duration=Toast.LENGTH\u LONG;
Toast Toast=Toast.makeText(上下文、文本、持续时间);
toast.show();
}
公共无效onProviderEnabled(字符串提供程序){
//TODO自动生成的方法存根
}
公共无效onStatusChanged(字符串提供程序,
int状态,捆绑附加){
//TODO自动生成的方法存根
} 
}
@凌驾
受保护的void onResume(){
super.onResume();
myLocation.enableMyLocation();
}
@凌驾
受保护的void onPause(){
super.onPause();
myLocation.disableMyLocation();
}
//按后退按钮返回到第一个活动(选择屏幕)
@凌驾
public void onBackPressed(){
//TODO自动生成的方法存根
//super.onBackPressed();
}
@凌驾
受保护的布尔值isRouteDisplayed(){
返回false;
}
//GPS警报的其余功能
私有void createGPSDisableAlert(){
AlertDialog.Builder=新建AlertDialog.Builder(此);
setMessage(“您的GPS已禁用!是否要启用它?”)
.setCancelable(错误)
.setPositiveButton(“启用GPS”,
新建DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int-id){
showGpsOptions();
}  
});  
builder.setNegativeButton(“什么都不做”,
新建DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int-id){
dialog.cancel();
}  
});  
AlertDialog alert=builder.create();
alert.show();
}  
普里瓦