Using Default Google Maps Activity from Android Studio and want to use MY Location displayed on a marker on a map plus the my location blue google button which is usually located bottom right.
Have looked over hundreds of examples and code and nothing is working.
package com.example.br.nightlyfegooglemap;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,OnInfoWindowClickListener,
OnMyLocationChangeListener, GoogleMap.OnMyLocationChangeListener {
private GoogleMap mMap;
protected GoogleApiClient mGoogleApiClient;
private static final String STATE_IN_PERMISSION="inPermission";
private static final int REQUEST_PERMS=1337;
private boolean needsInit=false;
private boolean isInPermission=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (savedInstanceState==null) {
needsInit=true;
}
else {
isInPermission=
savedInstanceState.getBoolean(STATE_IN_PERMISSION, false);
}
onCreateForRealz(canGetLocation());
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_IN_PERMISSION, isInPermission);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults) {
isInPermission=false;
if (requestCode==REQUEST_PERMS) {
if (canGetLocation()) {
onCreateForRealz(true);
}
else {
finish(); // denied permission, so we're done
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
if (needsInit) {
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,-73.98180484771729));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
mMap.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
mMap.setOnInfoWindowClickListener(this);
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
}
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
}
#Override
public void onMyLocationChange(Location lastKnownLocation) {
Log.d(getClass().getSimpleName(),
String.format("%f:%f", lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude()));
}
private void onCreateForRealz(boolean canGetLocation) {
if (canGetLocation) {
if (readyToGo()) {
setContentView(R.layout.activity_maps);
MapFragment mapFrag=
(MapFragment)getFragmentManager().findFragmentById(
R.id.map);
mapFrag.getMapAsync(this);
}
}
else if (!isInPermission) {
isInPermission=true;
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMS);
}
}
private void addMarker(GoogleMap map, double lat, double lon,
int title, int snippet) {
map.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
.title(getString(title))
.snippet(getString(snippet)));
}
private boolean canGetLocation() {
return(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)==
PackageManager.PERMISSION_GRANTED);
}
}
ERRORS
//CANNOT RESOLVE SYMBOLS FOR THESE
OnInfoWindowClickListener,
OnMyLocationChangeListener
new PopupAdapter
readyToGo
//REQUIRES PERMISSION
mMap.setMyLocationEnabled(true);
//DEPRECATED
mMap.setOnMyLocationChangeListener(this);
Related
When I tested it the first couple of times it was showing perfectly well, then I added some code and it just stopped. It still shows the Mapbox logo on the left bottom screen but it's not loading the map. Here's the code on the MapActivity:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, LocationEngineListener, PermissionsListener {
private MapView mapView;
private Button startButton;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private Location originLocation;
private LocationLayerPlugin locationLayerPlugin;
private Locash customerLocash;
private Point destinationPosition;
private Point originPosition;
private Marker destinationMarker;
private NavigationMapRoute navigationMapRoute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_map);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
startButton = findViewById(R.id.startButton);
Intent activityIntent = getIntent();
String locationJson = activityIntent.getStringExtra("location");
Gson gson = new Gson();
customerLocash = gson.fromJson(locationJson,Locash.class);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Launch Navigation
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.origin(originPosition)
.destination(destinationPosition)
.shouldSimulateRoute(true)
.build();
NavigationLauncher.startNavigation(MapActivity.this, options);
}
});
}
#Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
enableLocation();
LatLng point = new LatLng(customerLocash.getLongitude(),customerLocash.getLatitude());
destinationMarker = map.addMarker(new MarkerOptions().position(point));
destinationPosition = Point.fromLngLat(point.getLongitude(),point.getLatitude());
originPosition = Point.fromLngLat(originLocation.getLongitude(), originLocation.getLatitude());
getRoute(originPosition, destinationPosition);
startButton.setEnabled(true);
}
private void enableLocation() {
if (PermissionsManager.areLocationPermissionsGranted(this)){
initializeLocationEngine();
initializeLocationLayer();
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings("MissingPermission")
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this)
.obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null){
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
#SuppressWarnings("MissingPermission")
private void initializeLocationLayer() {
locationLayerPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationLayerPlugin.setLocationLayerEnabled(true);
locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
}
private void setCameraPosition(Location location){
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),
location.getLongitude()),13.0));
}
private void getRoute(Point origin, Point destination){
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (response.body() == null){
Toast.makeText(MapActivity.this, "No Routes Found", Toast.LENGTH_SHORT).show();
return;
} else if (response.body().routes().size() == 0){
Toast.makeText(MapActivity.this, "No Routes Found", Toast.LENGTH_SHORT).show();
return;
}
DirectionsRoute currentRoute = response.body().routes().get(0);
navigationMapRoute = new NavigationMapRoute(null, mapView,map);
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Toast.makeText(MapActivity.this, "Error:" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#SuppressWarnings("MissingPermission")
#Override
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null){
originLocation = location;
setCameraPosition(location);
}
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, "Location Required", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted){
enableLocation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
#SuppressWarnings("MissingPermission")
protected void onStart() {
super.onStart();
if (locationEngine != null){
locationEngine.requestLocationUpdates();
}
if (locationLayerPlugin != null){
locationLayerPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null){
locationEngine.removeLocationUpdates();
}
if (locationLayerPlugin != null){
locationLayerPlugin.onStop();
}
mapView.onStop();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState, #NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (locationEngine != null){
locationEngine.deactivate();
}
mapView.onDestroy();
}
}
Oh and the Locash object is a class I use to store user location on firebase and the likes.
Looks like a problem I had. Not sure if this is the same, but in my case setting the textureView option to true solved it.
This is how I did it in code:
val resourceOptions = ResourceOptions.Builder()
.accessToken(context.getString(R.string.mapbox_access_token))
.build()
mapView = MapView(context, MapInitOptions(context, resourceOptions).apply { textureView = true })
I am not sure how to do it in XML.
I never try Google Map. This is a client project where they use
compile project(':google-play-services_lib')
I have to improve their design to support the latest version of android that's way
compile 'com.android.support:appcompat-v7:25.1.1'
it shows me an error so I try this link.
It say It can be fixed by updating the Google Play Services dependency to 6.1.+. .
Then I use
compile 'com.google.android.gms:play-services:10.2.0'
to support latest version of android.
Then it shows me error getMap() so I convert it to getMapAsync() but what are duing is private static GoogleMap googlemap; then assign it like this:
googlemap=((MapFragment)getFragmentManager().findFragmentById(R.id.places_map)).getMap();
When i convert it to
googlemap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
It show me error. What to do
public class Frnt_mapActivity extends AppCompatActivity implements OnMapReadyCallback {//implements OnMapClickListener, OnMarkerDragListener {
public static double Shop_lat;
public static double Shop_lng;
public String Shop_title;
public String Shop_address;
public String Shop_icons;
ProgressDialog mDialog;
JSONObject jsonobject3;
JSONArray jsonarray3;
// Google Map
//private static GoogleMap googlemap;
public static EditText edit_search;
public static Button btn_search;
ArrayList<SearchBeams> getAllimgs;
// Location
ArrayList<String> world_locationlist;
ArrayList<LocationBeams> worldlocation;
// Looking for
ArrayList<String> looking_forlist;
ArrayList<LookingForBeams> world_looking_for;
public static ArrayList<SearchBeams> searchdata_list;
public static ArrayList<NormalSearchBeams> normlSearchList;
public static String mid;
public static String mpost_title;
public static String mimage;
public static List<String> imglist;
ArrayList<All_products_lat_long> venueList;
Spinner mySpinner2;
public static ArrayList<SearchBeams> GetIMG;
public static TextView txtlocation;
public static TextView txtlookingfor;
public static ArrayList<All_products_lat_long> mpItm;
String vals;
private int i;
private Intent intent;
HashMap<Marker, Integer> hashMap = new HashMap<Marker, Integer>();
public static LatLng latlong;
#Override
public void onMapReady(GoogleMap map) {
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frnt_map_activity);
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mySpinner2 = (Spinner) findViewById(R.id.spin_looking_for);
// Spinner adapter
txtlookingfor = (TextView) findViewById(R.id.country);
txtlocation = (TextView) findViewById(R.id.rank);
SupportMapFragment mapFragment=getSupportFragmentManager().findFragmentById(R.id.places_map).getMapAsync(this);
googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
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;
}
googlemap.setMyLocationEnabled(true);
googlemap.getUiSettings().setZoomControlsEnabled(true);
googlemap.getUiSettings().setMyLocationButtonEnabled(true);
googlemap.getUiSettings().setCompassEnabled(true);
googlemap.getUiSettings().setRotateGesturesEnabled(true);
googlemap.getUiSettings().setZoomGesturesEnabled(true);
googlemap.setMyLocationEnabled(true);
intent=new Intent(Frnt_mapActivity.this,MainActivity.class);
googlemap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
i=hashMap.get(arg0);
intent.putExtra("PRODUCT_ID", venueList.get(i).getId());
startActivity(intent);
//overridePendingTransition( R.anim.slide_right, R.anim.slide_left );
}
});
new Frnt_mIcons_Activity().execute();
new LocationList().execute();
new LookingForList().execute();
edit_search = (EditText)findViewById(R.id.txt_search);
btn_search = (Button)findViewById(R.id.btn_search);
btn_search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text;
text=edit_search.getText().toString();
// text!=null &&
if(text.equals("") && text.startsWith(" ")==false){
new GetSearch_data().execute();
/*new Get_normal_search().execute();
edit_search.setText("");*/
}else
new Get_normal_search().execute();
edit_search.setText("");
//new GetSearch_data().execute();
}
});
}
They are calling googlemap and also adding marks. how i can implement it
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try{
if(bd!=null){
Marker marker=googlemap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
.title(venue.getPost_title())
.icon(bd));
hashMap.put(marker, k);
}
}catch (Exception e){
e.printStackTrace();
}
}
switch (Integer.parseInt(venueList.get(k).getId()))
{
case 5689 :
Marker marker=googlemap.addMarker(new MarkerOptions()
.position(new LatLng(la, ln))
.title(venueList.get(k).getPost_title())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.fruitandveg)));
hashMap.put(marker, k);
break;
case 5779 :
Marker marker1=googlemap.addMarker(new MarkerOptions()
.position(new LatLng(la, ln))
.title(venueList.get(k).getPost_title())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.coffee)));
hashMap.put(marker1, k);
break;
.....}
This is a client project where they use compile project(':google-play-services_lib')
So, you replace that with this (notice the -maps)
compile 'com.google.android.gms:play-services-maps:10.2.0'
Then it shows me error getMap() so I convert it to getMapAsync()
Which is correct, but
You really should not have a static map variable. If there are static variables all over the app, something is wrong in the design.
When i convert it to googlemap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this); It show me error
Well, yes that'll error
1) getActivity() is not necessary. You already are in an Activity class
2) getSupportFragmentManager() will only be available if you extends AppCompatActivity (or FragmentActivity) in the class definition
3) getMapAsync(this) will not work unless you implements OnMapReadyCallback on the class definition.
If you do all that, then you will have something like
import com.google.android.gms.maps.OnMapReadyCallback;
public class YourActivity extends AppCompatActivity
implements OnMapReadyCallback {
private void SupportMapFragment mMapFragment;
// private GoogleMap mMap; // Commented so you don't use in onCreate
#Override
public void onMapReady(GoogleMap map) {
// this.mMap = map;
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// TODO: call other map setup methods
}
// Inside onCreate
mMapFragment = getSupportFragmentManager().findFragmentById(R.id.map);
mMapFragment.getMapAsync(this);
// Don't do this in onCreate
// googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
I'm trying to display heatmap points in android using google maps utility library, nothing is displayed on the map. I don't know if I need something else, I've looked at examples but in my case it doesn't work. I'm using fragments.
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
private HeatmapTileProvider mProvider;
protected LatLng mCenterLocation = new LatLng( 39.7392, -104.9903 );
public MapFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For showing a move to my location button
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.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;
}
googleMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
LatLng colorado = new LatLng(39.7392, -104.9903);
googleMap.addMarker(new MarkerOptions().position(colorado).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(colorado).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
addHeatMap();
}
});
return rootView;
}
public void addHeatMap(){
ArrayList<LatLng> locations = generateLocations();
mProvider = new HeatmapTileProvider.Builder().data(locations).build();
mProvider.setRadius(HeatmapTileProvider.DEFAULT_RADIUS );
googleMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
}
private ArrayList<LatLng> generateLocations() {
ArrayList<LatLng> locations = new ArrayList<LatLng>();
double lat;
double lng;
Random generator = new Random();
for (int i = 0; i < 1000; i++) {
lat = generator.nextDouble() / 3;
lng = generator.nextDouble() / 3;
if (generator.nextBoolean()) {
lat = -lat;
}
if (generator.nextBoolean()) {
lng = -lng;
}
locations.add(new LatLng(mCenterLocation.latitude + lat, mCenterLocation.longitude + lng));
}
return locations;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
Checking the Heatmaps guide, I don't see any issues about it. Try to call clearTileCache(), its indicated in its API reference that you should call it after setRadius.
I have a map activity in my app, and I'm trying to make that when I open the map activity, it will zoom in automatically to my location but instead it zooms in every some seconds.
This is my code:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String FIREBASE_URL="https://****.firebaseio.com/";
private Firebase firebaseRef;
private LocationManager locationManager;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
Firebase.setAndroidContext(this);
firebaseRef = new Firebase(FIREBASE_URL);
// 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);
setUpMapIfNeeded();
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
final String title = marker.getTitle().toString();
firebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot user : dataSnapshot.child("users").getChildren()) {
String event_title = user.child("event/event_title").getValue().toString();
if (title.equals(event_title)) {
String event_date = user.child("event/event_date").getValue().toString();
String event_content = user.child("event/event_content").getValue().toString();
String age_limit = user.child("event/age_limit").getValue().toString();
String event_hour = user.child("event/event_hour").getValue().toString();
String location_left = user.child("location_left").getValue().toString();
String location_right = user.child("location_right").getValue().toString();
final SharedPreferences sp = getSharedPreferences("key", 0);
final SharedPreferences.Editor sedt = sp.edit();
sedt.putString("event_title", event_title);
sedt.putString("event_date", event_date);
sedt.putString("event_content", event_content);
sedt.putString("age_limit", age_limit);
sedt.putString("event_hour", event_hour);
sedt.putString("location_left", location_left);
sedt.putString("location_right", location_right);
sedt.commit();
}
}
Intent intent = new Intent(MapsActivity.this, EventInfo.class);
startActivity(intent);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return true;
}
});
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(MapsActivity.this, "You have to accept!", Toast.LENGTH_LONG).show();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
}
if (mMap != null) {
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(arg0.getLatitude(), arg0.getLongitude()));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(12);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
});
}
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap=googleMap;
firebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.child("users").getChildren()) {
String rightLocation = child.child("location_right").getValue().toString();
String leftLocation = child.child("location_left").getValue().toString();
double location_left = Double.parseDouble(leftLocation);
double location_right = Double.parseDouble(rightLocation);
String event_title = child.child("event/event_title").getValue().toString();
LatLng cod = new LatLng(location_left, location_right);
googleMap.addMarker(new MarkerOptions().position(cod).title(event_title));
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
I can guess that it is a problem in my setUpMapIfNeeded() method, but I can't find the problem.
What am I doing wrong?
The problem is due to below code
CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(arg0.getLatitude(), arg0.getLongitude()));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(12);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
As onMyLocationChange listener is getting called when their is any change in location.
So if you required to change to center of map to latest location then you have do write code to check the actual displacement between previous location.
If actually displacement was happened then only you can change the center and zoom of the map.
I'm trying to track users position and draw a path/his route on a map according to his movement (updatePolyline(), updateCamera(), updateMarker() are responsible for drawing a route). Program compiles, but the crucial error is that onLocationChanged() isn't called when location actually changes, thus, no path is beeing drawn.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private PolylineOptions mPolylineOptions;
LocationManager locationManager;
private LatLng mLatLng;
double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
// LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
this.locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
// if(location != null) {
//
// onLocationChanged(location);
// }
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, this);
}
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
mLatLng = new LatLng(latitude, longitude);
runOnUiThread(new Runnable() {
#Override
public void run() {
updatePolyline();
updateCamera();
updateMarker();
}
});
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
initializeMap();
}
private void updatePolyline() {
mMap.clear();
mMap.addPolyline(mPolylineOptions.add(mLatLng));
}
private void updateMarker() {
mMap.addMarker(new MarkerOptions().position(mLatLng));
}
private void updateCamera() {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16));
}
private void initializeMap() {
mPolylineOptions = new PolylineOptions();
mPolylineOptions.color(Color.BLUE).width(10);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
LocationManager lm = null;
boolean gps_enabled = false, network_enabled = false;
if (lm == null)
lm = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MapsActivity.this);
dialog
.setTitle("No gps")
.setPositiveButton("Atšaukti", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
})
.setNegativeButton("Open settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MapsActivity.this.startActivity(myIntent);
}
});
AlertDialog alert_dialog = dialog.create();
alert_dialog.show();
}
return false;
}
});
}
}
}