I am creating an android app to record a user's activity using Google Maps SDK and the Google Play Services Location API. I am attempting to retrieve the user's elevation based on a given latitude and longitude. I originally used Location#getAltitude() but then realised that does not give the elevation above sea level.
I proceeded to use the open elevation API using the following query string:
String url = "https://api.open-elevation.com/api/v1/lookup?locations=" + latLng.latitude + "," + latLng.longitude;
However, that API appears to be much too slow in generating a response. I then found the Google Maps Elevation API which we can make a request using a URL also. However, we need to pass an API key and I do not want to pass this API key in the URL string and end up committing it to the remote repository.
In this repo (https://github.com/googlemaps/google-maps-services-java) I found the class:
/src/main/java/com/google/maps/ElevationApi.java which I thought I could use to avoid messing around with http requests.
In my gradle, I included this dependency:
implementation 'com.google.maps:google-maps-services:0.18.0'
At the moment, the code to retrieve the elevation is as follows:
ElevationApi.getByPoint(new GeoApiContext.Builder().apiKey(API_KEY).build(), latLng)
.setCallback(new PendingResult.Callback<ElevationResult>() {
#Override
public void onResult(ElevationResult result) {
consumer.doAction(result.elevation);
}
#Override
public void onFailure(Throwable e) {
e.printStackTrace();
}
});
What do I pass in for API_KEY here since I don't want to commit it to the repository? I have an api key defined in local.properties for maps, however, like so:
MAPS_API_KEY=<API_KEY_HERE>
Basically, my question is, can I define an API key in a properties file that is not committed to GitHub and then reference it in the code?
Thanks for any help.
Update:
I have managed to read the API key from local.properties using gradle but got an exception from the ElevationApi saying API 21+ expected, but was 30...strange. So I went back to the open-elevation API with the following Volley request:
/**
* Calculates elevation gain for the provided recording service
* #param recordingService the recording service to calculate elevation gain for
* #param response the handler to consume the elevation gain with
*/
public static void calculateElevationGain(RecordingService recordingService, ActionHandlerConsumer<Double> response) {
ArrayList<Location> locations = recordingService.getLocations();
JSONArray array = constructLocations(locations);
try {
if (array != null) {
RequestQueue requestQueue = Volley.newRequestQueue(recordingService);
String url = "https://api.open-elevation.com/api/v1/lookup";
JSONObject requestHeader = new JSONObject(); // TODO this seems very slow
requestHeader.put("locations", array);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, requestHeader,
response1 -> handleSuccessfulResponse(response1, response), RecordingUtils::handleErrorResponse);
request.setRetryPolicy(new DefaultRetryPolicy(500000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(request);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
I had to set the timeout to a high number not sure how hight it should be because I was getting Volley timeout errors due to the slow response times.
Are there any other ways I can retrieve elevation about sea level?
Yeah, open-elevation.com has intermittent issues with timeouts and latency.
There are some alternatives listed on this GIS stack exchange question Seeking alternative to Google Maps Elevation API. I'm the developer of Open Topo Data which is the most-voted answer over there. You can host your own server with docker, and I also have a free public API which has pretty good latency and uptime.
There's also GPXZ as an alternative to the Google Elevation API with higher-quality data, but it requires an API key so would have the same issue as with Google Maps.
I advise a different direction: stay with the Google and the API key, but employ best practices regarding secrets and source repositories. Since you are dealing with an Android app and not a webapp your key can be somewhat safe inside your app binary (versus a key in a web deployed app is exposed).
Bets practices:
Do not commit the API key. The best to achieve this is to exclude the file which contains the key from the source control repo. That can simply be done with .gitignore. For example this Codelab has a file with the secret, but it has a dummy value and normally this file should be excluded from the source. It is only there because that is an educational code lab.
As a security measure take advantage of GitGuardian to scan your repos in case you'd accidentally push an API key. In such events you'd get a notification. As for me I forked that Geospatial API codelab and saw the key file was in the gitignore and I accidentally pushed a key.
In case you accidentally push a key in a commit it's not enough to reverse the commit and delete the file! Scavenger bots will still find the information in your git history. Rather immediately disable the key and generate another one.
If you are dealing with a webapp you can restrict the API key usage to your webapp's domain. Similarly you can restrict the key to specific Android app signatures (don't forget to add your developer environment's signature) too. This guarantees that even if someone steals the key they probably won't be able to use it.
Related
Is it possible using custom OSRM server (Docker) for routing in navigation SDK? If i have custom streets in postgrey db, how can i calculate route on this streets?
Something as
NavigationRoute.builder(this)
.baseUrl("my server url")
does make request to my server but with additional params in query which i dont want :
/route/v1/driving/directions/v5/mapbox/driving-traffic/
I need just
/route/v1/driving/
Is it possible or exist some lib which converts osrm format to mapbox format?
I've found that it's reasonably trivial to use OSRM as a backing server for the Graphhopper Navigation API (which was forked from Mapbox I believe). I haven't tried using it directly with the Mapbox SDKs, but it might be worth a shot. Basically all I had to do was start up a forwarding server that would grab the coordinates and route parameters and pass them to OSRM, then add a request UUID on the way back to stop the SDK from complaining. I implemented the server in Ruby using Sinatra, and the code is below:
require 'net/http'
require 'sinatra'
require 'sinatra/json'
get '/directions/v5/:user/driving/:coordinates' do
uri = URI("http://router.project-osrm.org/route/v1/driving/#{params['coordinates']}")
uri.query = URI.encode_www_form({
alternatives: params['alternatives'],
continue_straight: params['continue_straight'],
geometries: params['geometries'],
overview: params['overview'],
steps: params['steps']
})
res = JSON.parse(Net::HTTP.get_response(uri).body)
res["uuid"] = SecureRandom.uuid
json(res)
end
I do not want to block threads in my application and so I am wondering are calls to the the Google Datastore async? For example the docs show something like this to retrieve an entity:
// Key employeeKey = ...;
LookupRequest request = LookupRequest.newBuilder().addKey(employeeKey).build();
LookupResponse response = datastore.lookup(request);
if (response.getMissingCount() == 1) {
throw new RuntimeException("entity not found");
}
Entity employee = response.getFound(0).getEntity();
This does not look like an async call to me, so it is possible to make aysnc calls to the database in Java? I noticed App engine has some libraries for async calls in its Java API, but I am not using appengine, I will be calling the datastore from my own instances. As well, if there is an async library can I test it on my local server (for example app engine's async library I could not find a way to set it up to use my local server for example I this library can't get my environment variables).
In your shoes, I'd give a try to Spotify's open-source Asynchronous Google Datastore Client -- I have not personally tried it, but it appears to meet all of your requirements, including being able to test on your local server. Please give it a try and let us all know how well it meets your needs, so we can all benefit and learn -- thanks!
I am trying to retrieve items from my Facebook news feed using the graph API. The code (unfinished) I am using is below, which seems to only be returning a single news feed post. I have read the documentation on cursor based pagination but it does not explain how to implement it, nor have i found any other resources explaining this matter.
// Get items from users news feed
public void getFeed() {
Session s = Session.getActiveSession();
new Request(
s,
"/me/home",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
/* handle the result */
JSONArray json = null;
JSONObject current = null;
try {
json = (JSONArray)response.getGraphObject().getProperty("data");
} catch(Exception e) {
// TODO
}
for(int i=0; i<5; i++) {
try {
current = json.getJSONObject(i);
Log.d("Value: ", current.get("message").toString());
} catch(Exception e) {
// Nothing
}
}
}
}
).executeAsync();
}
As I am still experimenting, I am just trying to pull down 5 news feed items and output the message JSON attribute. Could anybody advise me on how to properly implement the cursor based pagination to pull down an arbitrary number of feed posts at a time? Thanks
The person in your link is using FB-Andriod-SDK 3.0.1
Source
Which means it is using Graph v1.0
FB-Andriod-SDK 3.8 and above started using Graph v2.0
In Graph v2.0 and above the ability to use the "read_stream" permission became severely limited. So much so that unless you are a Facebook engineer you won't get it.
Limited Use
This permission is granted to apps building a Facebook-branded client on platforms where Facebook is not already available. For example, Android and iOS apps will not be approved for this permission. In addition, Web, Desktop, in-car and TV apps will not be granted this permission.
Source, Scroll down to "read_stream"
The user/home edge requires "read_stream" (user is a place holder for a User ID or "Me" keyword)
Permissions
A user access token with read_stream permission is required to view that person's news feed.
Source
This also extents to user/feed edge
Permissions
Any valid access token is required to view public links.
A user access token with read_stream permission is required.
Only posts whose authors have also granted read_stream permission to the app will be shown.
Source
As well as user/posts edge
This is a duplicate of the /feed edge which only shows posts published by the person themselves.
Source
On April 30, 2015 Graph v1.0 will be completely gone.
The current, latest version of the Graph API is v2.2. Apps calling v1.0 have until April 30, 2015 to upgrade to v2.0 or later.
Source, under "Staying up to date"
More insightful information about this can be found here.
Read all the comments Emil (FB Engineer) and Simon (Graph Product Manger) are the best sources
So what it boils down to is. You are attempting to do something that the Facebook developed app already does and they don't want you to do it.
First of all you can not use "me/home" as a call. It requires the "read_stream" permission and you'll never get that approved.
There is really no way to get this data on your own. You'll have to use one of FB's Media Partners
Here is more info.
Click here for more info
I am developing an Android app which takes the current location of the user and displays a list of restaurants close to his/her location. The restaurants' data is available to me (i.e I do have the lat/long of each restaurant I want to display in the search results). I can't use Google Places API, because I need to show only those restaurants that are available in our database(in our website). My question is how do I access my database(or even an URL),which is on a computer, to extract the restaurants' data and display as search results in my android app?
I am actually making a Seamless ( http://bit.ly/Jp7pUN ) type application for my company.
I am a complete newbie to android app development. So, pardon me if this is really a very broad or a stupid question. Please just tell me what topics I need to study to implement this. I would study and do it myself.
Thanks.
You will need:
a Sqlite database to store the restaurants and their longitude/latitude
a MapView to display the map (Don't forget to register your Google Maps API key)
a map overlay to show the markers on the map
GPS access to get the user's location (needs the appropriate Android permission)
a simple search algorithm that retrieves a result set of restaurants within x distance of the user's location
EDIT
If your database is stored on a server, you will need a way to query the server, preferably using an HTTP-based protocol such as REST. It is useful (but not required) to cache the restaurant locations on the Android device (using Sqlite), in case the user is offline (The good news: Since you can use Java both on Android and the server, 90% of your data access layer you will only need to write once).
For the data transfer from server to the Android client, JSON is a popular format.
To acces database on your computer (not SQLite on Android) you should use url for your database server changing localhost to: 10.0.2.2. But in case your database will be on the Internet - you should create maybe some REST API to get the data you need. Then use HttpClient to fetch the data from server.
Everything that you need is in Developer Guide: MapView
And for retrieving current location I advice using MyLocationOverlay
For example (url to server):
//public static final String SERVER_ADDRESS = "http://10.0.2.2:3000"; // for localhost server
public static final String SERVER_ADDRESS = "http://railsserver.herokuapp.com"; //for remote server
Accessing data on your server - this depends on that how you implement (and using what thechnology) your server (REST API?, WebService?, Plain HTML?) and what will be the format of the response from server (JSON? XML?, etc.)
I suggest using JSON because it is easy to parse using included classes in Android SDK:
String json = execute(new HttpGet(Constants.SERVER_URL + "/fetchData"));
JSONObject responseJSON = new JSONObject(json);
if(responseJSON.has("auth_error")) {
throw new IOException("fetchData_error");
}
Im working on oauth 1 Sparklr and Tonr sample apps and I'm trying to create a two-legged call. Hipoteticly the only thing you're supposed to do is change the Consumer Details Service from (Im ommiting the igoogle consumer info to simplify):
<oauth:consumer-details-service id="consumerDetails">
<oauth:consumer name="Tonr.com" key="tonr-consumer-key" secret="SHHHHH!!!!!!!!!!"
resourceName="Your Photos" resourceDescription="Your photos that you have uploaded to sparklr.com."/>
</oauth:consumer-details-service>
to:
<oauth:consumer-details-service id="consumerDetails">
<oauth:consumer name="Tonr.com" key="tonr-consumer-key" secret="SHHHHH!!!!!!!!!!"
resourceName="Your Photos" resourceDescription="Your photos that you have uploaded to sparklr.com."
requiredToObtainAuthenticatedToken="false" authorities="ROLE_CONSUMER"/>
</oauth:consumer-details-service>
That's adding requiredToObtainAuthenticatedToken and authorities which will cause the consumer to be trusted and therefore all the validation process is skipped.
However I still get the login and confirmation screen from the Sparklr app. The current state of the official documentation is pretty precarious considering that the project is being absorbed by Spring so its filled up with broken links and ambiguous instructions. As far as I've understood, no changes are required on the client code so I'm basically running out of ideas. I have found people actually claiming that Spring-Oauth clients doesn't support 2-legged access (which I found hard to believe)
The only way I have found to do it was by creating my own ConsumerSupport:
private OAuthConsumerSupport createConsumerSupport() {
CoreOAuthConsumerSupport consumerSupport = new CoreOAuthConsumerSupport();
consumerSupport.setStreamHandlerFactory(new DefaultOAuthURLStreamHandlerFactory());
consumerSupport.setProtectedResourceDetailsService(new ProtectedResourceDetailsService() {
public ProtectedResourceDetails loadProtectedResourceDetailsById(
String id) throws IllegalArgumentException {
SignatureSecret secret = new SharedConsumerSecret(
CONSUMER_SECRET);
BaseProtectedResourceDetails result = new BaseProtectedResourceDetails();
result.setConsumerKey(CONSUMER_KEY);
result.setSharedSecret(secret);
result.setSignatureMethod(SIGNATURE_METHOD);
result.setUse10a(true);
result.setRequestTokenURL(SERVER_URL_OAUTH_REQUEST);
result.setAccessTokenURL(SERVER_URL_OAUTH_ACCESS);
return result;
}
});
return consumerSupport;
}
and then reading the protected resource:
consumerSupport.readProtectedResource(url, accessToken, "GET");
Has someone actually managed to make this work without boiler-plate code?