android谷歌地图路线更新

时间:2012-10-05 23:36:31

标签: java android google-maps-api-3

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

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

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;
            }}

编辑 10.07.2012:我开始怀疑这是一个愚蠢的问题,没有人知道答案或没有人想回答。 我试图保存到局部变量并在获取Directions()函数中使用它们但由于某种原因导致我的应用程序崩溃。或者更好,我被邀请在编译之前修复错误。

0 个答案:

没有答案