I'm developing a simple app showing the position of the user on a map. When he moves, the camera follows him to keep the user at the center of the map. Everything seems very simple, here is the relevant code.
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
LocationManager locationManager = null;
Location currentBestLocation = null;
LocationListener locationListener = null;
GoogleMap map = null;
Marker marker = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
currentBestLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
currentBestLocation = location;
if(map != null){
LatLng position = new LatLng(location.getLatitude(), location.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(position, 17));
if(marker != null) marker.remove();
marker = map.addMarker(new MarkerOptions()
.position(position)));
}
}
.
.
.
};
}
#Override
public void onMapReady(GoogleMap map) {
this.map = map;
this.map.setMyLocationEnabled(true);
if(currentBestLocation != null)
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentBestLocation.getLatitude(), currentBestLocation.getLongitude()), 17));
}
#Override
protected void onStart() {
super.onStart();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
protected void onStop() {
super.onStop();
locationManager.removeUpdates(locationListener);
}
}
However with this implementation I'm facing the following issue: although the camera follows the user movements, very often the street name layer fails to update or there's a fuzzy/blurry section that fails to update until I do a manual scroll of the map. Then the entire map updates instantly. What am I doing wrong?
In your onLocationChanged use this code.
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
map.moveCamera(center);
map.animateCamera(zoom);
Related
I am following an online course to create an Uber clone. However, I am having an issue. From the emulator, when the rider option is clicked, I want to redirect to a new activity called "RiderActivity" and a map is supposed to be shown. However, nothing happens.
Here is my code for the new activity:
public class RiderActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 1){
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);
updateMap(lastKnownLocation);
}
}
}
}
public void updateMap(Location location){
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rider);
// 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;
//setup location manager and listerner
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE) ;
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateMap(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if(Build.VERSION.SDK_INT < 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else{
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);
updateMap(lastKnownLocation);
}
}
// 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.newLatLng(sydney));
}
}
While in the MainActivity, I have a method
public void redirectActivity(){
if(ParseUser.getCurrentUser().get("riderOrDriver") == "rider"){
Intent intent = new Intent(getApplicationContext(),RiderActivity.class);
}
}
emulators do not support google maps, until just now, you need to download new emulators with play store support.
If you have done the above, you might wanna crosscheck your google map api key and check whether you have enabled maps api in developer api console.
Getting a map in app is rather a very simple step by step process as given in google map integration docs.
I am making a location based reminder app and want to know how to add markers to the current location.
I am using the following code:
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(googleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 10f));
//Add a marker in Sydney, Australia, and move the camera.
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
mMap.clear();
locationLat = latLng.latitude;
locationLong = latLng.longitude;
AddLocationActivity.this.addMarker(new LatLng(locationLat,locationLong), AddLocationActivity.locationName);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(locationLat,locationLong), 10.9f));
AddLocationActivity.this.mainClass.locationName = address;
Log.i("AddLocationActivity",""+AddLocationActivity.this.mainClass.locationName);
}
});
}
Is there any method to zoom the map view and/or add markers to the current location?
change your code according to following:
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
mMap.clear();
Marker marker = mMap.addMarker(new MarkerOptions().position(latLng).title("Title"));
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.9f));
}
});
Try this instead
LatLng markerLocation = new LatLng(latitude,longitude); // latitude and longitude must be a float or double
Marker marker = mMap.addMarker(new MarkerOptions()
.position(markerLocation)); // any title you want
for zooming the map view, there is a default function already. use hand gestures if you want to add a bottom, you can add zoom controls
Here is the whole code
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(googleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 10f));
//Add a marker in Sydney, Australia, and move the camera.
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
mMap.clear();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10f));
Marker marker = mMap.addMarker(new MarkerOptions().position(latLng));
}
});
}
Try this way this worked for me
public class MainActivity extends Activity implements LocationListener {
GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
}
#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));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
OUTPUT
You first need to get the current location by a onlicationchangelistener in google maps. here is the listener in the code.
Then place marker according to that location you got.
Below is the code part-
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
if(mMarker == null){
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
}else{
mMarker.remove();
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
}
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
};
add the listener to maps.
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
This will put marker in the current lcoation.
I have code for google maps in fragment android , i want the camera in my location but the camera is in other location and i dont know why this happen
anyone can help me find out why this situation happen
This is my fragment code :
public class FragmentMap extends Fragment implements LocationListener {
MapView mapView;
GoogleMap map;
double latitude;
double longitude;
public String bestProvider;
public Criteria criteria;
#Override
public void onLocationChanged(Location location) {
// Getting latitude of the current location
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.map_fragment, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this.getActivity());
// Updates the location and zoom of the MapView
map.setMyLocationEnabled(true);
criteria = new Criteria();
bestProvider = String.valueOf(MainActivity.locationManager.getBestProvider(criteria, true)).toString();
Location location = MainActivity.locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
CameraUpdate cameraUpdate =
CameraUpdateFactory
.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16);
map.animateCamera(cameraUpdate);
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
This is my location declaration :
public static LocationManager locationManager;
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
your onlocationchange should be -
#Override
public void onLocationChanged(Location location) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude()))
.zoom(14)
.build();
if (map != null) {
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
this will move camera to your present location.
let me know if it worked for you.
I am working on an Android application in which I would like to show user the nearby area to his location. Unfortunately, when I get map data from GoogleMaps, it shows me the entire world and just a dot on the present location and I need to keep zooming in. I tried to set the zoom factor upto 100, but that didn't change anything. Is there something I am doing wrong. Kindly let me know.
Here is my code :
public class MapsActivitiyFragment extends FragmentActivity implements LocationListener {
static GoogleMap googleMap;
LocationManager locationManager;
String provider;
LatLng myPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_maps_activitiy);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.googleMap);
googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
circleDraw(location.getLatitude(),location.getLongitude());
zoomIn(location.getLatitude(), location.getLatitude());
onLocationChanged(location);
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
public void circleDraw(double i, double ii) {
googleMap.addCircle(new CircleOptions().center(new LatLng(i, ii))
.radius(10000).strokeColor(Color.BLACK).strokeWidth(5)
.fillColor(Color.argb(50, 238, 116, 116)));
}
public void zoomIn(double Lat, double Long) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(Lat,
Long));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
}
#Override
public void onLocationChanged(Location location) {
googleMap.clear();// clean the map
Toast.makeText(this, "Location Changed", Toast.LENGTH_SHORT).show();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
myPosition = new LatLng(latitude, longitude);
circleDraw(latitude, longitude);
zoomIn(latitude, longitude);
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
Update
Image :
remember that onLocationChanged is invoked when you're position is changed. If you stand still you can have a problem with getting it also you will have a lot of problems with that when you work on emulator.
Your code looks fine. Set zoom in the place were you setup you map. Don't set it in onLocationChanged In your code I would set the zoom in onCreate
// EDIT
LatLng center = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition.Builder cameraPosition = new CameraPosition.Builder();
cameraPosition.target(center);
cameraPosition.zoom((int)configuration.get("zoom"));
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition.build()));
This is TrackMap.java
public class TrackMap extends FragmentActivity implements LocationListener {
GoogleMap map;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track_map);
boolean lowPowerMoreImportantThanAccurancy = true;
LocationRequest request = LocationRequest.create();
request.setPriority(lowPowerMoreImportantThanAccurancy ?
LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY:
LocationRequest.PRIORITY_HIGH_ACCURACY);
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
Marker marker = map.addMarker(new MarkerOptions()
.position(new LatLng(0, 0)).draggable(true)
// Set Opacity specified as a float between 0.0 and 1.0,
// where 0 is fully transparent and 1 is fully opaque.
.alpha(0.7f).flat(true)
.getPosition());
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
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));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
}
I wonder why it keep points to my current position while I viewing other parts of the map. Your help is very much appreciated.I doesn't really know what to delete the particular code to suit my needs
because every time onLocationChanged is called you animate camera to the new location passed in.