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);
}
Related
I have multiple locations that I need to display on my map.
I want the info/label for each marker to display on the maps along with the pin icon whether the marker/pin is clicked or not by the user.
I have the following code to display the markers.
for (DepartmentLocation loc : departmentLocations) {
if (loc != null && loc.getLatitude() != null && loc.getLongitude() != null) {
LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title(loc.getName());
markerOptions.visible(true);
Marker marker = googleMap.addMarker(markerOptions);
marker.showInfoWindow();
marker.setVisible(true);
markers.add(marker);
}
}
But still, I see only the red pins and no labels beside the pin.
Here is how my maps look like. I can see only one info label, not the others.
I have tried using the IconGenerator from the map utils.
implementation 'com.google.maps.android:android-maps-utils:0.5'
for (DepartmentLocation loc : departmentLocations) {
if (loc != null && loc.getLatitude() != null && loc.getLongitude() != null) {
LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
MarkerOptions markerOptions = new MarkerOptions()
.icon(BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon(loc.getName())))
.position(latLng)
.title(loc.getName());
markerOptions.visible(true);
Marker marker = googleMap.addMarker(markerOptions);
marker.showInfoWindow();
marker.setVisible(true);
markers.add(marker);
}
}
When I use iconfactory, I am unable to show both the pin and the info label.
Only one InfoWindow is displayed at a time on GoogleMap. You can't display multiple InfoWindow at a time.
You have to use IconGenerator for that. You can set a view to IconGenerator and make a Bitmap form that view. You can make a view that contains both Marker and your InfoWindow View. Use that view to crate your Desired Marker.
You can check this answer
From the documentation, there is a text saying that the info window is shown one at a time, so there is no way to do that:
"An info window allows you to display information to the user when they
tap on a marker. Only one info window is displayed at a time. If a
user clicks on a marker, the current info window will be closed and
the new info window will be displayed. Note that if the user clicks on
a marker that is currently showing an info window, that info window
closes and re-opens."
You can read more here: https://developers.google.com/maps/documentation/android-sdk/infowindows
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'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#
Well I Have implemented kataklisma / android-google-places library
for parsing the Google places API data, but I cant find the Following methods
place.getLatitude();
place.getLongitude();
I m getting all these
place.getName()
place.getFormattedAddress()
place.getIcon()
place.getId()
place.getReference()
place.getVicinity()
via following code successfully
if (result.getStatusCode() == StatusCode.OK) {
List<Place> placesList = (List<Place>) result.getResults();
for (Place place : placesList) {
StaticParsedData.PLACE_NAMEs.add(place.getName());
StaticParsedData.PLACE_FORMATED_ADDRESSEs.add(place
.getFormattedAddress());
StaticParsedData.PLACE_ICONs.add(place.getIcon());
StaticParsedData.PLACE_IDs.add(place.getId());
StaticParsedData.PLACE_REFRENCEs.add(place.getReference());
StaticParsedData.PLACE_VISINITIEs.add(place.getVicinity());
}
but i need to get the Latitude and Longitude of the places also,But I cant find any method to get latitude and Longitude values. I don't think that following methods are available in this library.
place.Latitude();
place.Longitude();
May be I am doing wrong. can any body guide me regarding this. how to get Latitude and Longitude of any place via this library
Also here is an image of the library showing the packages hierarchy and its libs
Or is there any other Robust library for parsing the data of Google Places API
I solved my problem. Yes I was doing wrong. To get latitude and longitude of the place we have to extract it from Geometry object like this.
First you have to get Object of the Geometry like this
if (result.getStatusCode() == StatusCode.OK) {
List<Place> placesList = (List<Place>) result.getResults();
for (Place place : placesList) {
StaticParsedData.PLACE_GEOMETERIEs.add(place.getGeometery());
}
and then extract the individual latitude and longitude of any place like this
for (int i = 0; i < StaticParsedData.PLACE_NAMEs.size(); i++) {
Geometry geometry = StaticParsedData.PLACE_GEOMETERIEs
.get(i);
com.a2plab.googleplaces.models.Place.Location location = geometry.location;
Double lat = location.lat;
Double lng = location.lng;
MarkerOptions placesIndicater = new MarkerOptions()
.icon(placeMarkerIcon)
.title(StaticParsedData.PLACE_NAMEs
.get(i))
.snippet(
StaticParsedData.PLACE_VISINITIEs
.get(i))
.position(new LatLng(lat, lng));
placeMarker = map
.addMarker(placesIndicater);
placeMarkerRef.add(placeMarker);
}
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);