-1

I'm quite a beginner to android and I'm trying out my best to learn android. I'm trying to create an android application that identify the user location using google maps. However I was able to identify user's location, but not as I expected.

As in the following picture it shows a default location. Once I click the button in top left corner, the map shows my location.

enter image description here

I would like to know my location straight away, without clicking a button. Also I want to know the user location and store it in a string, not in longitude and latitude values. Any Help?

Code:

package com.example.lalinda.googlemap1;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

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

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);
    }
}
ONE_FE
  • 968
  • 3
  • 19
  • 39

1 Answers1

1

Google maps uses user's lastKnownLocation for location, If the lastknownLocation is unknown it takes time to fetch location through different provider say GPS or Network. I would suggest to use lastKnownLocation as base location and update it with LocationListener.

       @Override
       public void onMapReady(GoogleMap googleMap) { 
       if (ActivityCompat.checkSelfPermission
                (this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                &&
                ActivityCompat.checkSelfPermission
                        (this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            }, 1);

        }
        else {

            // enable location buttons
            googleMap.setMyLocationEnabled(true);
            googleMap.getUiSettings().setMyLocationButtonEnabled(true);

            // fetch last location if any from provider - GPS.
            final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            final Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            //if last known location is not available
            if (loc == null) {

                final LocationListener locationListener = new LocationListener() {
                    @Override
                    public void onLocationChanged(final Location location) {
                        clearMap(googleMap); // clear map for every new location to update your marker unless `n` number of markers will form.
                        // getting location of user
                        final double latitude = location.getLatitude();
                        final double longitude = location.getLongitude();
                        final LatLng userCurrentLocation = new LatLng(latitude, longitude);
                        //focus added here **edited**
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userCurrentLocation, 14));

                        googleMap.addMarker(new MarkerOptions()
                       .position(userCurrentLocation)
                       .draggable(true)
       .icon(BitmapDescriptorFactory.fromResource(R.drawable.your_marker_icon_from_deawable)));
                        //do something with Lat and Lng, Parse to String if u want or set marker.

                    }

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

                    @Override
                    public void onProviderEnabled(String provider) {
                        //when user enables the GPS setting, this method is triggered.
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                        //when no provider is available in this case GPS provider, trigger your gpsDialog here.
                    }
                };

                //update location every 10sec in 500m radius with both provider GPS and Network.

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10*1000, 500, locationListener);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 500, locationListener);
            }
            else {
                //do something with last known location.
                // getting location of user
                final double latitude = loc.getLatitude();
                final double longitude = loc.getLongitude();
                final LatLng userCurrentLocation = new LatLng(latitude, longitude);

                //focus added here **edited**
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userCurrentLocation, 14));

                googleMap.addMarker(new MarkerOptions()
                .position(userCurrentLocation)
                .draggable(true)
       .icon(BitmapDescriptorFactory.fromResource(R.drawable.your_marker_icon_from_deawable)));
            }
           }
        }

Permission handling:

     @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {

        case 1:
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED){
                //do something
            }
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

This example is just for demonstration (example purpose) and I did not optimized my code by using methods. please edit in future.

W4R10CK
  • 5,502
  • 2
  • 19
  • 30
  • cannot resolve method 'clearMap' and 'your_marker_icon_from_deawable'. What classes should I include? – ONE_FE Sep 22 '16 at 17:30
  • use `googleMap.clear();` instead of `clearMap()`(Its a function and i forgot to add in code), and 'your_marker_icon_from_deawable' means add any icon from drawable folder to show as marker like this `R.drawable.name_of_your_image` – W4R10CK Sep 22 '16 at 17:35
  • your code works fine, but still I have to click the button in top left corner. – ONE_FE Sep 22 '16 at 17:51
  • check now. I edited again. go to line `focus added here` – W4R10CK Sep 22 '16 at 17:57
  • thanks, this is what I needed. Can you help me to get the current location as a string? – ONE_FE Sep 22 '16 at 18:03
  • Appriciated, to change to `LatLng` parse the double value to string. `String lat = Double.toString(latitude); String lon = Double.toString(longitude);` Or `String lat = Double.toString(location.getLatitude()); String lon = Double.toString(location.getLongitude());` – W4R10CK Sep 22 '16 at 18:19
  • I menat how to get the street name and city of user location or is there any way to convert longitude and latitude values? – ONE_FE Sep 23 '16 at 17:33
  • I found the solution here http://stackoverflow.com/questions/9409195/how-to-get-complete-address-from-latitude-and-longitude – ONE_FE Sep 23 '16 at 17:45
  • One more question, Do I need to turn on the Wifi on my mobile when I'm using this? Seems like I have to turn on the wifi of my mobile. – ONE_FE Sep 24 '16 at 16:43