Positing user current location and show it in Google maps

前端 未结 2 1781
夕颜
夕颜 2020-12-18 16:53

I am developing an android application that contains 3 activities and one of them is map. I am using google maps

what I want:

  1. When the user opens th

相关标签:
2条回答
  • 2020-12-18 17:44

    Remove your method onCreate and add this code:

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        initMap(); // This is the method which initialize the map
    
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                0, new GeoUpdateHandler());
    
        Drawable drawable = this.getResources().getDrawable(R.drawable.point);
        itemizedoverlay = new CustomPinpoint(drawable);
        createMarker();
    }
    
    @Override
    public void onResume()
    {
        super.onResume();
        try
        {
            initMyLocation();
        }catch(Exception e){}
    }
    
    
    /**
     * Inits the map.
     */
    protected void initMap()
    {
        mapView = (MyMapView) findViewById(R.id.mapView);
    
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(true);
        mapView.setStreetView(false);
        mapController = mapView.getController();
    
        mapOverlay = new MapOverlay();
        List<Overlay> overlays = mapView.getOverlays();
    
        overlays.add(mapOverlay);
    
        mapController.setZoom(14);
    
        mapView.invalidate();
    }
    
    /**
     * Initialises the MyLocationOverlay and adds it to the overlays of the map.
     */
    public void initMyLocation() {
        try
        {
            LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Location l = LocationService.getLastKnownLocation(lm);
            int lat = (int)(l.getLatitude()*1E6);
            int lng = (int)(l.getLongitude()*1E6);
            mapController.setCenter(new GeoPoint(lat , lng));
    
            myLocOverlay = new MyLocationOverlay(this, mapView);
            myLocOverlay.enableMyLocation();
            mapView.getOverlays().add(myLocOverlay);
            mapController.setCenter(myLocOverlay.getMyLocation());
        }catch(NullPointerException e){}
    
        findMe();
    }
    
    
    
    
    /**
     * This method will animate to my current position
     */
    public void findMe()
    {
        try
        {
            mapController.animateTo(myLocOverlay.getMyLocation());
        }catch(NullPointerException e){}
    }
    

    Then to store the Overlays for future use you can either use SharedPreferences or SQLite. There are loads of tutorials for each of them.

    0 讨论(0)
  • 2020-12-18 17:45

    I have implemented the same thing you want. I am providing you the sample code. In this I have also implemented the ProgressDialog when fetching the location.

    This is the starting point for getting the location. I named this AndroidLocationActivity. This is the 1st activity which starts when your app starts.

    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 = AndroidLocationActivity.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(AndroidLocationActivity.this, String.valueOf(time), Toast.LENGTH_LONG).show();
    

    Here set the time if time is not more than 1minute than i am not updating the location.

                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 (AndroidLocationActivity.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(AndroidLocationActivity.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 doInBackground(String... params) {
                // TODO Auto-generated method stub
                while (flag) {
                    if (latitude !=0 && longitude != 0) {
                        flag=false;
                    }
                }
                return null;
            }
    
            @Override
            protected void onPostExecute(Void result) {
                // TODO Auto-generated method stub
                Toast.makeText(AndroidLocationActivity.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(AndroidLocationActivity.this.getApplicationContext(), HomeMenuActivity.class);
    

    set the lat & lng here and start new activity

                homeIntent.putExtra("lat", latitude);
        homeIntent.putExtra("lng", longitude);
                startActivity(homeIntent);
                }
                locationManager.removeUpdates(locationListener);
            }
        }
    
        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
            }
        } 
    

    This is the function in which i am displaying the Map. This is the HomeMenuActivity

    public static Context context;
    onCreate(..) {
        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(your pic....);
    
            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();
    
        }
    
    }
    

    ItemizedOverlay Class

    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();
    
            }
    
        }
    
    
    
        @Override
    
        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);
    
        }
    
    }
    

    Hope this will help.....

    0 讨论(0)
提交回复
热议问题