Strava API - accurate longitude and latitude - api

Does anyone know a way to get the exact longitude and latitude for an activity from the strava api using a get request?
I'm trying to integrate the strava api with google maps and I'm trying to build an array with the appropriate long/lat locations, but the https://www.strava.com/api/v3/athlete/activities?per_page=100... request is only returning longitude and latitudes rounded off like: start_longitude: 2.6.
I've found a "hacky" way of retrieving the start coordinates by looping through results and then sending off another request within the loop, although this is sending WAY too many requests. - below is a snippet of my request:
// start request
$.get( "https://www.strava.com/api/v3/athlete/activities?per_page=100&access_token=ACCESSTOKEN", function (results) {
// loop through request
for (i = 0; i < results.length; i++) {
if(results[i].type === 'Run') {
// add an element to the array for each result
stravaComplete.push(true);
$.get( "https://www.strava.com/api/v3/activities/"+ results[i].id +"?per_page=5&access_token=ACCESSTOKEN", function (runs) {
if(typeof runs.segment_efforts[0] != "undefined"){
var runLatitude = runs.segment_efforts[0].segment.start_latitude;
var runLongitude = runs.segment_efforts[0].segment.start_longitude;
stravaActivityList.push({"lat": runLatitude, "lng": runLongitude});
}
// remove the element from the array
stravaComplete.pop();
// if all the elements have been removed from the array it means the request is complete
if(stravaComplete.length == 0) {
// reinitialize map
initMap(stravaActivityList);
}
});
}
}
});
Any guidance would be great. Thanks.

It's not clear if you need coordinates of start points only, or for the whole activity and what accuracy is required.
Response to query https://www.strava.com/api/v3/athlete/activities includes a field map => summary_polyline from which you should be able to extract coordinates of the whole (although simplified) activity. You can also use this polyline to display it in google maps.
If you, however, need even better accuracy you need to retrieve every activity and use map => summary_polyline or map => polyline fields.
To get full data streams should be used

Use summary_polyline[0] and summary_polyline[-1] (Ruby) instead of rounded values. See this code from Slava for an example.

Related

How to read values from a view to insert in ratingValue and ratingCount in my web in order to be recognized by Google Structured data testing tool?

I was using an external service to get Aggregate Rating in my recipes blog, but dis service disappeared so I decided to build one myself. First of all, this is my first experience with cloud data and JavaScript programming so please, be paciente with me :-).
I'm doing my experiments in this duplicate of my blog: https://jleavalc.blogspot.com/
by now it works as I planned, letting one to vote and storing results in a oracle table, making it possible to retrieve results from a view of this table to get ratingCount and ratingValue values, as anyone can see in that link...
But at the end, despite you can see the stars, despite you can vote and get result stored, showing voting results, Structured data testing tool don't see tag values, so all work is useless.
I think I'm getting close to the problem, but not getting close to the solution. I have the impression that the cause of my problems is the asynchrony of the execution of the script that brings the data from the table, while the function is executed, the browser continues to render the page and it doesn't arrive in time to write those values ​​before the google tool can read them, so they appear empty to it.
I have tried everything including labels and variables in GTM with the same result. The latest version of the code, from this morning is installed right before the "/head" tag and it looks like this:
<script style='text/javascript'>
var myPostId = "<data:widgets.Blog.first.posts.first.id/>";
// <![CDATA[
var micuenta = 0;
var nota = 0;
getText("https://ge4e65cc87f573d-XXXXXXXXXXXX.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q={\"receta\":{\"$eq\":\"" + myPostId + "\"}}");
async function getText(file) {
let x = await fetch(file);
let y = await x.text();
let datos = JSON.parse(y);
nota = datos.items[0].media;
micuenta = datos.items[0].votos;
};
// This version gives the same result and is interchangeable with the previous one. I keep it commented so as not to forget it:
// var settings = {
// "url": "https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q={\"receta\":{\"$eq\":\"" + myPostId + "\"}}",
// "method": "GET",
// "timeout": 0,
// "async": false,
// };
// $.ajax(settings).done(function (response) {
// if (response.items.length != 0) {
// micuenta = response.items[0].votos;
// nota = response.items[0].media;
// }
// });
</script>
The key is, I think, getting this call to execute before Google's tool finishes rendering the Blogger post page.
The URL that I invoke to get the data calls an oracle view that returns a single row with the corresponding data from the recipe, placing this call:
recipe
In the browser the result is the following:
{"items":[{"receta":"5086941171011962392","media":4.5,"votos":12}],"hasMore":false,"limit":25,"offset":0,"count":1,"links":[{"rel":"self","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q=%7B%22receta%22:%7B%22%24eq%22:%225086941171011962392%22%7D%7D"},{"rel":"edit","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q=%7B%22receta%22:%7B%22%24eq%22:%225086941171011962392%22%7D%7D"},{"rel":"describedby","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/metadata-catalog/notas/"},{"rel":"first","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q=%7B%22receta%22:%7B%22%24eq%22:%225086941171011962392%22%7D%7D"}]}
And I just need to take the median and votes values ​​to create the RatingCount and RatingValue labels
Can anyone offer me an idea that solves this little problem? :-)

Is it possible to get a list of places near a Lat/Long using MapKit?

I'm trying to build a simple location search that returns a list of places near the user. So for example, using current location, or a given Latitude and Longitude I want to list out all place names, businesses, towns, etc. within a certain radius. Is this possible using MapKit? I know it's easy to do using Facebook graph API.
The best I can find is to do CLGeocoder().reverseGeocodeLocation but that just returns the nearest address. I even tried using
CLLocation(
coordinate:CLLocationCoordinate2D,
altitude:CLLocationDistance,
horizontalAccuracy:CLLocationAccuracy,
verticalAccuracy:CLLocationAccuracy,
timestamp:Date
)
and setting the accuracy to 1,000 meters, but that didn't increase the number of results either. So, my assumption is that with MapKit, you can not get a list of place results around a given point. Is that true?
For good measure, here is the code I'm calling.
let latitude = CLLocationDegrees(40.692001)
let longitude = CLLocationDegrees(-73.983386)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let altitude = CLLocationDistance(1000.0)
let accuracy = CLLocationAccuracy(1000.0)
let locationArea = CLLocation(coordinate: location, altitude: altitude, horizontalAccuracy: accuracy, verticalAccuracy: accuracy, timestamp: Date())
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(locationArea) { (placemarks, error) in
if error == nil {
print(placemarks!.count)
for place in placemarks! {
print(place)
}
} else {
print(error!)
}
}
Unless the API has changed, I believe the answer is no. I ended up using the facebook places API.

AngularJS: Take a single item from an array and add to scope

I have a ctrl that pulls a json array from an API. In my code I have an ng-repeat that loops through results.
This is for a PhoneGap mobile app and I'd like to take a single element from the array so that I can use it for the page title.
So... I'm wanting to use 'tool_type' outside of my ng-repeat.
Thanks in advance - I'm just not sure where to start on this one.
Example json data
[{ "entry_id":"241",
"title":"70041",
"url_title":"event-70041",
"status":"open",
"images_url":"http://DOMAIN.com/uploads/event_images/241/70041__small.jpg",
"application_details":"Cobalt tool bits are designed for machining work hardening alloys and other tough materials. They have increased water resistance and tool life. This improves performance and retention of the cutting edge.",
"product_sku":"70041",
"tool_type": "Toolbits",
"sort_group": "HSCo Toolbits",
"material":"HSCo8",
"pack_details":"Need Checking",
"discount_category":"102",
"finish":"P0 Bright Finish",
"series_description":"HSS CO FLAT TOOLBIT DIN4964"},
..... MORE .....
Ctrl to call API
// Factory to get products by category
app.factory("api_get_channel_entries_products", function ($resource) {
var catID = $.url().attr('relative').replace(/\D/g,'');
return $resource(
"http://DOMAIN.com/feeds/app_productlist/:cat_id",
{
cat_id: catID
}
);
});
// Get the list from the factory and put data into $scope.categories so it can be repeated
function productList ($scope, api_get_channel_entries_products, $compile) {
$scope.products_list = [];
// Get the current URL and then regex out everything except numbers - ie the entry id
$.url().attr('anchor').replace(/\D/g,'');
$scope.products_list = api_get_channel_entries_products.query();
}
Angular works as following:
Forgiving: expression evaluation is forgiving to undefined and null, unlike in JavaScript, >where trying to evaluate undefined properties can generate ReferenceError or TypeError.
http://code.angularjs.org/1.2.9/docs/guide/expression
so you only need to write:
<title>{{products_list[0].tool_type}}</title>
if there is a zero element the title will be the tool_type, if not, there is no title.
Assuming you want to select a random object from the list to use something like this should work:
$scope.product-tool_type = products_list[Math.floor(Math.random()*products_list.length)].tool_type
Then to display the result just use
<h1>{{product-tool_type}}</h1>
Or alternatively:
<h1>{{products_list[Math.floor(Math.random()*products_list.length)].tool_type}}</h1>

HighChart.js data source recommendations

I am looking to use Highstock.js for an application I am developing and looking to implement a stock performance with Highcharts stock library chart; http://www.highcharts.com/stock/demo/
I was wondering if there was any good suggestions on where to get the data source from?
Thank-you!
I fetch data from an API, and then store the data in localstorage.
e.g:
This fetches data from an API for use with Highcharts, and stores/updates it in localstorage (jStorage).
updateLocalStorage: function(id) {
//Check if local storage needs updating
if (isNaN($.jStorage.get(id))) {
//Data exists in Localstorage, merge data
//Query API for highstock data
return $.post('api/', {
data_id: id
}, function(data) {
if (data) {
var merged = $.extend($.jStorage.get(id), data);
$.jStorage.set(id, merged);
}
});
//return true;
}
}
Once this data has been fetched I then render highcharts from the data that is stored in localstorage.
$.when(updateLocalStorage(id)).then(function(response){
if(response){
//Local storage is up to date. Render chart
}
});
I can also fetch data from the API using a timer and update localstorage, when I want to re-render the chart I can just use the highcharts setData method, e.g:
var json = $.jStorage.get(id);
for(i =0; i < json.data; i++) {
chart_object.series[i].setData(json.data[i]);
}
You can hardcode data in series / data object as in the example http://www.highcharts.com/demo/ Obviously you can also use dynamically way to define points.
http://docs.highcharts.com/#preprocessing
If you are asking about where to get financial stock price data from, there are several sources I know of including google finance and yahoo finance. Here are some links to help you:
How can I get stock quotes using Google Finance API?
http://www.yqlblog.net/blog/2009/06/02/getting-stock-information-with-yql-and-open-data-tables/

Have Google maps center around geo-locs and zoom in appropriately

I would like to pass an x amount of geo-locations to the Google Maps API and have it centered around these locations and set the appropriate zoom level so all locations are visible on the map. I.e. show all the markers that are currently on the map.
Is this possible with what the Google Maps API offers by default or do I need to resolve to build this myself?
I used fitBounds (API V3) for each point:
Declare the variable.
var bounds = new google.maps.LatLngBounds();
Go through each marker with FOR loop
for (i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(markers[i].lat, markers[i].lng);
bounds.extend(latlng);
}
Finally call
map.fitBounds(bounds);
There are a number of ways of doing this but it is pretty easy if you are using the V2 API. See this post for an example, this group post or this post.
For V3 there's zoomToMarkers
Gray's Idea is great but does not work as is. I had to work out a hack for a zoomToMarkers API V3:
function zoomToMarkers(map, markers)
{
if(markers[0]) // make sure at least one marker is there
{
// Get LatLng of the first marker
var tempmark =markers[0].getPosition();
// LatLngBounds needs two LatLng objects to be constructed
var bounds = new google.maps.LatLngBounds(tempmark,tempmark);
// loop thru all markers and extend the LatLngBounds object
for (var i = 0; i < markers.length; i++)
{
bounds.extend(markers[i].getPosition());
}
// Set the map viewport
map.fitBounds(bounds);
}
}