Укажите текущее местоположение пользователя и покажите его на картах Google - PullRequest
0 голосов
/ 06 марта 2012

Я занимаюсь разработкой приложения для Android, которое содержит 3 действия, одним из которых является карта.Я использую карты Google

, что я хочу:

  1. Когда пользователь открывает действие (карту), он показывает его местоположение, а не координаты.

  2. Пользователь также должен иметь возможность устанавливать (закреплять) любое место с помощью булавки, и мое приложение должно сохранять координаты для этого булавки в переменной, чтобы я мог использовать его позже.

public class LActivity extends MapActivity 
{    
    /** Called when the activity is first created. */

    MapView mapView;
    GeoPoint geo;
    MapController mapController;
    LocationManager locationManager;
    CustomPinpoint itemizedoverlay;


    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapView);
        // create a map view
        //LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main);

        mapView.setBuiltInZoomControls(true);
        // Either satellite or 2d 
        mapView.setSatellite(true);
        mapController = mapView.getController();
        mapController.setZoom(14); // Zoon 1 is world view
        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();
    }

    public class GeoUpdateHandler implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            int lat = (int) (location.getLatitude() * 1E6);
            int lng = (int) (location.getLongitude() * 1E6);
            GeoPoint point = new GeoPoint(lat, lng);
            createMarker();
            mapController.animateTo(point); // mapController.setCenter(point);
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

    private void createMarker() {
        GeoPoint p = mapView.getMapCenter();
        OverlayItem overlayitem = new OverlayItem(p, "", "");
        itemizedoverlay.addOverlay(overlayitem);
        mapView.getOverlays().add(itemizedoverlay);
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}

это класс CustomPinpoint

public class CustomPinpoint extends ItemizedOverlay<OverlayItem> {

    static int maxNum = 3;
    OverlayItem overlays[] = new OverlayItem[maxNum];
    int index = 0;
    boolean full = false;
    CustomPinpoint itemizedoverlay;

    public CustomPinpoint(Drawable defaultMarker) {
        super(boundCenterBottom(defaultMarker));
    }

    @Override
    protected OverlayItem createItem(int i) {
        return overlays[i];
    }

    @Override
    public int size() {
        if (full) {
            return overlays.length;
        } else {
            return index;
        }
    }

    public void addOverlay(OverlayItem overlay) {
        if (index < maxNum) {
            overlays[index] = overlay;
        } else {
            index = 0;
            full = true;
            overlays[index] = overlay;
        }
        index++;
        populate();
    }

}

Ответы [ 2 ]

1 голос
/ 07 марта 2012

Я реализовал то же, что вы хотите. Я предоставляю вам пример кода. В этом я также реализовал ProgressDialog при получении местоположения.

Это отправная точка для получения местоположения. Я назвал это AndroidLocationActivity. Это первое действие, которое начинается при запуске приложения.

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();

Здесь задайте время, если время не превышает 1 минуты, чем я не обновляю местоположение.

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

установите здесь лат и lng и начните новое действие

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

Это функция, в которой я отображаю карту. Это 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);

    }

}

Надеюсь, это поможет .....

0 голосов
/ 06 марта 2012

Удалите ваш метод onCreate и добавьте этот код:

@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){}
}

Затем, чтобы сохранить оверлеи для будущего использования, вы можете использовать SharedPreferences или SQLite . Для каждого из них есть множество учебных пособий.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...