Positing user current location and show it in Google maps

前端 未结 2 1782
夕颜
夕颜 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 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.

提交回复
热议问题