Finding a Location on Google Map

I am trying to find my location on Google Map. My code is here. I started the app on my phone, but unfortunately it stopped. Any ideas on what might be the problem? Thank.

  public class MainActivity extends Activity implements LocationListener {

    private LatLng loc ;
    private LocationManager locationManager;
    private String provider;

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

      locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

      Criteria criteria = new Criteria();
      provider = locationManager.getBestProvider(criteria, false);
      Location location = locationManager.getLastKnownLocation(provider);

      if (location != null) {
        onLocationChanged(location);
      }

      GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
      map.addMarker(new MarkerOptions().position(loc).title("Istanbul"));
      map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
      map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
    }

    @Override
    public void onLocationChanged(Location location) {
        double lat = (double) (location.getLatitude());
        double lng = (double) (location.getLongitude());
        loc = new LatLng(lat,lng);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }

    @Override
    protected void onPause() {

        super.onPause();
        locationManager.removeUpdates(this);
    }
  }

      

0


source to share


3 answers


public class MainActivity extends FragmentActivity implements LocationListener {

GoogleMap googleMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    }else { // Google Play Services are available

        // 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){
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, this);
    }
}
@Override
public void onLocationChanged(Location location) {

    TextView tvLocation = (TextView) findViewById(R.id.tv_location);

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

    // Showing the current location in Google Map
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    // Zoom in the Google Map
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    // Setting latitude and longitude in the TextView tv_location
    tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
}

      



Download here

+2


source


// try this
**main.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    android:orientation="vertical">

    <fragment
        android:id="@+id/maps"
        android:name="pl.mg6.android.maps.extensions.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

public class MyActivity extends FragmentActivity {


    public static LocationManager mlocManager;
    public static LocationListner mListner;
    GoogleMap map;

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

        map = getMapView();
        map.setMyLocationEnabled(true);

        try {
            mlocManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
            mListner = new LocationListner();
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    try {
                        try {
                            mlocManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, mListner);
                        } catch (Throwable e) {
                            e.printStackTrace();
                        }

                        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListner);
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    try {
                        mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mListner);
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }

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

    }

    public GoogleMap getMapView() {
        FragmentManager fm = getSupportFragmentManager();
        SupportMapFragment f = (SupportMapFragment) fm.findFragmentById(R.id.maps);

        // Getting GoogleMap object from the fragment
        return f.getExtendedMap();
    }

    public void setMapMarker(LatLng loc){
        map.addMarker(new MarkerOptions().position(loc).title("Istanbul"));
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
        map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
    }


    class LocationListner implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            setMapMarker(new LatLng(location.getLatitude(),location.getLongitude()));
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

    }
}

      



+1


source


In this line:

map.addMarker(new MarkerOptions().position(loc).title("Istanbul"));

      

loc is null

Also, you shouldn't call onLocationChanged () directly, it's a callback. The whole process is event driven, that is, when the GPS or the network gives you the location that this method triggers.

+1


source







All Articles