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));
}
...
}
Related
I want to have my markers so that when clicked upon they will open a new activity that will display a list of locations from my SQLite database. If someone could show me the code to add to my markers to open activity for that particular marker it would be great.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private static final LatLng Kerry = new LatLng(52.212636048, -9.812321255);
private static final LatLng Limerick = new LatLng(52.653131468516236, -8.632676814862014);
private static final LatLng Clare = new LatLng(52.887135246510255, -9.063511195184182);
private static final LatLng Galway = new LatLng(53.27726074573369, -9.065918590802234);
private static final LatLng Mayo = new LatLng(53.88316732870579, -9.42381429549789);
private static final LatLng Sligo = new LatLng(54.20195132022076, -8.59144563453587);
private static final LatLng Leitrim = new LatLng(54.340224636620334, -8.037324331196);
private static final LatLng Donegal = new LatLng(55.013236950319495, -8.226710776524827);
private static final LatLng Cork = new LatLng(51.85961876429461, -8.49543099484229);
private Marker mKerry;
private Marker mLimerick;
private Marker mClare;
private Marker mGalway;
private Marker mMayo;
private Marker mSligo;
private Marker mLeitrim;
private Marker mDonegal;
private Marker mCork;
private LocationManager locationManager;
private 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);
}
/**
* 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;
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(#NonNull Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
///array list for markers
List<Marker> markerList = new ArrayList<>();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mKerry = googleMap.addMarker(new MarkerOptions()
.position(Kerry)
.title("Kerry")
.snippet("Confirmed cases past 14 days: 44"));
mKerry.setTag(0);
markerList.add(mKerry);
mCork = googleMap.addMarker(new MarkerOptions()
.position(Cork)
.title("Cork")
.snippet("Confirmed cases past 14 days: 191")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mCork.setTag(0);
markerList.add(mCork);
mLimerick = googleMap.addMarker(new MarkerOptions()
.position(Limerick)
.title("Limerick")
.snippet("Confirmed cases past 14 days: 270")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mLimerick.setTag(0);
markerList.add(mLimerick);
mClare = googleMap.addMarker(new MarkerOptions()
.position(Clare)
.title("Clare")
.snippet("Confirmed cases past 14 days: 39")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mClare.setTag(0);
markerList.add(mClare);
mGalway = googleMap.addMarker(new MarkerOptions()
.position(Galway)
.title("Galway")
.snippet("Confirmed cases past 14 days: 143")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mGalway.setTag(0);
markerList.add(mGalway);
mMayo = googleMap.addMarker(new MarkerOptions()
.position(Mayo)
.title("Mayo")
.snippet("Confirmed cases past 14 days: 98")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mMayo.setTag(0);
markerList.add(mMayo);
mSligo = googleMap.addMarker(new MarkerOptions()
.position(Sligo)
.title("Sligo")
.snippet("Confirmed cases past 14 days: 20")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mSligo.setTag(0);
markerList.add(mSligo);
mLeitrim = googleMap.addMarker(new MarkerOptions()
.position(Leitrim)
.title("Leitrim")
.snippet("Confirmed cases past 14 days: 5")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mLeitrim.setTag(0);
markerList.add(mLeitrim);
mDonegal = googleMap.addMarker(new MarkerOptions()
.position(Donegal)
.title("Donegal")
.snippet("Confirmed cases past 14 days: 351")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mDonegal.setTag(0);
markerList.add(mDonegal);
for (Marker m : markerList) {
LatLng latLng = new LatLng(m.getPosition().latitude, m.getPosition().longitude);
mMap.addMarker(new MarkerOptions().position(latLng));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 7));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 7));
}
}
}
'''
I think it's something like:
mMap.setOnInfoWindowClickListener(marker -> {
Intent intent = new Intent(this, SomeActivity.class);
intent.putExtra("Key", marker.getTag().toString());
startActivity(intent);
});
Somewhere in SomeActivity, to retrieve the string tag of the marker:
String value = getIntent().getParcelableExtra("Key");
I am creating an Android application and have set up a standard Google Maps activity. The application so far just displays the location of the user. The camera is set to focus on the users location initally. I am running into a problem when I try to scroll or drag to a new position on the emulator. I drag and once i lift up the mouse the camera resets to its original position.
onMapReady Code
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mMap.clear();
LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(currentLocation).title("You Are Here"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(currentLocation)
.zoom(25)
.bearing(200)
.tilt(90)
.build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (listAddresses.get(0).getAdminArea() != null) {
String address += listAddresses.get(0).getAdminArea();
}
Toast.makeText(MapsActivity.this, address, Toast.LENGTH_SHORT).show();
Log.i("Address", address);
} catch (Exception e) {
e.printStackTrace();
}
}
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mMap.clear();
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(userLocation)
.zoom(25)
.bearing(0)
.tilt(90)
.build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
This is the code I have to display a marker at current location. I also have code to get AdminArea of current location.
I believe the problem is that my code is runnning constantly so that when I attempt to drag the screen, it just resets to where the camera was originally set. The same occurs for the Toast displaying the current location. This does not update wth new information when i change new location
You are correct. You are setting the camera location in your onLocationChange method, which fires constantly (the user's location doesn't have to change much for this method to fire). So, by setting the camera location to the currentLocation, it will keep scrolling the map. Try commenting that out and see what happens.
public void onLocationChanged(Location location) {
mMap.clear();
LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(currentLocation).title("You Are Here"));
//CameraPosition cameraPosition = new CameraPosition.Builder()
// .target(currentLocation)
// .zoom(25)
// .bearing(200)
// .tilt(90)
// .build();
//mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
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.
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