Marker not visible in Google Map Android v2 - android

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.

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

Android - Google Maps - LocationListener - adding marker onLocationChanged makes app crash

I want a marker to show my current location. All permissions needed are added. When I comment out mMap.addMarker and mMap.moveCamera the app is working and Googlemaps is shown. If I let one of those two in my code the app crashes before the map even opens.
I've tried with removing the marker if it isn't null but this doesn't solve the problem.
Do you guys have any idea how I can get the app working?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private List<LatLng> fountain = null;
private LocationManager locationManager;
private double posLat;
private double posLng;
private LatLng position;
private Marker mPosition;
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) this.getSystemService(Context.LOCATION_SERVICE);
startGPS();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(48.16786112327462, 16.383984438313828);
mPosition = mMap.addMarker(new MarkerOptions().position(sydney).title("Your Position").icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
//--------------------------------------------GPS Listener---------------------------------------
public void startGPS() {
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) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 5);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this);
onLocationChanged(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 5: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
getDialog2("Keine Erlaubnis für GPS").show();
}
}
}
}
#Override
public void onLocationChanged(Location location) {
posLat = location.getLatitude();
posLng = location.getLongitude();
position = new LatLng(posLat, posLng);
if (mPosition != null) {
mPosition.remove();
}
mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//----------------------------Helper Methods-----------------------------------------------
public Dialog getDialog2(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
return builder.create();
}
public Dialog getDialog(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
Okay, I already solved the problem. So I post the solution here.
I have implemented on the MapsActivity the LocationListener interface and for some reason it doesn't work this way. I can retrieve the geocoordinates but as soon as I want to move the camera or add a marker it the app crashes as it gets opened.
I don't know why, but instead of:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this)
I undo the implementation of the LocationListener and just create a new one at the position of ,,this":
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
posLat = location.getLatitude();
posLng = location.getLongitude();
position = new LatLng(posLat, posLng);
if (mPosition != null) {
mPosition.remove();
}
mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
);
and this way it works without problem.

why the google maps camera not in my location?

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.

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

Not working plot multiple marker getOverlay().add(classobject) not accept

This is my code i want to plot multiple marker in google map
when i write mapview.getoverlay().add(overlaymarker) it is not working
i am not use MapActivity i use fragment so this is not supported getoverlays() please help me.......
fragmnt1.java
public class one extends Fragment implements LocationListener {
MapView mapView;
GoogleMap googleMap;
private boolean mapsSupported = true;
Location location;
double latitude; // latitude
double longitude;
LatLng latlang;
LocationManager manager;
Overlay_Marker overmarker;
frag provider;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RelativeLayout parent = (RelativeLayout) inflater.inflate(R.layout.one, container, false);
mapView = (MapView) parent.findViewById(R.id.map);
provider=new frag(getActivity());
Log.d("spn", "oncreate view");
return parent;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(getActivity());
} catch (Exception ex) {
mapsSupported = false;
}
if (mapView != null) {
mapView.onCreate(savedInstanceState);
}
initializeMap();
Log.d("spn", "onactivity created");
}
private void initializeMap() {
if (googleMap == null && mapsSupported) {
mapView = (MapView) getActivity().findViewById(R.id.map);
googleMap = mapView.getMap();
Drawable dmarker=getResources().getDrawable(R.drawable.ic_launcher);
dmarker.setBounds(0, 0, dmarker.getIntrinsicWidth(), dmarker.getIntrinsicHeight());
overmarker=new Overlay_Marker(dmarker,getActivity());
Drawable windmill = getResources().getDrawable(R.drawable.ic_launcher);
Drawable bigBen = getResources().getDrawable(R.drawable.ic_launcher);
Drawable eiffelTower = getResources().getDrawable(R.drawable.ic_launcher);
overmarker.addOverlayItem(52372991, 4892655, "Amsterdam", windmill);
overmarker.addOverlayItem(51501851, -140623, "London", bigBen);
overmarker.addOverlayItem(48857522, 2294496, "Paris", eiffelTower);
//List<Overlay_Marker> temp = (List<Overlay_Marker>) mapView.getOverlay();
// temp.add(overmarker);
mapView.getOverlay().add(overmarker); /// Not working
GetLongitude_Latitude();
}
}
public void GetLongitude_Latitude()
{
manager=(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
location=provider.getLocation(LocationManager.NETWORK_PROVIDER);
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
String provider = manager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = manager.getLastKnownLocation(provider);
manager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
// Toast.makeText(getActivity(), "Location retrieved"+location.getLatitude()+" and "+location.getLongitude(), Toast.LENGTH_SHORT).show();
//else
// Toast.makeText(getActivity(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
Log.d("spn", "location"+location);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
initializeMap();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onLocationChanged(Location location) {
latitude=location.getLatitude();
longitude=location.getLongitude();
latlang=new LatLng(latitude, longitude);
MarkerOptions marker=new MarkerOptions().position(latlang);
googleMap.addMarker(marker);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder().target(
latlang).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#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
}
}

Categories

Resources