im creating a small mobile app that should allow me to find my current location on google maps.
I had it working earlier i was able to click on one of the buttons and it zoomed into my current location.
Now for some reason im getting the following error
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference
it points towards line 53 of my code which is posted below:
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.getUiSettings().setZoomControlsEnabled(true);
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
double myLongitude = myLocation.getLongitude();
double myLatitude = myLocation.getLatitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(myLongitude, myLatitude);
Marker me = mMap.addMarker(new MarkerOptions()
.position(new LatLng(myLatitude, myLongitude))
.title("Im here!")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.people))
);
// Zoom into my current location
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(myLatitude, myLongitude), 15.0f));
}
}
Line 53 refers to : double myLongitude = myLocation.getLongitude();
No idea why this is happening
Any help will be appreciated!
locationManager.getLastKnownLocation(provider) can return null, as described in the documentation here.
In your code, you're getting a NullPointerException because in line 53, myLocation is null.
Related
i create one map in this i show one marker on current location its working fine
when location turn on already but when Activity is on and i turn On location it does not show any marker i want to show marker when location is on
any help?..
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
getCurrentLocation();
// latLngCurrentLocation is my current location which is update using getCurrentLocation() method.
if(latLngCurrentLocation != null) {
// add marker on current location
markerCurrent = mMap.addMarker(new MarkerOptions()
.position(latLngCurrentLocation)
.draggable(true)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.title("Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrentLocation));
mMap.animateCamera(CameraUpdateFactory.zoomTo(8));
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setOnMarkerDragListener(this);
}
}
Through GpsTracker class or googleClient api you can get latitude and longtitude and then get it as gpstracker.getlatitude and getlongtitude and set this values to global variables and access it whereever you want.
You will get location in onLocationChanged(Location location) once your position is changed. You will get Latitude and Longitude in location object, so you can set your marker into onLocationChanged(Location location) method
#Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null)
{
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
OR if you want to refresh your marker once GPS turns on then you can use BroadcastReceiver. BroadcastReciever triggers when GPS turns/off so you can check whether GPS is turned on or off, You can find example in following link, Broadcast receiver for GPS
I'm trying to develop android app with google maps, but I have error -
NullPointerException: CameraUpdateFactory is not initialized
GoogleMap mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 0, this);
double lat = Double.parseDouble("xx.xxxxxx");
double log = Double.parseDouble("yy.yyyyyy");
LatLng currentPosition = new LatLng(lat, log);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition,16));
mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + lat + "Lng:" + log));
Please help me.
Thanks in advance.
You need implement
OnMapReadyCallback
and then override
onMapReady
This is to make sure that your map has been properly set and ready for any camera updates.
public class YourMapFragment extends Fragment implements OnMapReadyCallback {
...
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition,16));
mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + lat + "Lng:" + log));
}
...
}
I have implemented the Google Maps API v2 in my Android app. I add a marker and zoom to level 14 when I open the activity containing the map fragment.
Here is how I add/update the marker:
private void updateMarker() {
if(marker != null){
marker.remove();
}
LatLng latlng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
marker = mMap.addMarker(new MarkerOptions().position(latlng).title(username));
marker.setIcon((BitmapDescriptorFactory.fromResource(R.drawable.marker)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(zoom), 2000, null);
}
It works correctly in debug via Android Studio, using a Nexus 5 with the latest Android installed. The problem is when I run a release build. The marker is added in the correct place, the zoom animation works correctly, zooming to the correct level. But it doesn't move to the marker I added.
Use this
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom));
Or
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom), 2000, null);
Don't call both method right after each other.
you should pass the result value of CameraUpdateFactory.newLatLngZoom(latlng, zoom) to animateCamera which returns a CameraUpdate that moves the center of the screen to a latitude and longitude specified by a LatLng object, and moves to the given zoom level. You can read more about it here
Implement GoogleApiClient.ConnectionCallbacks and override onConnected method as follows:
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mGMLastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGMGoogleApiClient);
try {
// Get LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled)
{
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
//You can still do this if you like, you might get lucky
mGMLastKnownLocation = locationManager.getLastKnownLocation(provider);
if (mGMLastKnownLocation != null) {
//place marker at current position
mMap.clear();
// Get latitude of the current location
double latitude = mGMLastKnownLocation.getLatitude();
// Get longitude of the current location
double longitude = mGMLastKnownLocation.getLongitude();
// Create a LatLng object for the current location
latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(7));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mCurrLocation = mMap.addMarker(markerOptions);
} else {
mGMLocationRequest = new LocationRequest();
mGMLocationRequest.setInterval(5000); //5 seconds
mGMLocationRequest.setFastestInterval(3000); //3 seconds
mGMLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGMGoogleApiClient, mGMLocationRequest, this);
}
} else {
//prompt user to enable location
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
}
} catch (Exception e) {
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
}
Also, implement LocationListener and override the onLocationChanged method as follows:
#Override
public void onLocationChanged(Location location) {
//remove previous current location marker and add new one at current position
if (mCurrLocation != null) {
mCurrLocation.remove();
}
double latitude = location.getLatitude();
double longitude = location.getLongitude();
latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(latitude, longitude)).title("Position").snippet("I am here").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mCurrLocation = mMap.addMarker(markerOptions);
Toast.makeText(this, "Location Changed", Toast.LENGTH_SHORT).show();
//If you only need one location, unregister the listener
LocationServices.FusedLocationApi.removeLocationUpdates(mGMGoogleApiClient, this);
}
I hope it helps!!
I need to display users current locations using gps. At startup it displays some random location in sea and when i'll click to gps icon it displays my current location (white circle with optic icon).
How can I do to display that on startup? I'm new at android/java so feel free to correct me anything.
my code is:
public class MainMapsActivity extends FragmentActivity implements android.location.LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_maps);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
}
Create a data member of Location class.
public static Location mLocation;
use OnMyLocationChangeListener on Map
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mLocation = location;
displayCurrentLocation();
}
});
public void displayCurrentLocation(){
CameraPosition cameraPosition = new CameraPosition.Builder().
target(new LatLng(mLocation.getLatitude(), mLocation.getLongitude())).
tilt(60).
zoom(15).
bearing(0).
build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
hope it will works.
You can achieve this in two ways
Run a service (background operation) and get current latitude and longitude at the app starting itself , before coming to the targeted screen
Expose methods in service which you can access from Activity
Show users current location from the service method input
Or else implement a listener which will every time update the users current location
You can refer the following Example 1 and Example 2
I'm trying to run a method when the current location changes. It calculates the distance each time the current location changes and then displays it in a textview.
public GoogleMap googleMap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// final MediaPlayer mPlayer = MediaPlayer.create(FakeCallScreen.this, R.raw.mysoundfile);
// 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, (LocationListener) this);
Location marker = new Location("");
marker.setLatitude(lat);
marker.setLongitude(long1);
if(select==false){
TextView t = (TextView) findViewById(R.id.tv_location);
t.setText("Please select a marker" + lat + long1);
Toast.makeText(this, "not selected", Toast.LENGTH_LONG).show();
} else if(select==true){
float distanceBetweenPoints = location.distanceTo(marker);
TextView t = (TextView) findViewById(R.id.tv_location);
t.setText("Distance to station is "+ distanceBetweenPoints);
Toast.makeText(this, "Distance is "+distanceBetweenPoints, Toast.LENGTH_LONG).show();
if(distanceBetweenPoints<1000){
//do something
}
}
}
And the onInfoWindow Code
googleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener(){
public void onInfoWindowClick(Marker marker) {
LatLng clickedMarkerLatLng = marker.getPosition();
lat = clickedMarkerLatLng.latitude;
long1 = clickedMarkerLatLng.longitude;
String name = marker.getTitle();
select=true;
TextView t = (TextView) findViewById(R.id.tv_location);
t.setText("Location of "+ name +" is "+ lat + " by " + long1);
How would I go about making this run when the location changes?
You should declare your class as
public MyClassName extends Activity implements LocationListener
And then put your code in onLocationChanged