Android: Why does a new instance of Location require a provider? - java

I have a lot of geo data stored online with latitude and longitude and I'd like to use the distanceTo method instead of my own haversine formula.
So I need to put each record into a Location field, but here's my question: it requires a "provider" string. Why? What will Android do with that information?
for (ArrayList<String> item : Places_Data) {
Location itemloc = new Location("provider");
itemloc.setLatitude(latIn);
itemloc.setLongitude(lonIn);
//do something with my new location
}

From the source code for Location, it doesn't use the string to do anything meaningful. It just uses it to describe the Location internally. If you do Location#toString(), it prints out the co-ordinates, the provider and other details (accuracy, etc). That's all it's used for, internal description.
You can make the provider anything, as seen in this answer: Creating Android Location Object

Use correctly the way
package android.location.LocationManager
Location location = new Location(LocationManager.GPS_PROVIDER);
Use NETWORK_PROVIDER o GPS_PROVIDER
https://developer.android.com/reference/android/location/LocationManager.html#GPS_PROVIDER
https://developer.android.com/reference/android/location/LocationManager.html#NETWORK_PROVIDER

Related

HERE API - TMC to Coordinates

I've been using the HERE Java library to decode binary TPEG files, however I am running into trouble when trying to get locations from the TMC location reference.
I'd like to be able to take the TMC reference (location id, country code, location table version) and get lat/long coordinates. Unfortunately, after pouring through HERE's API docs, I can't seem to find an API that would do this for me.
Once you have a TMCLocationReference, you can transform it to a LinearLocation using LocationReferenceResolvers.tmc method.
There should be an example in Resolving a Location Reference section.
The resolver allows you to transform the TMCLocationReference into a LinearLocation containing internal HERE maps ids, which can be transformed to WKT like LineStrings using for instance the PropertyMaps.geometry method, for which you can find more details in the dev guide.
As an example, you could do something like this:
StandaloneCatalogFactory scf = new StandaloneCatalogFactory();
Catalog optimizedMap = scf.create(OptimizedMap.v2.HRN);
CacheManager cacheManager = CacheManager.withLruCache();
LocationReferenceResolver<TMCLocationReference, BidirectionalLinearLocation> tmcResolver =
LocationReferenceResolvers.tmc(optimizedMap, cacheManager);
TMCLocationReference tmcLocationReference = ...
BidirectionalLinearLocation linearLocation = tmcResolver.resolve(tmcLocationReference);
PropertyMap<Vertex, LineStringHolder<GeoCoordinate>> geometry =
PropertyMaps.geometry(optimizedMap, cacheManager);
LineStringHolder<GeoCoordinate> lineString =
geometry.get(linearLocation.getLocation().getPath().get(0));

Can Google's Places API findCurrentPlace method be used to get the exact current address, rather than the address of the closest 'Place'?

I am currently using the Google Places API within my (Java) Android application to get the current device location and display it into an editText. Currently when I make the call to placesClient.findCurrentPlace(request), a list of the closest places and the likelihood of the device being there are returned, like so:
Place 'XXXXXXX' has likelihood: 0.600000
Place 'YYYYYYY' has likelihood: 0.0500000
Place 'ZZZZZZZ' has likelihood: 0.00000
Where the places are things like "Thames River" or "Telus Stadium". I can then get the address from each of these from the response. My question is, is there any way to get back the address of the phones current location, opposed to the address of the closest 'Place'?
I have done something similar with the Places Autocomplete so that it suggests addresses rather than places, which works very well. Getting the current place is done in a slightly different way though, and therefore I can't seem to make the same change.
The reason that I am attempting to do this using the Places API is because I have a start and end location AutoCompleteEditText which the user can type into. They can choose to have their current location shown in the Start Location AutoCompleteEditText, and I was hoping to show the address in the same format as it would be in if they had typed in the address and clicked it using the Places AutoComplete.
Here is the code currently being used to get the address of the closest place, which I would like to modify to get the address the phone is currently at.
List<Place.Field> placeFields = Collections.singletonList(Place.Field.ADDRESS);
FindCurrentPlaceRequest request = FindCurrentPlaceRequest.newInstance(placeFields);
...
Task<FindCurrentPlaceResponse> placeResponse = placesClient.findCurrentPlace(request);
placeResponse.addOnCompleteListener(new OnCompleteListener<FindCurrentPlaceResponse>() {
#Override
public void onComplete(#NonNull Task<FindCurrentPlaceResponse> task) {
if (task.isSuccessful()) {
FindCurrentPlaceResponse response = task.getResult();
for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) {
Log.i(LOG_TAG, String.format("Place '%s' has likelihood: %f",
placeLikelihood.getPlace().getAddress(),
placeLikelihood.getLikelihood()));
}
} else {
Log.e(LOG_TAG, "Error finding current location");
}
}
});
Forget having to use the Google Places API for this - It's simple to do without having to interact with any API.
Simply get the current location using a FusedLocationProviderClient to return the last known latitude and longitude of the device (as seen here), and then use an instance of Geocoder to get addresses from that latitude and longitude using the getFromLocation method. This can then easily be converted into a string which matches what the Google Places API would have returned (as seen here).

Geonames java client: How to retrieve the country and adminName1?

Geonames database works fine for me when to query via WEB. However, there are java packages org.geonames with classes WebService, Toponym and other ones, which seem to do the same from within java application. So, I try to use org.geonames for creating a query like
https://secure.geonames.org/countrySubdivision?lat=47.03&lng=30.2&username=myUserName
which, when sending via WEB, returns xml nwith countryName and adminName1 tags. However, I cannot find appropriate method (methods) in org.geonames returning object with countryName and adminName1 by given latitude and longitude.
How do I solve the problem?
The methods are in the class Toponym, not in the package.
Here is the javadoc with all the methods.
And here is an example from their website.
WebService.setUserName("demo"); // add your username here
ToponymSearchCriteria searchCriteria = new ToponymSearchCriteria();
searchCriteria.setQ("zurich");
ToponymSearchResult searchResult = WebService.search(searchCriteria);
for (Toponym toponym : searchResult.getToponyms()) {
System.out.println(toponym.getName()+" "+ toponym.getCountryName());
}

How to convert to C# a code to calculate a Distance and Bearing from google maps api

When I'm using Google Maps on Android I create a method to take a point A and calculate if it is inside of an area of 1km to the point B :
float[] results = new float[1];
Location.distanceBetween(centerLatitude, centerLongitude, testLatitude,
testLongitude, results);
float distanceInMeters = results[0];
boolean isWithin10km = distanceInMeters < 10000;
But I need to to this inside of my API, so I send a Location(Lat,Long) to my Server, I get a list of locations and try to make a match and them return something, the problem is, how to "unwrap" the code so I could switch to C#!
I founf the implementation of it, but it has some proper classes that I'm sure it doesn't exist in C#! here
I would reccomend that you use the assembly Sysetem.Device.Location (you can download a nugetpackage if you don't have it on your machine from here).
Then you can do the following using the GeoCoordinate class:
var geo1=new GeoCoordinate(centerLatitude, centerLongitude);
var geo2=new GeoCoordinate(testLatitude, testLongitude):
var result=geo1.GetDistanceTo(geo2);
For more information, please visit the documentation at MSDN.

how to save Location Info in Firebase

I am trying to save location (so latitide and longitude) as one of the keys/fields in Firebase. In their example SFVehicles, they do show how to query once the information is stored but my problem is how do i save in the first place.
In their blog post, GeoFire goes Mobile, they are showing how the data would look like - but how do I get that location field populated?
I am able to save other types of strings to the Firebase though. I just use the code below.
Question is What data type should the location field be?
Firebase ref = new Firebase("https://myfirebaselink.firebaseio.com/");
//User
alan = new User("Alan Turing", 1912);
alanRef.setValue(obj);
I tried location to be a List<String>, but that did not work -- the location field looked like below:
Edit: On more research, found this blog post by Google but they are also saving as keys latitude1 and longitude. This probably was written before GeoFire` was introduced.
The GeoFire for Java project has a great README, that covers (amongst other) setting location data:
In GeoFire you can set and query locations by string keys. To set a location for a key simply call the setLocation() method. The method is passed a key as a string and the location as a GeoLocation object containing the location's latitude and longitude:
geoFire.setLocation("firebase-hq", new GeoLocation(37.7853889, -122.4056973));
To check if a write was successfully saved on the server, you can add a GeoFire.CompletionListener to the setLocation() call:
geoFire.setLocation("firebase-hq", new GeoLocation(37.7853889, -122.4056973), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, FirebaseError error) {
if (error != null) {
System.err.println("There was an error saving the location to GeoFire: " + error);
} else {
System.out.println("Location saved on server successfully!");
}
}
});
To remove a location and delete it from the database simply pass the location's key to removeLocation:
geoFire.removeLocation("firebase-hq");
It looks from here
That the type of the object is GeoLocation , like in line 83.

Categories

Resources