below is my code which give hardcoded lat long of user i want to show dynamic latlong where ever user go map show current location of user how to do this
?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support_map_fragment);
FragmentManager fmanager = getSupportFragmentManager();
Fragment fragment = fmanager.findFragmentById(R.id.map);
SupportMapFragment supportmapfragment = (SupportMapFragment)fragment;
GoogleMap supportMap = supportmapfragment.getMap();
LatLng latLng = new LatLng(24.89337, 67.02806);
supportMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
supportMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my new spot!")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
supportMap.getUiSettings().setCompassEnabled(true);
supportMap.getUiSettings().setZoomControlsEnabled(true);
supportMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20));
}
Try adding this line:
supportMap.setMyLocationEnabled(true);
You obviously need to get the current location of the user. You need to use LocationListener to request continuous updates. You can specify the time interval or the distance interval between the location updates. This with give you a Location object from which you can extract the latitude and longitude. You can then use these 2 values to point the current location on the map. There are numerous questions and great answers on How to get the current location. You can start by reading:
Location Strategies Google's documentation
Some of the previous questions are:
How to get Latitude and Longitude of the mobile device in android?
how to get longitude and latitude in android
find current location latitude and longitude
How to get the current location latitude and longitude in android
Hope this helps.
Related
In my Android application i need to get the traveled road with car and i check it with google android directions API and GPS.
But the problem is that some times the GPS location is not precise and i can get an error of 10Km for some lecture and that means that in a total travel of 150km my "distance traveled" can be 250km and it's wrong!
Yesterday i test it in highway and the problem is that when the marker is located out from highway, the calculation of distance traveled from my current position and the last marker located by road is very wrong (in this case out of the highway).
There is some best way for getting traveled distance with car using the phone?
Maybe some better code for getting more precise GPS position?
Here is my code:
private void getUserLocation() {
Log.d(TAG, "getUserLocation()");
checkLocationPermission();
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
String stringStartLat, stringStartLng;
double lat = location.getLatitude();
double lng = location.getLongitude();
//Start position of device
if (travelInfo.getStartLat() == 0 && travelInfo.getStartLng() == 0) {
travelInfo.setStartLat(lat);
travelInfo.setStartLng(lng);
//Set lastcoordinates equals to start
travelInfo.setLastLat(lat);
travelInfo.setLastLng(lng);
}
//Current position of device
travelInfo.setCurrentLat(lat);
travelInfo.setCurrentLng(lng);
stringStartLat = Double.toString(travelInfo.getStartLat());
stringStartLng = Double.toString(travelInfo.getStartLng());
//Set the TextView in the fragment with start coordinates
Log.d(TAG,"LatitudeStart: " + stringStartLat);
Log.d(TAG,"LongitudeStart: " + stringStartLng);
if (startMarker == null) {
//Add the user location to the map with a marker
LatLng userLoction = new LatLng(travelInfo.getStartLat(), travelInfo.getStartLng());
startMarker = googleMap.addMarker(new MarkerOptions()
.position(userLoction)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
.title("Start Position")
.snippet("Show the start position of user"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(userLoction).zoom(9).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else {
LatLng currentLocation = new LatLng(travelInfo.getCurrentLat(), travelInfo.getCurrentLng());
currentPositionMarker = googleMap.addMarker(new MarkerOptions()
.position(currentLocation)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
.title("Current Position")
.snippet("Show the current position of user during travel"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(currentLocation).zoom(11).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
if (travelInfo.getEndLat() != 0 && travelInfo.getEndLng() != 0) {
Log.i(TAG, "Dentro if userlocation");
//Get total distance of travel
getTotalDistanceTime(travelInfo);
//Get the percurred distance from last known coordinates
getPercurredDistance(travelInfo);
}
}
}
});
}
And getpercurredDistance use google direction API with this url
String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + obj.getLastLat() + "," + obj.getLastLng() + "&destination=" + obj.getCurrentLat() + "," + obj.getCurrentLng() + "&mode=driving&key=AI*******************I";
For getting distance traveled from last marker and current position marker.
But some times it put the localized position too far from real position... how avoid this?
EDIT
The method that i use is good for my work? mFusedLocationClient.getLastLocation()
There is no possibilities to get more precise GPS position from GPS sensor of android device, but you can filter "wrong" points this ways:
1) for each travel point get several values of Lat and Lng, discard the minimum and maximum and average the remaining ones;
2) log timestamps of each travel point and compare it for two neighboring points: speed (distance between that two points divided by time interval of that points) grater than max. car speed (e.g. 250 km/h) that means the second point is wrong (if first point is good of course).
3) use Google Maps Roads API to find best-fit road geometry for a given set of GPS coordinates.
Also take a look at this question.
For real-time location purposes, location updates allow you to request location updates at different intervals. See the android developer location documentation. The function you want is FusedLocationProviderClient.requestLocationUpdates.
There is no reason GPS (or any other widely used location technology) should ever give you 10km error for a single location estimate. If you are getting this, there is a large mismatch between when you the location estimate was made and when you are requesting it.
I am getting the place name of google maps using
Place place = PlaceAutocomplete.getPlace(MainActivity.this, data);
Logger.e("The ", "Place: " + place.getName());
now i want to set the marker at this place name. How can I acheive this?
First try to get the latitude and longitude from place name using Geocoder after that try following code for showing the marker on the map.
GoogleMap map;
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.addMarker(new MarkerOptions()
.position(new LatLng(placelatitude, placeLongitude))
.title("Place Name"));
Here i am able to display User on google map by getting user latitude and longitude now i want to display near by events happening in user location and want to display nearby venues so chosen foursquare api.here it is
2nd one
Here is my code to display user on map
R.id.map)).getMap();
// Creating location manager and location classes instances
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
;
mCurrentLocation = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// if location found display as a toast the current latitude and
// longitude
if (mCurrentLocation != null) {
Toast.makeText(
this,
"Current location:\nLatitude: "
+ mCurrentLocation.getLatitude() + "\n"
+ "Longitude: " + mCurrentLocation.getLongitude(),
Toast.LENGTH_LONG).show();
USER_LOCATION = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
// adding marker
googleMap.addMarker(new MarkerOptions().position(USER_LOCATION).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)).title("Your current location"));
// Move the camera instantly to hamburg with a zoom of 15.
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(USER_LOCATION, 12));
// Zoom in, animating the camera.
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
give me a brief idea how to use that api.based on my code.
Sorry, but do you want a complete tutorial for copy&paste?
You managed to get a location, you have a documentation of the api you want to use... so use it?
Take the location you have from Android. Format it so that the api can use it (perhaps they need coordinates, perhaps a city name, ...) and then call the web service. You will get a result and have to interpret it.
Where is actually your problem?
I'm currently having a map, and each 10 meters I use LocationListener to refresh my location and get the new Latitude and Longitude. Now I wish that the route the user is taking will be displayed with a red line. So everytime the OnLocationChange() from LocationListener class is called, I want to update the map with a line between the last location and the new location.
So far I've added the following:
private void initializeDraw() {
lineOptions = new PolylineOptions().width(5).color(Color.RED);
lineRoute = workoutMap.addPolyline(lineOptions);
}
during the OnLocationChanged I call this:
drawTrail();
now what should I insert into this function so that each time it adds the newly attained location as a point and draws a line from the last to the new point.
Thanks
First translate Location into LatLng:
LatLng newPoint = new LatLng(location.getLatitude(), location.getLongitude());
Then add a point to existing list of points:
List<LatLng> points = lineRoute.getPoints();
points.add(newPoint);
lineRoute.setPoints(points);
Here is my app:
public class HlavnaAktivita extends MapActivity implements LocationListener {
...
public void onLocationChanged(Location location) {
Log.w("myApp", String.valueOf(location.getLatitude()));
}
When I give to emulator for example 48.590007 and 17.824579, it just write "17.0". I tried http://www.androidcompetencycenter.com/?s=GPS this tutorial (from StackOverflow) and when I run that app, it write good postition, but on map is just rounded position (17, 48) (position according to maps.google.com is good, but on map is cca 100km wrong).
What could be the problem? I tried a lot of tutorials but it's still not working.
To get the exact position on the map you need 2 parameters:
Latitude and Longitude of a Point.
GeoPoint accepts latitude and longitude in microdegrees so try to create your point like this to get better accuracy:
double lati = location.getLatitude();
double longi = location.getLongitude();
GeoPoint geo_point= new GeoPoint((int)(lati * 1e6),(int)(longi * 1e6));
It converts somewhere your number to int. To avoid it try someting like:
Log.w("myApp", String.valueOf((float) location.getLatitude()));
This was just my mistake - I forget to add (). Sorry.