I have this seemingly simple class in my app. All it does it add a circle to the mapView at my Location with the circle color depending on the CDMA signal Strength at the location. Or that's what it's supposed to do.
The app works fine if I only ask for one circle and the location with the cdma signal but it doesn't work in the if Statement format, even if there is only one else if present. My question is why and if It has anything to do with how many times maps can be called at once. And If anyone knows a workaround, it would help a lot.
private GoogleMap mMap;
int cdmaSignal;
double latitude;
double longitude;
BroadcastReceiver br;
#Override
protected void onResume() {
super.onResume();
if(br == null){
br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent z) {
shoveItThrough((int) z.getExtras().get("cell signal cdma"),
(double) z.getExtras().get("latitude"), (double) z.getExtras().get("longitude"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(0) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build();
//
//mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
/*mMap.addCircle(new CircleOptions()
.center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(255,0,0)).fillColor(Color.rgb((255,0,0)));*/
//LatLng home = new LatLng(latitude, longitude);
//mMap.addMarker(new MarkerOptions().position(home));
if(cdmaSignal<=-120 && cdmaSignal>-100){
mMap.addCircle(new CircleOptions()
.center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(255,0,0)).fillColor(Color.rgb(255,0,0)));
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
/*LatLng home = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(home));
mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
} else if(cdmaSignal<=-100 && cdmaSignal>-80){
mMap.addCircle(new CircleOptions()
.center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(255,98,12)).fillColor(Color.rgb(255,98,12)));
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
/*LatLng home = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(home));
mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
} else if(cdmaSignal<=-80 && cdmaSignal>-60){
mMap.addCircle(new CircleOptions()
.center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(255,181,12)).fillColor(Color.rgb(255,181,12)));
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
/*LatLng home = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(home));
mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
} else if(cdmaSignal<=-60 && cdmaSignal>-40){
mMap.addCircle(new CircleOptions()
.center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(211,255,0)).fillColor(Color.rgb(211,255,0)));
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
/*LatLng home = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(home));
mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
} else if(cdmaSignal<=-40 && cdmaSignal>-20){
mMap.addCircle(new CircleOptions()
.center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(164,255,0)).fillColor(Color.rgb(164,255,0)));
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
/*LatLng home = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(home));
mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
} else if(cdmaSignal<=-20 && cdmaSignal>-0){
mMap.addCircle(new CircleOptions()
.center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(0,255,0)).fillColor(Color.rgb(0,255,0)));
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
/*LatLng home = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(home));
mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
}
}
};
}
registerReceiver(br, new IntentFilter("location_update"));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
}
#Override
protected void onDestroy() {
super.onDestroy();
if(br != null){
unregisterReceiver(br);
}
}
/**
* 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;
}
public void shoveItThrough(int c, double la, double lo){
cdmaSignal = c;
latitude = la;
longitude = lo;
}
}
Related
I am using the following method to move the camera:
private void moveCamera(LatLng latLng, float zoom, GoogleMap map) {
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
When I am using it inside OnMapReady like this:
private void initMapHome() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.harta_adauga_adresa_acasa);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady: map is readyyyyyyyyyyyyyyyyyyy");
gmap = googleMap;
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
gmap.setMyLocationEnabled(true);
gmap.getUiSettings().setMyLocationButtonEnabled(true);
gmap.getUiSettings().setCompassEnabled(true);
gmap.getUiSettings().setMapToolbarEnabled(false);
gmap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
});
gmap.setOnMapClickListener(latLng -> {
gmap.clear();
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title(adresa);
gmap.addMarker(options).showInfoWindow();
});
moveCamera(pozitie_curenta, DEFAULT_ZOOM, gmap);
}
});
}
The camera animates in a nice manner to the selected position, the pozitie_curenta LatLng created somewhere else in my code. Now, I have a AutoCompleteTextView that returns the places (I am using the one created by Mukesh Solanki from github), and I am looking to move the camera on the selected place from the AutoCompleteTextView. I have the following code:
adresa_home.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Place place = (Place) parent.getItemAtPosition(position);
adresa_home.setText(place.getDescription());
placesApi.fetchPlaceDetails(place.getId(), new OnPlacesDetailsListener() {
#Override
public void onPlaceDetailsFetched(PlaceDetails placeDetails) {
latitudine_acasa = placeDetails.getLat();
longitudine_acasa = placeDetails.getLng();
updateHartaHome(latitudine_acasa, longitudine_acasa, place.getDescription());
}
#Override
public void onError(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
}
);
}
});
The place is fetched correctly, and I get the latitude and longitude correctly. The method updateHartaHome is looking like this:
private void updateHartaHome(double lat, double lng, String title) {
acasa = new LatLng(lat, lng);
MarkerOptions options = new MarkerOptions()
.position(pozitie_curenta)
.title(title);
gmap.addMarker(options).showInfoWindow();
moveCamera(acasa, DEFAULT_ZOOM, null, gmap);
}
Debugging the code I've come to the conclusion that the problem it's with the moveCamera from the updateHartaHome which is never called. Setting a breakpoint on the line gmap.addMarker(options).showInfoWindow(); gets me the following:
So, eveything looks fine, but the map doesn't update and, it also doesn't add the marker. Setting the breakpoint on the moveCamera line, it never gets accesed. Any help would be appreciated, I've been going mad over this issue. Thanks!
Please try this once inside your onMapReady method
CameraPosition cameraPosition = CameraPosition.builder()
.target(new LatLng(placeLatitude, placeLongitude))
.zoom(16)
.bearing(0)
.tilt(45)
.build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
where mGoogleMap is defined as
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
if you want to add Marker do this before moving the camera
mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(placeLatitude, placeLongitude)));
EDIT:
If you want to click on the map and move the camera
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
mGoogleMap.clear();
mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(latLng.latitude, latLng.longitude)));
CameraPosition cameraPosition = CameraPosition.builder()
.target(new LatLng(latLng.latitude, latLng.longitude))
.zoom(16)
.bearing(0)
.tilt(45)
.build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
to start with, I am completely confused with various api's available for location and map. So, I even dont know if the code is optimal for sdk 27.(I have minimum sdk 24 set.)
The problem is this piece of code shows the current location well and fine, butand the map gets updated when the location is changed. But, that is not reflected in location. See, the polyline drawn from LatLong does not follow the current location.
Also, I am trying to implement FusedLocationProviderClient but thats probably not the case here.
Any help will be very welcome.
public class SecondFragment extends Fragment implements OnMapReadyCallback {
//Color stroke = new Color(222.0,135.0, 135.0,174.0);
private GoogleMap mMap;
public static SecondFragment newInstance() {
SecondFragment fragment = new SecondFragment();
return fragment;
}
public GoogleMap getMap() {
return mMap;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, null, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
double latitude;
double longitude;
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
latitude = 0.0;
longitude = 0.0;
} else {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
latlang.Lat = latitude;
latlang.Lang = longitude;
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(latitude, longitude)).zoom(18).build();
double angle = Math.toRadians(93.833);
Point cPoint = mMap.getProjection().toScreenLocation(new LatLng(latitude,longitude));
System.out.println("mPoint X"+ cPoint.x);
System.out.println("mPoint Y"+ cPoint.y);
Point mPoint = new Point();
//Azimuth Pos only
double lat_azi = 2*Math.sin(angle)+cPoint.y;
double long_azi = 2*Math.cos(angle)+cPoint.x;
LatLng nat_azi =mMap.getProjection().fromScreenLocation(mPoint);
//private List<Point> mPoint = new ArrayList<Point>();
Marker marker = mMap.addMarker(new MarkerOptions()
.position(nat_azi)
.anchor(0.5f,0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.sun_pos_icon))
);
Marker marker_loc = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon))
);
mMap.addPolyline(new PolylineOptions()
.add(new LatLng(lat_azi, long_azi), new LatLng(latitude, longitude), new LatLng(0,0))
.width(15)
.color(Color.MAGENTA));
PathOfSun.getTime();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.getUiSettings().setZoomControlsEnabled(true); // true to enable
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
}
}
}
You can follow below link for Updating Marker position on the Map.
Move marker with gps in google map android
I'm new to programming in Android, I'm developing an application which shows some markers that I'm giving you by code, when adding a cluster, it marks me a few default points.
I would like to know how do I change those default points in the cluster and add the markers to the points I want?
private void addItems() {
double lat = 3.424014;
double lng = -76.536218;
for (int i = 0; i < 5; i++) {
double offset = i / 60d;
lat = lat + offset;
lng = lng + offset;
MyItem offsetItem = new MyItem(lat, lng);
mClusterManager.addItem(offsetItem);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
btnclute=(Button)findViewById(R.id.btn_cluster);
//cluster
btnclute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(3.422504, -76.538128), 13));
mClusterManager = new ClusterManager<MyItem>(getBaseContext(), mMap);
mMap.setOnCameraIdleListener(mClusterManager);
mMap.setOnMarkerClickListener(mClusterManager);
addItems();
}
});
}
/**
* 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;
mapa= googleMap;
// Add a marker in Sydney and move the camera
//LatLng sydney = new LatLng(-34, 151);
//Marker
//Estadio
LatLng home = new LatLng(3.429862, -76.541336);
dato=getResources().getString(R.string.estadio);
mMap.addMarker(new MarkerOptions().position(home).title(dato)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.estadio)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(home, 13));
//Sebastian Belalcazar
LatLng home1 = new LatLng(3.449151, -76.545185);
dato1=getResources().getString(R.string.sebas);
mMap.addMarker(new MarkerOptions().position(home1).title(dato1)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.sebastian)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(home1, 13));
//Cristo Rey
LatLng home2 = new LatLng(3.435855, -76.564840);
dato2=getResources().getString(R.string.rey);
mMap.addMarker(new MarkerOptions().position(home2).title(dato2)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.cristo)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(home2, 13));
//Tres cruces
LatLng home3 = new LatLng(3.467800, -76.545473);
mMap.addMarker(new MarkerOptions().position(home3).title(getResources().getString(R.string.cruces))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.tres)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(home3, 13));
//Plaza de Caicedo
LatLng home5 = new LatLng( 3.451864, -76.532479);
dato3=getResources().getString(R.string.plaza);
dato4="-" + getResources().getString(R.string.caicedo);
dato5="-" + getResources().getString(R.string.pedro);
dato6="-" + getResources().getString(R.string.palacio);
mMap.addMarker(new MarkerOptions().position(home5).title(dato3)
.snippet(dato4 + "\n" +
dato5 + "\n" +
dato6)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.plaza)));
mapa.moveCamera(CameraUpdateFactory.newLatLngZoom(home5, 13));
You need to set an algorithm so the clusters don't align in a grid, thus becoming more precise.
NonHierarchicalDistanceBasedAlgorithm<ClusterItem> algo = new NonHierarchicalDistanceBasedAlgorithm<>();
mClusterManager.setAlgorithm(algo);
//If that isn't enough you can change the latlng
Collection<ClusterItem> col = algo.getItems();
for (ClusterItem clusterItem : col) {
clusterItem.getPosition().latitude = yourNewLatitude;
clusterItem.getPosition().longitude = yourNewLongitude;
}
I'm trying to control Google map camera like this
private void setUpMap() {
Log.e(LOG_TAG, "in setup method");
mMap.setMyLocationEnabled(true);
LatLng startingPoint = new LatLng(129.13381, 129.10372);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(startingPoint, 16));
Log.e(LOG_TAG, "in Setup method" + (mMapFragment == null));
}
LogCat prints
"in setup method"
"in setup method false"
2 log is shown it means mMap.moveCamera(...) is called
setUpMap() call from here
private void setUpMapIfNeeded() {
mMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentByTag(MFragment.TAG);
if (mMapFragment != null) {
mMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
}
});
}
}
try this: hope it will work.
private void setUpMap() {
Log.e(LOG_TAG, "in setup method");
mMap.setMyLocationEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(15).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
Log.e(LOG_TAG, "in Setup method" + (mMapFragment == null));
}
Your coordinates specified at LatLng startingPoint = new LatLng(129.13381, 129.10372); seems to be a bit off. In more detail, the maximum latitude is 90 degrees, which is the north pole (-90 is the south pole).
The result of this will be that the camera will not move to a position which is invalid.
Try using coordinates from a known location, such as LatLng startingPoint = new LatLng(55.70, 13.19); which will give you the position of Lund, Sweden.
So basically, revise the latitude and longitude coordinates for your position.
I m working with google map. I want to get marker pointed to the current location of user by default.How can i do this.Here is my code and is there any way to get the map of India only on google map.plz help me..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_activity1);
MapFragment fm = (MapFragment) getFragmentManager()
.findFragmentById(R.id.fragment1);
// Getting Map for the SupportMapFragment
final GoogleMap map = fm.getMap();
if(map!=null){
map.setMyLocationEnabled(true);
}
if(map!=null){
Location myLocation = map.getMyLocation();
if(myLocation !=null){
LatLng myLatLng = new LatLng(myLocation.getLatitude(),
myLocation.getLongitude());
CameraPosition myPosition = new CameraPosition.Builder()
.target(myLatLng).zoom(17).bearing(90).tilt(30).build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(myPosition));
}
}
// Setting a click event handler for the map
map.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Clears the previously touched position
map.clear();
// Animating to the touched position
map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
map.addMarker(markerOptions);
double lat=latLng.latitude;
double longitude=latLng.longitude;
String LAT=String.valueOf(lat);
String LONGITUDE=String.valueOf(longitude);
Intent in = new Intent(getApplicationContext(),
LocationActivity.class);
// Sending lat/long to next activity
in.putExtra(TAG_LAT, LAT);
in.putExtra(TAG_LONG, LONGITUDE);
startActivityForResult(in, 100);
}
});
}
To get marker pointed to the current location, you can do like that:
Location myLcation = map.getMyLocation();
LatLng myPosition = new LatLng(myLcation.getLatitude(),myLcation.getLongitude());
MarkerOptions currentLocationMarker = new MarkerOptions()
.position(myPosition)
.title(/*YOUR TITLE*/)
.icon(BitmapDescriptorFactory.fromResource(R.drawable./*YOUR ICON*/));
map.addMarker(currentLocationMarker);
if you want to zoom on this position:
CameraUpdate location = CameraUpdateFactory.newLatLngZoom(myPosition, 6);
mMap.animateCamera(location);