OnMapReady gets called before ReadCsvFile() is executed,which fetches the latlng points from the a CSV file.Hence when map is displayed, it doesn't show the current Location.How can i make sure onMapReday is called only after latLng points are fetched from the file? How to prevent getting a null pointer exception at
"googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));"
public void onMapReady(final GoogleMap googleMap) {
ReadCsvFile(this);
for (LocationHelperBean locationHelperBean : parameterList) {
latLng=new LatLng(Double.parseDouble(String.valueOf(locationHelperBean.getLatitude())), Double.parseDouble(String.valueOf(locationHelperBean.getLongitude())));
arrayPoints.add(latLng);
}
googleMap.setMyLocationEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
googleMap.addMarker(new MarkerOptions().snippet("latitude:" + latitude + "longitude:" + longitude + "bearing:" + bearing + "accuracy:" + accuracy + "altitude" + altitude + "speed" + speed).position(latLng).draggable(true));
PolylineOptions polylineOptions = new PolylineOptions().add(latLng).width(6).color(Color.RED).geodesic(true);
polylineOptions.addAll(arrayPoints);
map.addPolyline(polylineOptions);
}
If you use MapView you could just call onCreate(null) after you have obtained everything from readCsvFile() to set up the map. Otherwise just get the GoogleMap when it's ready and call setupMap() when readCsvFile() finished like so:
private GoogleMap map;
#Override
public void onMapReady(GoogleMap map) {
this.map = map;
setupMap();
}
private void setupMap() {
if (map != null && latLng != null) {
// Do something with map (e.g. add markers,...)
}
}
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));
}
});
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 do want to get current location with GoogleApiClient with this code below,
#Override
public void onConnected(#Nullable Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null)
{
currentLat = mLastLocation.getLatitude();
currentLon = mLastLocation.getLongitude();
}else
{
Toast.makeText(getApplicationContext(), "Cannot get lat and lon", Toast.LENGTH_SHORT).show();
}
}
then after that i do want to put marker on current location, my problem is mLastlocation still null
#Override
public void onMapReady(GoogleMap googleMap) {
dGoogleMap = googleMap;
if(mLastLocation != null)
{
MarkerOptions marker = new MarkerOptions()
.position(new LatLng(currentLat, currentLon))
.title("My Current Location");
dGoogleMap.addMarker(marker);
dGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(currentLat, currentLon), 16));
}
}
Or this is my fault missunderstand the flow of async, or just my poor logic needs to be improved.
Put below line in your onMapReady method
dGoogleMap.setMyLocationEnabled(true);
I have the following function that returns me the current location of device:
void getCurrentLocation()
{
Location myLocation = map.getMyLocation();
if(myLocation!=null)
{
double dLatitude = myLocation.getLatitude();
double dLongitude = myLocation.getLongitude();
map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))
.title("My Location").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
else
{
Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
}
}
but some methods are showing in red like it were undefined:
As you can notice, these methods are related with map, it work in onMapReady() function but out of it show it unrecognized. Why is that? What libraries I have to add? I declare map like this:
private MapFragment map;
Here is what your general code structure should look like.
The important part is to assign your local map reference to the one returned in the onMapReady() callback.
public class MainActivity extends Activity
implements OnMapReadyCallback {
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap retMap) {
map = retMap;
setUpMap();
}
public void setUpMap(){
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
}
void getCurrentLocation()
{
Location myLocation = map.getMyLocation();
if(myLocation!=null)
{
double dLatitude = myLocation.getLatitude();
double dLongitude = myLocation.getLongitude();
map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))
.title("My Location").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
else
{
Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
}
}
}
Why are you using
private MapFragment map;
Your map should be of type
com.google.android.gms.maps.GoogleMap
Just change
private MapFragment map;
to
private GoogleMap map;
and get the map like the following:
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
It will work fine.
I'm trying to control Google map camera like this
private void setUpMap() {
Log.e(LOG_TAG, "in setup method");
mMap.setMyLocationEnabled(true);
LatLng startingPoint = new LatLng(129.13381, 129.10372);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(startingPoint, 16));
Log.e(LOG_TAG, "in Setup method" + (mMapFragment == null));
}
LogCat prints
"in setup method"
"in setup method false"
2 log is shown it means mMap.moveCamera(...) is called
setUpMap() call from here
private void setUpMapIfNeeded() {
mMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentByTag(MFragment.TAG);
if (mMapFragment != null) {
mMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
}
});
}
}
try this: hope it will work.
private void setUpMap() {
Log.e(LOG_TAG, "in setup method");
mMap.setMyLocationEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(15).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
Log.e(LOG_TAG, "in Setup method" + (mMapFragment == null));
}
Your coordinates specified at LatLng startingPoint = new LatLng(129.13381, 129.10372); seems to be a bit off. In more detail, the maximum latitude is 90 degrees, which is the north pole (-90 is the south pole).
The result of this will be that the camera will not move to a position which is invalid.
Try using coordinates from a known location, such as LatLng startingPoint = new LatLng(55.70, 13.19); which will give you the position of Lund, Sweden.
So basically, revise the latitude and longitude coordinates for your position.