How to display my location on Google Maps for Android API v2

前端 未结 6 2004
抹茶落季
抹茶落季 2020-12-07 15:03

I\'ve looked high and low for an answer on this, and no one, in any forum question has been able to help. I\'ve searched through the tutorials. The API Guide says:

6条回答
  •  失恋的感觉
    2020-12-07 15:31

    Java code:

    public class MapActivity extends FragmentActivity implements LocationListener  {
    
        GoogleMap googleMap;
        LatLng myPosition;
    
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_map);
    
            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment)
            getSupportFragmentManager().findFragmentById(R.id.map);
    
            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();
    
            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);
    
            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    
            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();
    
            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);
    
            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);
    
            if (location != null) {
                // Getting latitude of the current location
                double latitude = location.getLatitude();
    
                // Getting longitude of the current location
                double longitude = location.getLongitude();
    
                // Creating a LatLng object for the current location
                LatLng latLng = new LatLng(latitude, longitude);
    
                myPosition = new LatLng(latitude, longitude);
    
                googleMap.addMarker(new MarkerOptions().position(myPosition).title("Start"));
            }
        }
    }
    

    activity_map.xml:

    
    
    

    You will get your current location in a blue circle.

提交回复
热议问题