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);
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.
What is LatLngBounds object used for in Google Places Autocomplete API?
.. and/or what does it mean by :
biasing the results to a specific area specified by latitude and longitude bounds
?
In the Google Places Autocomplete docs, it says to pass in LatLngBounds and AutocompleteFilter .
PendingResult<AutocompletePredictionBuffer> result =
Places.GeoDataApi.getAutocompletePredictions(
mGoogleApiClient, query, bounds, autocompleteFilter);
In using the Places Autocomplete, I can see how the AutocompleteFilter restricts results, say by country. What's not clear is how LatLngBounds is being used. In the example code there is this for the Bounds object:
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW =
new LatLngBounds(
new LatLng(37.398160, -122.180831),
new LatLng(37.430610, -121.972090));
It says the bound is to Mountain View (a city in SF Bay Area California), yet I can still get results for other countries when filter is null.
From this resource:
https://developers.google.com/places/android-api/autocomplete
Your app can get a list of predicted place names and/or addresses from the autocomplete service by calling GeoDataApi.getAutocompletePredictions(), passing the following parameters:
Required: A LatLngBounds object, biasing the results to a specific area specified by latitude and longitude bounds.
Optional: An AutocompleteFilter containing a set of place types, which you can use to restrict the results to one or more types of place.
Suppose you want to search Cafe The Coffee Day, If you set LatLngBounds result will be display according to that location.
E.g If you set LatLngBounds in New York and you search cafe coffee day, you will see results of New York. If you set LatLngBounds of Sydney you will see results of Sydney.
Now If you want to set LatLngBounds to your location, then you have to get current location and set LatLngBounds according to that.
You can also specify radius for getting a specific result.
For Example.
I am using below code to get result of my current city.
protected GoogleApiClient mGoogleApiClient;
private PlaceAutocompleteAdapter mAdapter;
AutoCompleteTextView autoTextViewPlace;
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(Places.GEO_DATA_API)
.build();
// I am getting Latitude and Longitude From Web API
if((strLatitude != null && !strLatitude.trim().isEmpty()) && (strLongitude != null && !strLongitude.trim().isEmpty())){
LatLng currentLatLng = new LatLng(Double.parseDouble(strLatitude), Double.parseDouble(strLongitude));
if(currentLatLng != null){
setLatlngBounds(currentLatLng);
}
}
public void setLatlngBounds(LatLng center){
double radiusDegrees = 0.10;
LatLng northEast = new LatLng(center.latitude + radiusDegrees, center.longitude + radiusDegrees);
LatLng southWest = new LatLng(center.latitude - radiusDegrees, center.longitude - radiusDegrees);
LatLngBounds bounds = LatLngBounds.builder().include(northEast).include(southWest).build();
mAdapter = new PlaceAutocompleteAdapter(getActivity(), mGoogleApiClient, bounds,
null);
autoTextViewPlace.setAdapter(mAdapter);
}
I'm using MapQuest (since Google Map API will be down in september) and I'd like to add a point at an exact coordinates position.
I've created a movieClip named geoPoint and traced a circle in it.
Now, I've managed to display the coordinates in a text field like that :
if (Geolocation.isSupported){
var my_geo:Geolocation = new Geolocation();
my_geo.addEventListener(GeolocationEvent.UPDATE, onGeoUpdate);
my_geo.setRequestedUpdateInterval(50);
var my_txt:TextField = new TextField();
my_txt.wordWrap=true;
addChild(my_txt);
}
function onGeoUpdate(e:GeolocationEvent):void{
my_txt.text = "My Latitude is "+e.latitude+" and my Longitude is "+e.longitude;
}
Now is it possible to add my movieClip at the e.latitude and e.longitude point ?
I've tried :
var geo:MovieClip;
geo = new geoPoint;
addChild(geo(new LatLng(e.latitude, e.longitude)));
but it doesn't work.
Someone knows how can I do it ?
Thanks !
It should be
geo = new geoPoint();
You should also probably figure how to translate latitude and longitude to x and y coordinates, because I'm doubtful the next line will work. You're calling a MovieClip constructor that takes a LatLng argument.
For what you need to achive, you may have to use a class provided by the MapQuest Api, like PolygonOverlay or CircleOverlay. There is an example here under "Shape Collections" http://developer.mapquest.com/content/as3/v7/7.0.6_MQ/samples/samplesexplorer/index.html#
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.
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?