why the google maps camera not in my location? - android

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.

Related

marker is showing wrong location on google map

i have created navigation drawer activity to show my map using map fragment.
my map is visible but it points wrong location.i want to show my current location. i have checked permissions in manifest. I don't know where exactly i have done wrong.
here is mapFragment.java file
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_map, container, false);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
}
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getLocality() + ":";
result += addresses.get(0).getCountryName();
LatLng latLng = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(latLng).title(result));
map.setMaxZoomPreference(20);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
Use this code :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_map, container, false);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
// changes here
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
}
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getLocality() + ":";
result += addresses.get(0).getCountryName();
LatLng latLng = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(latLng).title(result));
map.setMaxZoomPreference(20);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
}

Simple tracking app using Google Maps on Android

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);

Marker not visible in Google Map Android v2

Hello I need help adding marker to the google map to show my current location. Even after using the addMarker() method and checking the API key, the marker is still not visible. I am able to get latitude, longitude values but the marker is not visible. I am trying to do it for fragment.
Here is my complete code:
public class WhereAmI extends Fragment {
GoogleMap googleMap;
TextView tv;
Location current;
LocationManager lm;
LocationListener locLis;
public static double lat=0.0000;
public static double longi=0.0000;
public static String addressString="Address Not Available";
LatLng Locateme;
public static String disp;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.whereami, container,false);
tv=(TextView) v.findViewById(R.id.textView1);
lm=(LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
locLis=new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
switch (arg1) {
case LocationProvider.AVAILABLE:
Toast.makeText(getActivity(), "AVAILABLE", Toast.LENGTH_SHORT).show();
break;
case LocationProvider.OUT_OF_SERVICE:
Toast.makeText(getActivity(), "OUT_OF_SERVICE", Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Toast.makeText(getActivity(), "TEMPORARILY_UNAVAILABLE", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getActivity(), provider+" Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getActivity(), provider+" Disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location loc) {
addressString="";
lat=loc.getLatitude();
longi=loc.getLongitude();
Geocoder gc=new Geocoder(getActivity());
List<Address> address;
try{
address=gc.getFromLocation(lat, longi, 1);
for(int i=0;i<address.size();i++)
{ Address a=address.get(i);
for(int j=0;j<a.getMaxAddressLineIndex();j++){
addressString+=a.getAddressLine(j)+"\n";
}}
disp="Latitude: "+lat+"\n"+"Longitude: "+longi+"\n"+"Address: "+addressString;
tv.setText(disp);
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
googleMap.setMyLocationEnabled(true);
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat,longi)).title("Current Location"));
marker.setIcon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat, longi)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}catch(Exception e){
e.printStackTrace();
}
}};
return v;
}
#Override
public void onResume() {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 5, locLis);
super.onResume();
}
#Override
public void onPause() {
lm.removeUpdates(locLis);
super.onPause();
}
}
because you are sending NULL to the parameters i.e Latitude and Longitude.
Make sure you are getting the coordinates to pointer to point.

Android : Setting default zoom level for an area with com.google.android.gms.maps.GoogleMap

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()));

The Google Map keep pointing to my current location when I viewing other parts of the map

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.

Categories

Resources