java - 定位用户当前位置并在 Google map 中显示

标签 java android google-maps

我正在开发一个 Android 应用程序,其中包含 3 个 Activity ,其中之一是 map 。我正在使用谷歌地图

我想要什么:

  1. 当用户打开 Activity ( map )时,它会向用户显示她的位置而不是坐标。

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

}

最佳答案

我已经实现了你想要的同样的事情。我为您提供示例代码。在此,我还在获取位置时实现了 ProgressDialog。

这是获取位置的起点。我将此命名为 AndroidLocationActivity。这是您的应用程序启动时启动的第一个 Activity 。

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

在此处设置经纬度并开始新 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
        }
    } 

这是我显示 map 的功能。这是 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类

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

    }

}

希望这会有所帮助......

关于java - 定位用户当前位置并在 Google map 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9586530/

相关文章:

java - JCA 资源适配器如何读取 ra.xml 中定义的自定义属性

android - "SHAREit"android 应用程序在技术上是如何工作的?

android - 通过 Android 上传的照片在 Facebook 上未获批准

android - 如何仅在Retrofit响应成功时添加GSON CallAdapter Factory

java - Android MapView - 如何获取 map 选定部分的中心?

iphone - 在非英语语言的 iPhone 上使用 Google map 寻找方向

java - 小程序中的netty抛出AccessControlException

java - 使用 google+ 的 api key 从 java 中的桌面应用程序发出请求

java - 第一次迭代后的 while 循环不更新数组值

ios - 以相同的方式在 GMSAutocomplete 中使用文本字段而不是搜索栏