Getting User Location in maps

Ashten

I am trying to get user's location in map. I have two pages--one which has a 'click to show my location' button and another page which leads to the map when button is clicked. I want only the second page when the app is opened. But I can't figure out how to correct the code. I have checked some other questions here but I can't solve my problem. Kindly help as I am a beginner.

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

public void showMyLocation(View view) {
    startActivity(new Intent(getApplicationContext(),MapsActivity.class));
}
}

MapsActivity.java

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{

private GoogleMap mMap;
LocationManager locationManager;
private static final int REQUEST_LOCATION_PERMISSION = 1;
Marker marker;
LocationListener locationListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]
                        {Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_LOCATION_PERMISSION);
    }
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            //get the location name from latitude and longitude
            Geocoder geocoder = new Geocoder(getApplicationContext());
            try {
                List<Address> addresses =
                        geocoder.getFromLocation(latitude, longitude, 1);
                String result = addresses.get(0).getLocality()+":";
                result += addresses.get(0).getCountryName();
                LatLng latLng = new LatLng(latitude, longitude);
                mMap.addMarker(new MarkerOptions().position(latLng).title(result));
                mMap.setMaxZoomPreference(20);
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

// Add a marker in Sydney and move the camera
//        LatLng sydney = new LatLng(-34, 151);
//        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}
Akash Amin

You didn't call the showMyLocation method in onCreate.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showMyLocation();

    }

    //Removed the view object paramter as its not required
    public void showMyLocation() {
        startActivity(new Intent(getApplicationContext(),MapsActivity.class));
    }
}

Best practice is if you don't have anything to do with your MainActivity then set MapsActivity as launcher activity.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Getting user's location for google Maps

Google Maps iOS SDK, Getting Current Location of user

Issues getting user location from CLLocationManager (Google Maps API)

Not getting current location on maps

Not getting user location

Getting user location in swift

Follow user location on google maps

google maps - centering on user location

Getting the name of a location from google maps

Display user location on react native maps

React-google-maps user location

Saving user input & location from current location Google maps API

Getting user location on opening map in mapbox

Good way of getting the user's location in Android

Getting locations near User's Location

Getting user location in Android seems impossible

Getting user location in Xamarin with google play services

getting user location and creating map not in sync

Getting coodinates of a location by user tagging place in map

Getting user location and setting it to state using redux

Getting the current location using Google Maps API flutter

Google Maps Android, detect user interation in a location aware map

How do I track the location of a user throughout the day in Google Maps?

Swift Google Maps GMS Marker not sticking on user location

Displaying current user location in google maps only once

Stop Map Updating on User Location Update - Google Maps iOS SDK

JavaScript Google Maps API - Center on User's Location not loading map

How to show user location on Google Maps iOS SDK

Camera does not follow user current location in Google Maps