I am a beginner in Android programming. I already looked at similar questions and answers but I still can't figure out why this doesn't work. When I try this on the emulator and click a location, no marker appears. This is my code:
Edit: I get a marker when I click now with the following code. It only gives me a runtime exception (NullPointer exception) when I click the map the second time:
public class MapViewFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map_view, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
Context context = getActivity().getApplicationContext();
final LocationsDB locationsDB = new LocationsDB(context);
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng point) {
// Drawing marker on the map
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point);
markerOptions.title(point.latitude + " : " + point.longitude);
googleMap.clear();
googleMap.animateCamera(CameraUpdateFactory.newLatLng(point));
googleMap.addMarker(markerOptions);
// Create location object
Location location = new Location(point.latitude, point.longitude);
// add location to SQLite database
locationsDB.insert(location);
}
});
}
});
return rootView;
}
}
Log messages:
7-20 07:33:00.076 5359-5359/? W/RcsService: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.rcs.service.service.a.a()' on a null object reference
at com.google.android.rcs.service.e.b(SourceFile:43)
at com.google.android.rcs.service.service.JibeService.onDestroy(SourceFile:162)
at android.app.ActivityThread.handleStopService(ActivityThread.java:3569)
at android.app.ActivityThread.-wrap26(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1703)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
07-20 07:33:00.079 5359-5359/? E/ActivityThread: Service com.google.android.rcs.service.service.JibeService has leaked IntentReceiver com.google.android.rcs.service.provisioning.RcsReconfigurationSmsReceiver#741339 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Service com.google.android.rcs.service.service.JibeService has leaked IntentReceiver com.google.android.rcs.service.provisioning.RcsReconfigurationSmsReceiver#741339 that was originally registered here. Are you missing a call to unregisterReceiver()?
at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:1310)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:1091)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1397)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1370)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1358)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:603)
at com.google.android.rcs.service.provisioning.RcsSmsReceiver.a(SourceFile:12)
at com.google.android.rcs.service.h.g(SourceFile:230)
at com.google.android.rcs.service.h.<init>(SourceFile:212)
at com.google.android.rcs.service.service.a.<init>(SourceFile:13)
at com.google.android.rcs.service.e.a(SourceFile:32)
at com.google.android.rcs.service.service.JibeService.d(SourceFile:145)
at com.google.android.rcs.service.service.JibeService.onCreate(SourceFile:91)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3404)
at android.app.ActivityThread.-wrap4(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Look here in Google Maps example
https://developers.google.com/maps/documentation/android-api/marker
If you want to add marker when clicking you can also look here:
http://wptrafficanalyzer.in/blog/adding-marker-on-touched-location-of-google-maps-using-android-api-v2-with-supportmapfragment/
The concept is to do like the folowing code:
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
});
//Show Marker on a Location
googleMap.addMarker(new MarkerOptions().position(TIMES_SQUARE));
//Change Default Color of Marker
googleMap.addMarker(new MarkerOptions()
.position(BROOKLYN_BRIDGE)
.title("First Pit Stop")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
//Replace Default Marker Icon with Custom Image
googleMap.addMarker(new MarkerOptions()
.position(WALL_STREET)
.title("Wrong Turn!")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.my_flag)));
Get the users current position latitude and longitude
LatLng latLng = new LatLng(lat, lng);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
mMap.clear();
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
markerOptions.getPosition();
mCurrLocationMarker = mMap.addMarker(markerOptions);
try in this way.
Pass your latitude and longitude values
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
// adding marker
googleMap.addMarker(marker);
This code in MapsActivity works for me :
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
public void centreMapOnLocation(Location location, String title){
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,12));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centreMapOnLocation(lastKnownLocation,"Your Location");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
// 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.setOnMapLongClickListener(this);
Intent intent = getIntent();
if (intent.getIntExtra("Place Number",0) == 0 ){
// Zoom into users location
locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
centreMapOnLocation(location,"Your Location");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centreMapOnLocation(lastKnownLocation,"Your Location");
} else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
} else {
Location placeLocation = new Location(LocationManager.GPS_PROVIDER);
placeLocation.setLatitude(MainActivity.location.get(intent.getIntExtra("Place Number",0)).latitude);
placeLocation.setLongitude(MainActivity.location.get(intent.getIntExtra("Place Number",0)).longitude);
centreMapOnLocation(placeLocation,MainActivity.places.get(intent.getIntExtra("Place Number",0)));
}
}
#Override
public void onMapLongClick(LatLng latLng) {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
String adress ="";
try {
List<Address> listaddress = geocoder.getFromLocation(latLng.latitude,latLng.longitude,1);
if (listaddress != null && listaddress.size()>0){
if (listaddress.get(0).getThoroughfare() != null){
if (listaddress.get(0).getSubThoroughfare() != null){
adress += listaddress.get(0).getSubThoroughfare() + "";
}
adress += listaddress.get(0).getThoroughfare();
}
}
}catch (Exception e){
e.printStackTrace();
}
mMap.addMarker(new MarkerOptions().position(latLng).title(adress));
MainActivity.places.add(adress);
MainActivity.location.add(latLng);
MainActivity.arrayAdapter.notifyDataSetChanged();
Toast.makeText(this, "Location Saved..!", Toast.LENGTH_SHORT).show();
}
}
Related
I am using the following method to move the camera:
private void moveCamera(LatLng latLng, float zoom, GoogleMap map) {
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
When I am using it inside OnMapReady like this:
private void initMapHome() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.harta_adauga_adresa_acasa);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady: map is readyyyyyyyyyyyyyyyyyyy");
gmap = googleMap;
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
gmap.setMyLocationEnabled(true);
gmap.getUiSettings().setMyLocationButtonEnabled(true);
gmap.getUiSettings().setCompassEnabled(true);
gmap.getUiSettings().setMapToolbarEnabled(false);
gmap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
});
gmap.setOnMapClickListener(latLng -> {
gmap.clear();
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title(adresa);
gmap.addMarker(options).showInfoWindow();
});
moveCamera(pozitie_curenta, DEFAULT_ZOOM, gmap);
}
});
}
The camera animates in a nice manner to the selected position, the pozitie_curenta LatLng created somewhere else in my code. Now, I have a AutoCompleteTextView that returns the places (I am using the one created by Mukesh Solanki from github), and I am looking to move the camera on the selected place from the AutoCompleteTextView. I have the following code:
adresa_home.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Place place = (Place) parent.getItemAtPosition(position);
adresa_home.setText(place.getDescription());
placesApi.fetchPlaceDetails(place.getId(), new OnPlacesDetailsListener() {
#Override
public void onPlaceDetailsFetched(PlaceDetails placeDetails) {
latitudine_acasa = placeDetails.getLat();
longitudine_acasa = placeDetails.getLng();
updateHartaHome(latitudine_acasa, longitudine_acasa, place.getDescription());
}
#Override
public void onError(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
}
);
}
});
The place is fetched correctly, and I get the latitude and longitude correctly. The method updateHartaHome is looking like this:
private void updateHartaHome(double lat, double lng, String title) {
acasa = new LatLng(lat, lng);
MarkerOptions options = new MarkerOptions()
.position(pozitie_curenta)
.title(title);
gmap.addMarker(options).showInfoWindow();
moveCamera(acasa, DEFAULT_ZOOM, null, gmap);
}
Debugging the code I've come to the conclusion that the problem it's with the moveCamera from the updateHartaHome which is never called. Setting a breakpoint on the line gmap.addMarker(options).showInfoWindow(); gets me the following:
So, eveything looks fine, but the map doesn't update and, it also doesn't add the marker. Setting the breakpoint on the moveCamera line, it never gets accesed. Any help would be appreciated, I've been going mad over this issue. Thanks!
Please try this once inside your onMapReady method
CameraPosition cameraPosition = CameraPosition.builder()
.target(new LatLng(placeLatitude, placeLongitude))
.zoom(16)
.bearing(0)
.tilt(45)
.build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
where mGoogleMap is defined as
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
if you want to add Marker do this before moving the camera
mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(placeLatitude, placeLongitude)));
EDIT:
If you want to click on the map and move the camera
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
mGoogleMap.clear();
mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(latLng.latitude, latLng.longitude)));
CameraPosition cameraPosition = CameraPosition.builder()
.target(new LatLng(latLng.latitude, latLng.longitude))
.zoom(16)
.bearing(0)
.tilt(45)
.build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
here is my Updated code for real time location activity.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private Marker currentLocationMaker;
private LatLng currentLocationLatLong;
private DatabaseReference mDatabase;
#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);
startGettingLocations();
mDatabase = FirebaseDatabase.getInstance().getReference();
getMarkers();
}
/**
* 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 recife = new LatLng(-8.065638, -34.891130);
mMap.addMarker(new MarkerOptions().position(recife).title("Related Searches"));
CameraPosition cameraPosition = new CameraPosition.Builder().zoom(15).target(recife).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
public void onLocationChanged(Location location) {
if (currentLocationMaker != null) {
currentLocationMaker.remove();
}
//Add marker
currentLocationLatLong = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLocationLatLong);
markerOptions.title("My Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentLocationMaker = mMap.addMarker(markerOptions);
//Move to new location
CameraPosition cameraPosition = new CameraPosition.Builder().zoom(15).target(currentLocationLatLong).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LocationData locationData = new LocationData(location.getLatitude(), location.getLongitude());
mDatabase.child("location").child(String.valueOf(new Date().getTime())).setValue(locationData);
Toast.makeText(this, "Updated Location", Toast.LENGTH_SHORT).show();
getMarkers();
}
private ArrayList findUnAskedPermissions(ArrayList<String> wanted) {
ArrayList result = new ArrayList();
for (String perm : wanted) {
if (!hasPermission(perm)) {
result.add(perm);
}
}
return result;
}
private boolean hasPermission(String permission) {
if (canAskPermission()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
}
}
return true;
}
private boolean canAskPermission() {
return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS disabled!");
alertDialog.setMessage("Enable GPS?");
alertDialog.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Not", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private void startGettingLocations() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetwork = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean canGetLocation = true;
int ALL_PERMISSIONS_RESULT = 101;
long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;// Distance in meters
long MIN_TIME_BW_UPDATES = 1000 * 10;// Time in milliseconds
ArrayList<String> permissions = new ArrayList<>();
ArrayList<String> permissionsToRequest;
permissions.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
permissions.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
permissionsToRequest = findUnAskedPermissions(permissions);
//Check if GPS and Network are on, if not asks the user to turn on
if (!isGPS && !isNetwork) {
showSettingsAlert();
} else {
// check permissions
// check permissions for later versions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (permissionsToRequest.size() > 0) {
requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]),
ALL_PERMISSIONS_RESULT);
canGetLocation = false;
}
}
}
//Checks if FINE LOCATION and COARSE Location were granted
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
return;
}
//Starts requesting location updates
if (canGetLocation) {
if (isGPS) {
lm.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
} else if (isNetwork) {
// from Network Provider
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
} else {
Toast.makeText(this, "Unable to get location", Toast.LENGTH_SHORT).show();
}
}
private void getMarkers(){
mDatabase.child("location").addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get map of users in datasnapshot
if (dataSnapshot.getValue() != null)
getAllLocations((Map<String,Object>) dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
}
private void getAllLocations(Map<String,Object> locations) {
for (Map.Entry<String, Object> entry : locations.entrySet()){
Date newDate = new Date(Long.valueOf(entry.getKey()));
Map singleLocation = (Map) entry.getValue();
LatLng latLng = new LatLng((double) singleLocation.get("latitude"), (double) singleLocation.get("longitude"));
addGreenMarker(newDate, latLng);
}
}
private void addGreenMarker(Date newDate, LatLng latLng) {
SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(dt.format(newDate));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mMap.addMarker(markerOptions);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Here is my Logcat Stack trace
Process: com.softtech.aqeel.childsequrity, PID: 3739
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double
at com.softtech.aqeel.childsequrity.MapsActivity.getAllLocations(MapsActivity.java:247)
at com.softtech.aqeel.childsequrity.MapsActivity.access$000(MapsActivity.java:39)
at com.softtech.aqeel.childsequrity.MapsActivity$3.onDataChange(MapsActivity.java:228)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database##16.0.4:183)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
i am trying to trace real time location of an android device for my project but at this point its giving me these exceptions. my app starts and when i open Maps Activity, map shows me for a little bit and then app automatically stops.
Use below code for creating object and casting.
LatLng latLng = new LatLng((double) singleLocation.get("latitude"), (double) singleLocation.get("longitude"));
use doubleValue() from Long
Change
LatLng latLng = new LatLng((Double) singleLocation.get("latitude"), (Double) singleLocation.get("longitude"));
to
LatLng latLng = new LatLng((Long) singleLocation.get("latitude").doubleValue(), (Long) singleLocation.get("longitude").doubleValue());
Get the latitude and longitude from singleLocation and convert it by this way and insert into the LatLng.
you must have to first convert Object value into String.
Like below
Map singleLocation = (Map) entry.getValue();
String latitude = String.valueOf(singleLocation.get("latitude"));
String longitude = String.valueOf(singleLocation.get("longitude"));
Double doublelat = Double.parseDouble(latitude);
Double doublelong = Double.parseDouble(longitude);
LatLng latlng = new LatLng(doublelat, doublelong);
You won't get any exception.
I'm trying to set the marker on my current location, so I tried to convert a Location to a LatLng class:
LatLng mCurrentPlace= new LatLng(location.getLatitude(),location.getLongitude());
Then I recalled the addMarker method:
mMap.addMarker(new MarkerOptions()
.title(getString(R.string.default_info_title))
.position(mCurrentPlace)
.snippet(getString(R.string.default_info_snippet)))
But Launching the application by "Run", it arrested.
Where am I goning wrong?
Thanks.
public void moveMap(GoogleMap gMap, double latitude, double longitude) {
Log.v(TAG, "mapMoved: " + gMap);
LatLng latlng = new LatLng(latitude, longitude);
CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(latlng, 6);
gMap.addMarker(new MarkerOptions().position(latlng));
gMap.moveCamera(cu);
}
Call this method where you want location and marker and in on mapasync callback method.
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(context);
gMap = googleMap;
gMap.getUiSettings().setMapToolbarEnabled(false);
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if(items.get(getLayoutPosition())!=null )
moveMap(gMap,latitude, longitude);
}
public void initializeMapView() {
if (mapView != null) {
// Initialise the MapView
mapView.onCreate(null);
// Set the map ready callback to receive the GoogleMap object
mapView.getMapAsync(this);
}
}
Override onMapReadyCallback method and do this.
Call initializeMapView method in onCreate() or In adapter onBindViewHolder
Try using the LatLng.Builder
LatLng.Builder builder = LatLng.newBuilder();
builder.setLatitude(location.getLatitude());
builder.setLongitude(location.getLongitude());
latLng = builder.build();
MAP Activity
public class MapsActivity2 extends FragmentActivity implements
OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener {
private GoogleMap mMap;
LatLng loc;
Location location;
private double currentLatitude = 0;
private double currentLongitude = 0;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
// 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(Context.LOCATION_SERVICE);
}
/**
* 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 atLnmove 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.newLg(sydney));
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;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(MapsActivity2.this);
}
public double getLatitude(){
if(location != null){
currentLatitude = location.getLatitude();
}
// return latitude
return currentLatitude;
}
public double getLongitude(){
if(location != null){
currentLongitude = location.getLongitude();
}
// return longitude
return currentLongitude;
}
#Override
public boolean onMyLocationButtonClick() {
location=mMap.getMyLocation();
currentLatitude=getLatitude();
currentLongitude=getLongitude();
LatLng currentLocation = new LatLng(currentLatitude, currentLongitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
mMap.addMarker(new MarkerOptions().position(currentLocation).title("Marker in Current Location"));
return false;
}
}
Resource XML
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.atziant.parashar.gmapsapi.MapsActivity2" />
I use this code in order to instantiate the Google Map :
map = ((MapFragment) getChildFragmentManager().findFragmentById(R.id.map));
mMap = map.getMap();
mMap.setMyLocationEnabled(true);
This use to work fine with many devices such as nexus 5 and Samsung Galaxy S6 but I have a tablet (SONY XPERIA Z3) and when I try to navigate to this Fragment the app crash with the logcat:
FATAL EXCEPTION: main
Process: com.example.veriah.loneworker, PID: 20646
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean)' on a null object reference
Also I already have activated locations to this Tablet.
Is anyone Know why this happening?
Thank you in advance
Try this solution :
map.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
googleMap.setMyLocationEnabled(true);
}
});
you have to use onMapReady and for marshmallow you have to check permissions individually -->
public LocationManager locationmaneger;
locationmaneger = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
lon = location.getLongitude();
lat = location.getLatitude();
System.out.println(lon + " " + lat);
// LatLng mycurrentposition = new LatLng(lat, lon);
//mMap.setMyLocationEnabled(true);
mMap.clear();
int i;
mMap.addMarker(new MarkerOptions()
.title("My Location")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.myloc))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(lat, lon)))
.setDraggable(true);
//camera
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
/* CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
mMap.animateCamera(cameraUpdate);*/
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
.bearing(rotate) // Sets the orientation of the camera to east
.tilt(80) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if(rotate == 150 )
{
rotate = 200;
}
else{
rotate = 150;
}
locationmaneger.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case 10:
if(grantResults.length > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
locationmaneger.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
locationmaneger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
return;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
System.out.println("i am on mapready");
if(isNetworkConnected())
{
mMap = googleMap;
if (Build.VERSION.SDK_INT >= 23) {
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_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.INTERNET},10);
return;
}
}else{
System.out.println(lon + " " + lat);
locationmaneger.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 120000 , locationListener);
locationmaneger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 120000 , locationListener);
}
}
I am developing an application in which I want to display current location using marker in my map. I am using Google Map v2. Here I can display Map and marker when GPS is off ,but not visible any marker on map when GPS on. My requirement is display marker on map with current position
I tried like this,
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//locationManger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
this);
ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>)
getIntent().getSerializableExtra("arrayList");
if(location!=null){
double latitude = location.getLatitude();
double langitude = location.getLongitude();
myPosition = new LatLng(latitude, langitude);
CameraPosition position= new CameraPosition.Builder().
target(myPosition).zoom(17).bearing(19).tilt(30).build();
//_googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
_googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
_googleMap.addMarker(new
MarkerOptions().position(myPosition).title("start"));
}
Use below code it worked for me:
#Override
public void onLocationChanged(Location location) {
map.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
map.addMarker(mp);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
Try this,it is showing current location:
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// to set current location
googleMap.setMyLocationEnabled(true);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
Try this:-
private void initMap() {
if (googleMap != null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// to set current location
googleMap.setMyLocationEnabled(true);
Marker pos_Marker = googleMap.addMarker(new MarkerOptions().position(starting).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_laumcher)).title("Starting Location").draggable(false));
pos_Marker.showInfoWindow();
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(START_locationpoint, 10));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15),2000, null);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
Use this. It works for me.
#Override
public void onLocationChanged(Location location) {
map.clear();
mp1 = new MarkerOptions();
mp1.position(new LatLng(location.getLatitude(),
location.getLongitude()));
mp1.draggable(true);
mp1.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
map.addMarker(mp1);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location
.getLongitude()), 20));
}
You may try this:
public class MapsActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
private Circle mCircle;
double radiusInMeters = 100.0;
int strokeColor = 0xffff0000; //Color Code you want
int shadeColor = 0x44ff0000; //opaque red fill
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getSupportActionBar().setTitle("Map Location Activity");
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
//mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
#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_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
CircleOptions addCircle = new CircleOptions().center(latLng).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = mGoogleMap.addCircle(addCircle);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Location mlocation;
#Override
public void onLocationChanged(Location location) {
// Add a marker in Sydney and move the camera
mLocation = location;
LatLng myLocation = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(myLocation)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title("My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
Log.d("location", "Latitude:" + mLocation.getLatitude() + "\n" + "Longitude:" + mLocation.getLongitude());
}
for getting current position you can use getLastKnownLocation() method on LocationManager:
locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Location currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng current = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
googleMap.addMarker(new MarkerOptions().position(current).title("Marker Label").snippet("Marker Description"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(current).zoom(14).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
float lat = (float) latLng.latitude;
float lon = (float) latLng.longitude;
mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker in " + lat +" "+ lon));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
});