how to change marker position on location change in android - java

I have a Marker on the map and I need to change the position of marker.
Here is my code:
public void onLocationChanged(Location location) {
map.clear();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (Home_Activity.this.markerob != null) {
Home_Activity.this.markerob.remove();
markerob.setPosition(latLng);
}
latitude=location.getLatitude();
longitude=location.getLongitude();
CameraUpdate cameraUpdate =CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(18.0f).build());
MarkerOptions options = new MarkerOptions().position(latLng);
//options.title( getAddressFromLatLng( latLng ) );
options.icon(BitmapDescriptorFactory.fromBitmap(Bitmap.createScaledBitmap(
BitmapFactory.decodeResource(getResources(),
spmain.getavatarimage()), 90, 90, false)));
//map.addMarker(new MarkerOptions().position(latLng));
Toast.makeText(getApplicationContext(), "lat="+latLng,Toast.LENGTH_SHORT).show();
options.position(latLng);
map.getUiSettings().setRotateGesturesEnabled(true);
map.animateCamera(cameraUpdate);
map.moveCamera(cameraUpdate);
map.addMarker(options);
//locationManager.removeUpdates(this);
}
I have added onLocationChanged method and in that, am getting location details but not move the marker on new location.

Check whether your map has marker added on not (for the very first time). If not then add marker and keep the reference to that marker. For subsequent calls to onLocationChanged just use the same reference to update the latitude and longitude.
Marker myMarker;
if(myMarker == null){
marker = map.addMarker(options);
}
else {
marker.setPosition(new LatLng(location.getLatitude(),location.getLongitude()));
}
Hope this helps. Let me know it this does not work. Will post more relevant code.

Related

DistanceTo Crashes application when running [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to get the difference between 2 locations of which i have taken from the gps, Whenever i click on a button to go to my MapsActivity i get crashed with this error
Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
And When i comment the code which checks difference in distance it works just fine, i don't understand the connection between the Marker options and the DistanceTo
Here's my Code (Keep in mind that all works fine it's just the DistanceTo which doesn't work)
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get the latitude and longitude from the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
if(location != null)
// this gives address list from the maps, not important and commented
{
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
// Marker options where the issue occurs
//String result = addresses.get(0).getSubLocality()+":";
//result += addresses.get(0).getLocality()+":";
// result += addresses.get(0).getCountryCode();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker Title"));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
} catch (IOException e) {
e.printStackTrace();
}
//Where it checks for the locations and the distance between them
if(LocationA == null) {
LocationA = location;
}
LocationB = location;
LocationA = LocationB;
DiffernceInDistance = LocationA.distanceTo(LocationB);
}
Code where i made the Map
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
The issue was that i was asking for locations and also applying a marker at the same time, so markers couldn't load to the location, to solve it I commented, It doesn't crash anymore but it didn't solve my main issue (DistanceTo not working but that's not the reason i made this post therefore i won't ask for anymore help thanks )
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker Title"));

search location name in google map

I tried to search location name in google map activity.here in onsearch method address.getLatitude() and address.getLongitude are not work.its show red text.anyone please solve my error. below my code
public void onSearch(View view)
{
EditText location_tf = (EditText)findViewById(R.id.TFaddress);
String location = location_tf.getText().toString();
List<Address> addressList = null;
if(location != null || !location.equals(""))
{
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location , 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude() , address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(0,0);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
It seems that, you have either imported the wrong Address class or not imported at all. The class which you are looking for can be imported using following line:
import android.location.Address;
The above class contains getLatitude() and getLongitude() methods. Another package which also contains Address class, which I guess, by mistake you imported is following:
com.google.android.gms.identity.intents

Problems displaying a location and centering the camera on it

I've just had some issues for odd reasons with the CameraUpdateFactory.
So I incorporated this code in an onclickListener on the GpsButton on a navigation fragment:
if (ContextCompat.checkSelfPermission(mapFragment.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
Log.d("Permission checked", "checkSelfPermission passed with no errors");
map.setMyLocationEnabled(true);
Log.d("Permission checked", "Location Layer implementation successful");
} else {
//Request the Permission
ActivityCompat.requestPermissions(mapFragment.getActivity(), new String[]{
Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
This basically enables the location to be displayed as a blue dot on the map only when the GPS button is pressed. This has been perfectly functional so far.
I also incorporated a method to move the camera to my current location:
public void locateMe() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE); // Getting LocationManager object from System Service LOCATION_SERVICE
Criteria criteria = new Criteria();// Creating a criteria object to retrieve provider
String provider = locationManager.getBestProvider(criteria, true);// Getting the name of the best provider
if (ContextCompat.checkSelfPermission(mapFragment.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mapFragment.getActivity(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 2);
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
double latitude = location.getLatitude(); //Getting latitude of the current location
double longitude = location.getLongitude(); // Getting longitude of the current location
myPosition = new LatLng(latitude, longitude); // Creating a LatLng object for the current location
map.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition, CAMPUS_DEFAULT_ZOOM_LEVEL));//Camera Update method
}
}
For some reason, this is hit or miss. 3 days ago, it was locking on a position that wasn't where I currently was located while for the past 2 days it worked perfectly. No code was changed whatsoever. Could someone please explain what's going on? Any fixes or suggestions would be appreciated.
This occurs because you are using getLastKnownLocation.
This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.
If the provider is currently disabled, null is returned.
documentation
You have to use requestLocation updates if you want to retrieve the user's current documentation.
requestLocationUpdates documentation

How do I combine Google Maps and Location Services?

I have an Activity that gets position with fused location and puts it in two text boxes.
In a frame, I have a Google map.
In two text boxes, I have my latitude and longitude.
I want map center to adjust as location changes.
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
latitud.setText(String.valueOf(mCurrentLocation.getLatitude()));
longitud.setText(String.valueOf(mCurrentLocation.getLongitude()));
tiempo.setText(mLastUpdateTime);
}
My idea was adding to onLocationChanged something like this:
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
latitud.setText(String.valueOf(mCurrentLocation.getLatitude()));
longitud.setText(String.valueOf(mCurrentLocation.getLongitude()));
tiempo.setText(mLastUpdateTime);
LatLng mapCenter = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLatitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mapCenter, 16));
// Flat markers will rotate when the map is rotated,
// and change perspective when the map is tilted.
googleMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.flecha))
.position(mapCenter)
.flat(true)
.rotation(245));
CameraPosition cameraPosition = CameraPosition.builder()
.target(mapCenter)
.zoom(16)
.bearing(90)
.build();
// Animate the change in camera view over 2 seconds
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
2000, null);
}
But is giving me the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.moveCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference

Not able to display path from current location to destination google maps V2

I am trying to draw path from current location to destination using the answer Android: How to draw route directions google maps API V2 from current location to destination.
But in place of the hard coded I longitude and Latitude of the current location I want to use my real location. But whenever I try to do that, the App is crashing with error in line location = mMap.getMyLocation();
Any help is appreciated.
MapsActivity.Java
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
Location location;
LatLng myPosition;
GMapV2Direction md;
LatLng fromPosition = getYourLocation();
LatLng toPosition = new LatLng(13.683660045847258, 100.53900808095932);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
md = new GMapV2Direction();
setUpMapIfNeeded();
LatLng coordinates = new LatLng(13.685400079263206, 100.537133384495975);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));
mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));
Document doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);
int duration = md.getDurationValue(doc);
String distance = md.getDistanceText(doc);
String start_address = md.getStartAddress(doc);
String copy_right = md.getCopyRights(doc);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for(int i = 0 ; i < directionPoint.size() ; i++) {
rectLine.add(directionPoint.get(i));
}
mMap.addPolyline(rectLine);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
/*myPosition = getLocation();
ZoomCurrentLocation(myPosition);*/
}
}
}
private LatLng getYourLocation() {
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
// 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);
return latLng;
}
private void ZoomCurrentLocation(LatLng myPosition)
{
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 16));
}
private void setUpMap(LatLng myPosition) {
mMap.addMarker(new MarkerOptions().position(myPosition).title("Marker"));
}
}
Do you mean location = mMap.getMyLocation(); is the method getYourLocation() in the code, and the crash is at Location location = locationManager.getLastKnownLocation(provider); ?
If so, it may cause by NullPointer Exception, you need use new api FusedLocationApi to avoid getLastLocation null pointer.
Please check here to know how to use it. And here is the code for it on my github.
For the destination you can check here to get some idea.

Categories