I would like to make the map auto-focus to the current location and I've obtained the location via Location Kit.
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
Now, I was trying to set the latitude and longitude of the camera in OnMapReady() function, but how to retrieve them?
#Override
public void onMapReady(HuaweiMap huaweiMap) {
float zoom = 12.0f;
LatLng latLng = new LatLng(***mLat***, ***mLong***);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
.
.
.
}
I really need your assistance!!
Update
There is a official demo show how to realize this:
use location kit to get the current location
use map kit to show current location point in map
You can try to use the function moveCamera or animateCamera to make the map move to the location you want :
#Override
public void onMapReady(HuaweiMap huaweiMap) {
float zoom = 12.0f;
LatLng latLng = new LatLng(***mLat***, ***mLong***);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
huaweiMap.moveCamera(cameraUpdate);
}
Related
I hope you can help me. My current app is able to get my current location (via GPS). Now I add a marker to my current location which works perfect, but if I want to move my camera to the marker it doesn't work. The inputs for the moveCamera(positon); are the same as for addMarker(position);
here is my code:
//center is used when no location is available (Berlin)
final CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(52.5075389,13.5231758));
final CameraUpdate zoom = CameraUpdateFactory.zoomTo(14);
//get location from other activity
final Bundle extras = getIntent().getExtras();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapfragment);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng position = new LatLng(52.5075389,13.5231758);
if (extras != null) { //if location available
position = (LatLng)extras.getParcelable("location");
final CameraUpdate centerLocation = CameraUpdateFactory.newLatLng(position);
MarkerOptions markerOptions = new MarkerOptions().position(position).title(MARKER_TITLE).snippet(MARKER_SNIPPET);
googleMap.addMarker(markerOptions);
googleMap.getUiSettings().setMapToolbarEnabled(false); //hide auto created buttons
googleMap.moveCamera(centerLocation);
googleMap.animateCamera(zoom);
}
else{
//some other code here
}
My marker is at the correct position, but my centerLocation don't. Any suggestions?
thanks to the comments. here is my solution:
final float zoom = 14;
//rest of the code is unchaged
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, zoom));
I am creating an app with a google maps and a circle radius centered on the user’s location. I want the user to choose the desired radius of the circle with a spinner (1-10 km radius). But when I use the value from my spinner the radius circle doesn't appear.
For the location I can get the blue dot showing my appearance by: map.setMyLocationEnabled(true); and I can manually enter a location for map to zoom into. But when I try to zoom into and set center of circle on the device location I get a nullpointerexception error. Below is my code for the location and the toast is just for me to see that I get the actual location.
private void getDeviceLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
Task<Location> task = mFusedLocationClient.getLastLocation();
task.addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
Toast.makeText(MainActivity.this, "Current Position " + currentLocation.getLongitude(), Toast.LENGTH_LONG).show(); //Just to make sure we have a value
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map2);
supportMapFragment.getMapAsync(MainActivity.this);
}
}
});
}
Then I use userPosition for map to zoom into and set center of circle
public void onMapReady(GoogleMap map) {
LatLng userPosition = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
mGoogleMap = map;
map.setMyLocationEnabled(true);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(userPosition, 10f));
map.addCircle(new CircleOptions()
.center(userPosition)
.radius(mapRadius)
.strokeColor(0x330073FF)
.fillColor(0x330073FF)
.strokeWidth(2));
map.getUiSettings().setZoomControlsEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(true);
}
But here I get the error on the line userPosition: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.test.MainActivity.onMapReady(MainActivity.java:362).
I got the code from a tutorial and it seems to work for them and tried many different tutorials as well with slightly different code so not sure what I do wrong. I have tried searching and know others had similar problems but still haven't gotten it to work.
As for the radius, it works fine when I set a manual location and write It works well if I write the radius myself in meters. But if I try to use my spinner and the mapRadius value, the radius circle doesn’t show up at all when I run the emulator. This is the code that is in onCreate
spinnerRadius = findViewById(R.id.spinner_radius);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.spinner_radius_option, android.R.layout.simple_spinner_item);
spinnerRadius.setAdapter(spinnerAdapter);
spinnerRadius.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mapRadiusInput = parent.getItemAtPosition(position).toString();
mapRadius = Double.parseDouble(mapRadiusInput)*1000; //converting to meters
Toast.makeText(MainActivity.this, ""+mapRadius, Toast.LENGTH_LONG).show();
}
I am a beginner when it comes to programming and android and I spent quite a bit on time on these two problem and it wouldn’t surprise me if it is easy to solve. Any help or pointers would be greatly appreciated.
When you add the circle, save the return value (Circle) in a field variable, Circle myCircle.
Then in the onItemSelected update the circle radius with the value (in meters).
So, first declare the variable as a class field variable (for scope visibility later). I'm assuming this is all in one class - if not you'll need to make this variable accessible to the onItemSelected callback instance.
private Circle myCircle;
Then when adding the circle, save it:
myCircle = map.addCircle(new CircleOptions()
.center(userPosition)
.radius(mapRadius)
.strokeColor(0x330073FF)
.fillColor(0x330073FF)
.strokeWidth(2));
And in your onItemSelected, update the circle (in meters)
myCircle.setRadius(mapRadius);
Here's another example showing same thing: https://stackoverflow.com/a/38454501/2711811
And API doc: https://developers.google.com/android/reference/com/google/android/gms/maps/model/Circle.html#setRadius(double)
The key is to save the Circle when it's created. And as you can see from the API, with the Circle reference there are other setters which can be used.
I am having trouble figuring how to get the distance between 2 non fixed locations. The first location is my current location and the second is the latest current location after walking say 100 meters. Below is a snippet of code.
/**
* Callback that fires when the location changes.
*/
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
updateUI();
}
/**
* Updates the latitude, the longitude, and the last location time in the UI.
*/
private void updateUI() {
latitude = mCurrentLocation.getLatitude();
longitude = mCurrentLocation.getLongitude();
mLatitudeTextView.setText(String.format("%s: %f", mLatitudeLabel,latitude));
mLongitudeTextView.setText(String.format("%s: %f", mLongitudeLabel, longitude));
}
So below I have my mCurrentLocation but how do I get the newCurrentLocation so I use the distanceTo method.
double distance = mCurrentLocation.distanceTo(newCurrentLocation);
Any suggestions would be much appreciated.
You'll have to save the current location in a temporary variable, something like this:
public void onLocationChanged(Location location) {
Location temp = mCurrentLocation; //save the old location
mCurrentLocation = location; //get the new location
distance = mCurrentLocation.distanceTo(temp); //find the distance
updateUI();
}
My MapActivity records a polyline just fine however when I tip the screen on it's side and the orientation changes the polyline disappears? What could be causing this? Here is my code that is recording the polyline:
Location lastLocationloc;
private GoogleMap myMap;
#Override
public void onLocationChanged(Location location) {
if (lastLocationloc == null) {
lastLocationloc = location;
}
LatLng lastLatLng = locationToLatLng(lastLocationloc);
LatLng thisLatLng = locationToLatLng(location);
//Log.e(TAG, "Last LatLng is :"+lastLatLng);
//Log.e(TAG, "Last LatLng is :"+thisLatLng);
myMap.addPolyline(new PolylineOptions().add(lastLatLng).add(thisLatLng).width(10).color(Color.RED));
lastLocationloc = location;
}
How can I prevent this from happening?
You have to save your points and restore them later. One simple way is to use onSaveInstanceState which will keep your data across configuration changes and process being killed. Other options are files and DB. More info here: http://developer.android.com/guide/topics/data/data-storage.html
I have a map that I want to put a marker on, but the marker isn't showing up. Here is my code:
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
public class MapDetailActivity extends MapActivity
{
private final static String TAG = MapDetailActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.map_view);
// get longitude and latitude values from detail activity/object
Bundle bundle = this.getIntent().getExtras();
float latitude = bundle.getFloat("uie.top25.seattle.latitude");
float longitude = bundle.getFloat("uie.top25.seattle.longitude");
Log.i(TAG, "Latitude that is set : " + latitude);
Log.i(TAG, "Longitude that is set : " + longitude);
// create longitude and latitude map points
Double lat = latitude * 1E6;
Double lon = longitude * 1E6;
// create point on map
GeoPoint point = new GeoPoint(lat.intValue(), lon.intValue());
OverlayItem oi = new OverlayItem(point, null, null);
MapView mapView = (MapView) this.findViewById(R.id.myMapView);
MapController mapController = mapView.getController();
// set point on map
mapController.animateTo(point);
oi.setMarker(oi.getMarker(R.drawable.mm_20_red));
// set zoom level
mapController.setZoom(19);
}
#Override
protected boolean isRouteDisplayed()
{
// No driving directions, so this method returns false
return false;
}
}
Can someone tell me what I am doing wrong?
You must add your item to map using https://developers.google.com/maps/documentation/android/hello-mapview this documentation Part-2
You need to create an Overlay to display a marker, read this:
https://developers.google.com/maps/documentation/android/reference/com/google/android/maps/Overlay
If you couldn't be bothered reading all of that here's a ready to use tutorial:
http://android-er.blogspot.com/2009/11/display-marker-on-mapview-using.html
You will need to go through the documentation and examples, but the basic steps are:
1-Create your itemizedOverlay by extending the itemizedOverlay from google maps.
2-Add an overlay Item to your Itemized overlay, and set the marker or use the default one defined in the previous step.
3-Add the itemized overlay to the mapview overlays with:
mapview.getoverlays().add(myItemizedOverlay);
Just after you have add the overlay to the mapview overlays list, the overlay will be considered by mapview to be called for drawing on screen (calling the onDraw method)
good luck.