在Android中的Google地图中获取用户当前位置

时间:2012-03-18 15:49:01

标签: java android google-maps

  

可能重复:
  positing user current location and show it in Google maps

我正在开发具有Map Activity的应用程序。这张地图应该:

  1. 定位用户当前位置并将其显示在地图中
  2. 用户可以固定地图中的任何位置,我应该在此针中保存坐标
  3. 这是我的代码

       public class MapStackActivity extends MapActivity { 
    
    String provider;
    public double latitude, longitude = 0;
        CurrentPositionTask getCurrentLocation;
        Location currentLocation;
        LocationListener locationListener;
        LocationManager locationManager;
        private long time=0;
    
      @Override
      public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
    
       try {
           locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
           setCriteria();
           currentLocation = MapStackActivity.this.locationManager.getLastKnownLocation(provider);
    
           if (currentLocation == null) {
               currentLocation = new Location(provider);
           }
           time = currentLocation.getTime();
    
           if (latitude == 0 && longitude == 0) {
               latitude = currentLocation.getLatitude();
               longitude = currentLocation.getLongitude();    
           }
           Toast.makeText(MapStackActivity.this, String.valueOf(time), Toast.LENGTH_LONG).show();
           if (time >= 100000) {
               latitude = 0;
               longitude = 0;
           }
       } catch (NullPointerException e) {
           // TODO: handle exception
           System.out.println("Null");
           e.printStackTrace();
       } 
       catch (Exception e) {
           // TODO: handle exception
           e.printStackTrace();
       }
    
       runAsyncTask();    
      }
    
       @Override
       protected void onDestroy() {
       // TODO Auto-generated method stub
       super.onDestroy();
       locationManager.removeUpdates(locationListener);
      }
    
      public void setCriteria() {
       Criteria criteria = new Criteria();
       criteria.setAccuracy(Criteria.ACCURACY_FINE);
       criteria.setAltitudeRequired(false);
       criteria.setBearingRequired(false);
       criteria.setCostAllowed(true);
       criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
       provider = locationManager.getBestProvider(criteria, true);
       Toast.makeText(getApplicationContext(), "Provider - " + provider, Toast.LENGTH_SHORT).show();
       if (provider == null) {
           provider = LocationManager.GPS_PROVIDER;
       }
      }    
    
    
      public void runAsyncTask() {
       // TODO Auto-generated method stub
       if (getCurrentLocation == null) {
           getCurrentLocation = new CurrentPositionTask();    
       }
    
       if (getCurrentLocation != null) {
           getCurrentLocation.execute("Searching for Location");    
         }
      }
    
     public boolean checkConnection()
      {
       //ARE WE CONNECTED TO THE NET
    
       ConnectivityManager conMgr = (ConnectivityManager) getSystemService (MapStackActivity.CONNECTIVITY_SERVICE);
       if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable()&& conMgr.getActiveNetworkInfo().isConnected()) {
           return true;
       } else {
           return false;
       }
      } 
    
    
      private class CurrentPositionTask extends AsyncTask<String, Void, Void>
       {
       private ProgressDialog Dialog = new ProgressDialog(MapStackActivity.this);
       private boolean flag = true;
    
       public CurrentPositionTask() {
           locationListener = new MyLocationListener();
       }
    
       @Override
       protected void onPreExecute() {
           // TODO Auto-generated method stub
           super.onPreExecute();
           try {
               if (checkConnection()) {
                   Dialog.setTitle("Loading");
                   Dialog.setMessage("Searching for Location");
                   Dialog.show();
                   locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
               }
               else {
                   Toast.makeText(getApplicationContext(), "Internet is Not Available", Toast.LENGTH_LONG).show();
               }    
           } catch (Exception e) {
               // TODO: handle exception
               e.printStackTrace();
           }
          }
    
    
    
       @Override
       protected void onPostExecute(Void result) {
           // TODO Auto-generated method stub
           Toast.makeText(MapStackActivity.this, "Location Floats:- " + latitude + "," + longitude, Toast.LENGTH_LONG).show();
    
           super.onPostExecute(result);
           if (Dialog != null && Dialog.isShowing()) {
               Dialog.dismiss();
               time=0;
               Intent homeIntent = new Intent(MapStackActivity.this.getApplicationContext(), HomeMenuActivity.class);
               homeIntent.putExtra("lat", latitude);
               homeIntent.putExtra("lng", longitude);
                       startActivity(homeIntent);
                       }
                       locationManager.removeUpdates(locationListener);
                   }
    
    @Override
    protected Void doInBackground(String... params) {
        // TODO Auto-generated method stub
        return null;
    }
               }
    
      class MyLocationListener implements LocationListener {
    
       @Override
       public void onLocationChanged(Location location) {
           // TODO Auto-generated method stub
           if (location != null) {
               latitude = location.getLatitude();
               longitude = location.getLongitude();    
           }
       }
    
       @Override
       public void onProviderDisabled(String arg0) {
           // TODO Auto-generated method stub
           Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();
       }
    
       @Override
       public void onProviderEnabled(String arg0) {
           // TODO Auto-generated method stub
           Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
       }
    
       @Override
       public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
           // TODO Auto-generated method stub
       }
     }
    
    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    } }
    

    第二个活动是:

       public class HomeMenuActivity extends Activity{
    
    public static Context context;
    GeoPoint geoPoint;
    MapView mapview;
    MapController mapControll;
    Drawable userPic;
    public double latitude=0;
    public double longitude = 0;
     MyItemizedOverlay userPicOverlay;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        context = getApplicationContext(); // it will be used in Itemized Overlay
         latitude = getIntent().getDoubleExtra("lat", 0);//get the lat & lng
         longitude = getIntent().getDoubleExtra("lng", 0);
    }
    
    
    public void showMap() {
    
        // TODO Auto-generated method stub
        try {
    
            geoPoint = new GeoPoint((int)(latitude * 1E6),(int)(longitude * 1E6));
    
            mapview = (MapView)findViewById(R.id.mapview);
    
            mapControll= mapview.getController();
    
            mapview.setBuiltInZoomControls(true);
    
            mapview.setStreetView(true);
    
            mapview.setTraffic(true);
    
            mapControll.setZoom(16);
    
            mapControll.animateTo(geoPoint);
    
    
    
            userPic = this.getResources().getDrawable(R.drawable.ic_launcher);
    
            userPicOverlay = new MyItemizedOverlay(userPic);
    
            OverlayItem overlayItem = new OverlayItem(geoPoint, "", null);
    
            userPicOverlay.addOverlay(overlayItem);
    
            mapview.getOverlays().add(userPicOverlay);
            //Added symbols will be displayed when map is redrawn so force redraw now
    
            mapview.postInvalidate();
    
        } catch (Exception e) {
    
            // TODO: handle exception
    
            e.printStackTrace();
    
        }
    
    }
    public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
    
    
    
        private ArrayList<OverlayItem> myOverlays ;
    
    
    
        public MyItemizedOverlay(Drawable defaultMarker) {
    
            super(boundCenterBottom(defaultMarker));
    
            myOverlays = new ArrayList<OverlayItem>();
    
            populate();
    
        }
    
    
    
        public void addOverlay(OverlayItem overlay){
    
            myOverlays.add(overlay);
    
            populate();
    
        }
    
    
    
        @Override
    
        protected OverlayItem createItem(int i) {
    
            return myOverlays.get(i);
    
        }
    
    
    
        // Removes overlay item i
    
        public void removeItem(int i){
    
            myOverlays.remove(i);
    
            populate();
    
        }
    
    
    
        // Returns present number of items in list
    
        @Override
    
        public int size() {
    
            return myOverlays.size();
    
        }
    
    
    
    
    
        public void addOverlayItem(OverlayItem overlayItem) {
    
            myOverlays.add(overlayItem);
    
            populate();
    
        }
    
    
    
    
    
        public void addOverlayItem(int lat, int lon, String title) {
    
            try {
    
                GeoPoint point = new GeoPoint(lat, lon);
    
                OverlayItem overlayItem = new OverlayItem(point, title, null);
    
                addOverlayItem(overlayItem);    
    
            } catch (Exception e) {
    
                // TODO: handle exception
    
                e.printStackTrace();
    
            }
    
        }
    
    
    
        protected boolean onTap(int index) {
    
            // TODO Auto-generated method stub
    
            String title = myOverlays.get(index).getTitle();
    
            Toast.makeText(HomeMenuActivity.context, title, Toast.LENGTH_LONG).show();
    
            return super.onTap(index);
    
        }
    
    }}
    

    它不起作用,只是给我Toast“provider -Gps”然后“0”然后“Location float 0.0,0.0”。有什么问题,我该如何解决?

0 个答案:

没有答案