thank you for taking a moment to help, if you can!
I am building a weather app and there's a page that I'm working on that needs to have latitude and longitude be updated frequently from a users phone.
i realize that there are two methods to do this...
getCurrentPosition()
watchPosition()
and I'm not really sure how to get the latitude/longitude into the request
Here is the code that I'm using
<link rel="stylesheet" href="https://cdn.aerisapi.com/wxblox/latest/aeris-wxblox.css">
<script src="https://cdn.aerisapi.com/wxblox/latest/aeris-wxblox.js"></script>
<!--// target DOM element where WeatherBlox will be rendered //-->
<div id="wxblox" class="aeris-wrapper"></div>
<script>
// set Aeris account access keys
const aeris = new AerisWeather('CLIENT_ID', 'CLIENT_SECRET');
aeris.on('ready', () => {
// create desired WeatherBlox instance
var view = new aeris.wxblox.layouts.local.Main('#wxblox', {
obs: {
advisories: {
enabled: true
},
threats: {
enabled: true
}
},
nearby: {
request: {
limit: 4
}
},
shortterm: {
request: {
limit: 3
}
},
forecast: {
type: "detailed"
},
maps: {
animation: {
enabled: true,
autoplay: false,
alwaysShowPast: false,
alwaysShowFuture: false,
from: -2,
to: 0,
duration: 2,
endDelay: 1,
intervals: 10
},
controls: {
layers: [
{
value: "radar",
title: "Radar"
},{
value: "satellite",
title: "Satellite"
},{
value: "alerts",
title: "Advisories"
},{
value: "temperatures,clip-us-flat",
title: "Temps"
}
],
regions: [
{
zoom: 7,
title: "Local"
},{
zoom: 5,
title: "Regional"
}
]
}
}
});
// load data and render the view for a specific location
view.load({
p: "Latitude, Longitude"
});
});
</script>
At the bottom where it says p:"Latitude, Longitude" is where I would need the results of those geolocation methods, as variables, to be placed. Perhaps more clearly it should be "Users Latitude, Users Longitude"
The user opens the app and this is the first page that they will see. This is a local weather conditions page which gets data from the closest weather observation point to the user.
IF I had to choose between the two methods, I would probably prefer watchPosition since it keeps up with the users location as they move.
Thank you for any help you may offer
Sincerely,
Justin
Call view.load() in the success callback of getCurrentPosition().
// load data and render the view for a specific location
Geolocation.getCurrentPosition(pos => {
console.log(`Showing weather for lat ${pos.coords.latitude}, long ${pos.coords.longitude}`);
view.load({p: `${pos.coords.latitude}, ${pos.coords.longitude}`});
}, err => console.log(`Geolocation error: ${err.message}`));
Full code:
// set Aeris account access keys
const aeris = new AerisWeather('CLIENT_ID', 'CLIENT_SECRET');
aeris.on('ready', () => {
// create desired WeatherBlox instance
var view = new aeris.wxblox.layouts.local.Main('#wxblox', {
obs: {
advisories: {
enabled: true
},
threats: {
enabled: true
}
},
nearby: {
request: {
limit: 4
}
},
shortterm: {
request: {
limit: 3
}
},
forecast: {
type: "detailed"
},
maps: {
animation: {
enabled: true,
autoplay: false,
alwaysShowPast: false,
alwaysShowFuture: false,
from: -2,
to: 0,
duration: 2,
endDelay: 1,
intervals: 10
},
controls: {
layers: [{
value: "radar",
title: "Radar"
}, {
value: "satellite",
title: "Satellite"
}, {
value: "alerts",
title: "Advisories"
}, {
value: "temperatures,clip-us-flat",
title: "Temps"
}],
regions: [{
zoom: 7,
title: "Local"
}, {
zoom: 5,
title: "Regional"
}]
}
}
});
console.log("Getting Geolocation");
// load data and render the view for a specific location
Geolocation.getCurrentPosition(pos => {
console.log(`Showing weather for lat ${pos.coords.latitude}, long ${pos.coords.longitude}`);
view.load({
p: `${pos.coords.latitude}, ${pos.coords.longitude}`
});
}, err => console.log(`Geolocation error: ${err.message}`));
});
Related
I have created a sanity schema which works perfectly according to the tutorial. However I have a leaflet.js plugin and I am trying to get it to auto find my location when I create a new template in the sanity studio. This was already done in the tutorial below, but when I do it, I get the sanity map showing up but I do not get the marker on my current location. Instead I get the default San-Francisco.
In the tutorial the lady gets allows the browser to share her location. However I do not get that prompt. Is this something to do with localhost?
I am following this tutorial but I don't know what I missed.
Relevant parts from 31.00-37.00. Tutorial below:
https://www.youtube.com/watch?v=YtFfUER8ta8
Below is my posts.js
const getPosition = (options) => {
if (navigator.geolocation) {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, options);
});
}
};
export default {
name: "post",
title: "Blog Post",
type: "document",
initialvalue: async () => ({
postedAt: await getPosition()
.then(({ coords }) => {
const { latitude, longtitude, altitude } = coords;
return {
_type: "geopoint",
lat: latitude,
lng: longtitude,
alt: altitude || undefined,
};
})
.catch(() => undefined),
}),
fields: [
{
name: "title",
title: "Title",
type: "string",
},
{
name: "postedAt",
type: "geopoint",
title: "Location",
},
{
name: "slug",
title: "Slug",
type: "slug",
options: {
source: "title",
maxLength: 96,
},
},
{
name: "author",
title: "Author",
type: "reference",
to: { type: "author" },
},
{
name: "mainImage",
title: "Main image",
type: "image",
options: {
hotspot: true,
},
},
{
name: "categories",
title: "Categories",
type: "array",
of: [{ type: "reference", to: { type: "category" } }],
},
{
name: "publishedAt",
title: "Published at",
type: "datetime",
},
{
name: "body",
title: "Body",
type: "blockContent",
},
],
preview: {
select: {
title: "title",
author: "author.name",
media: "mainImage",
},
prepare(selection) {
const { author } = selection;
return Object.assign({}, selection, {
subtitle: author && `by ${author}`,
});
},
},
};
leaflet-input.json
{
"tileLayer": {
"attribution": "© OpenStreetMap contributors",
"url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
}
}
I'm using NestJS in the vanillaJS way (because I can't write typescript) and I have a many-to-many relation from user to bubble.
I want to write a updateUser-Route in which I also want to be able to update the bubble-affiliation.
But when I do so like this:
user.controller.js:
#Patch(':id')
#Bind(Param('id'), Body())
async updateUser(id, body) {
if (Object.keys(body).length !== 0) {
return await this.userService.updateUser(id, body);
}
throw new BadRequestException('Missing Body');
}
user.service.js:
async updateUser(id, user) {
return await this.userRepository.update(id, user);
}
I get this error:
Cannot query across many-to-many for property bubble
This is my user.entity.js:
var EntitySchema = require('typeorm').EntitySchema;
var User = require('./user.model').User;
var Bubble = require('../bubble/bubble.model').Bubble;
module.exports = new EntitySchema({
name: 'User',
target: User,
columns: {
id: {
primary: true,
type: 'int',
},
handle: {
type: 'varchar',
},
lastCheck: {
type: 'datetime',
default: () => 'NOW()',
},
rating: {
type: 'int',
},
},
relations: {
bubble: {
type: 'many-to-many',
target: 'Bubble',
joinTable: true,
cascade: true,
},
},
});
in postman I try to call it like this:
{
"rating": 10,
"bubble": [{
"id": "1234"
}]
}
if I leave bubble out it works and rating gets updated. with bubble I get the error described above
I have trading view charting library i'm working on it but now i want to add custom indicator in it but i don't know how to do.
I have found the solution
pass the custom_indicators_getter in the props to trading view default props
like this
custom_indicators_getter: function (PineJS) {
return Promise.resolve([
{
name: "Bar Colorer Demo",
metainfo: {
_metainfoVersion: 51,
id: "BarColoring#tv-basicstudies-1",
name: "BarColoring",
description: "Bar Colorer Demo",
shortDescription: "BarColoring",
isCustomIndicator: true,
isTVScript: false,
isTVScriptStub: false,
format: {
type: "price",
precision: 4,
},
defaults: {
palettes: {
palette_0: {
// palette colors
// change it to the default colors that you prefer,
// but note that the user can change them in the Style tab
// of indicator properties
colors: [{ color: "#FFFF00" }, { color: "#0000FF" }],
},
},
},
inputs: [],
plots: [
{
id: "plot_0",
// plot type should be set to 'bar_colorer'
type: "bar_colorer",
// this is the name of the palette that is defined
// in 'palettes' and 'defaults.palettes' sections
palette: "palette_0",
},
],
palettes: {
palette_0: {
colors: [{ name: "Color 0" }, { name: "Color 1" }],
// the mapping between the values that
// are returned by the script and palette colors
valToIndex: {
100: 0,
200: 1,
},
},
},
},
constructor: function () {
this.main = function (context, input) {
this._context = context;
this._input = input;
var valueForColor0 = 100;
var valueForColor1 = 200;
// perform your calculations here and return one of the constants
// that is specified as a key in 'valToIndex' mapping
var result =
(Math.random() * 100) % 2 > 1 // we randomly select one of the color values
? valueForColor0
: valueForColor1;
return [result];
};
},
},
]);
},
And after this onChartReady
tvWidget.onChartReady(() => {
//Bar Colorer Demo is the name we passed in description
widget.activeChart().createStudy("Bar Colorer Demo", false, true);
})
I am trying to create my own Tech Radar based on Zalando Tech Radar and getting it to Pull data from a CSV.
But when I refresh the index.html. It gives me a blank page.
What am I missing here?
<script>
function draw_radar(my_entries) {
radar_visualization({
svg_id: "radar",
width: 1450,
height: 1000,
colors: {
background: "#fff",
grid: "#bbb",
inactive: "#ddd"
},
title: "My Radar",
quadrants: [
{ name: "Bottom Right" },
{ name: "Bottom Left" },
{ name: "Top Left" },
{ name: "Top Right" }
],
rings: [
{ name: "INNER", color: "#93c47d" },
{ name: "SECOND", color: "#b7e1cd" },
{ name: "THIRD", color: "#fce8b2" },
{ name: "OUTER", color: "#f4c7c3" }
],
print_layout: true,
entries: my_entries
});
}
</script>
I am following a guide and it is asking me to wrap the radar_visualization() function with a custom one, that takes an array of entry, to render the transformed rows, e.g. draw_radar(entries).
<script>
function toEntry(row) {
return {
label: row.name,
quadrant: ['Bottom Right','Bottom Left','Top Left','Top Right'].indexOf(row.quadrant),
ring: ['INNER','SECOND','THIRD','OUTER'].indexOf(row.ring),
link: row.link,
moved: ['down','none','up'].indexOf(row.moved) -1,
active:true
}
}
</script>
The guide is also mentions a way to transform a row in the CSV into an entry for the tech radar:
<script>
fetch('./data.csv')
.then(function (resp) {
return resp.text();
})
.then(function (csv) {
var entries = d3.csvParse(csv,function (row) {
return toEntry(row);
});
draw\_radar(entries);
});
</script>
This is the last part to bring them all together. But when nothing happens when I load the .html
so I am trying to modify the example Cumulative flow chart here so that it has a release dropdown, making it so that it only shows information pertaining to a given release. My problem is that when a new release is selected from the release dropdown, the graph does not reload itself, and so it never actually shows information pertinent to the selected release. I think I have implemented the listeners correctly but I am not sure, so I am wondering if someone could tell me why this is happening and how to fix it. Thanks! My code is below:
<!DOCTYPE html>
<html>
<head>
<title>Historical Summary</title>
<script type="text/javascript" src="/apps/2.0rc3/sdk.js"></script>
<script type="text/javascript">
Rally.onReady(function() {
Ext.define('Rally.example.CFDCalculator', {
extend: 'Rally.data.lookback.calculator.TimeSeriesCalculator',
config: {
stateFieldName: 'ScheduleState',
stateFieldValues: ['Defined', 'In-Progress', 'Completed', 'Accepted']
},
constructor: function(config) {
this.initConfig(config);
this.callParent(arguments);
},
getMetrics: function() {
return _.map(this.getStateFieldValues(), function(stateFieldValue) {
return {
as: stateFieldValue,
groupByField: this.getStateFieldName(),
allowedValues: [stateFieldValue],
f: 'groupByCount',
display: 'area'
};
}, this);
}
});
Ext.define('Rally.example.CFDChart', {
extend: 'Rally.app.App',
requires: [
'Rally.example.CFDCalculator'
],
launch: function() {
this.add({
xtype: 'rallyreleasecombobox',
fieldLabel: 'Filter by Release:',
project: this.getContext().getProject(),
//value: Rally.util.Ref.getRelativeUri(this.getContext().getRelease()),
listeners: {
select: this._onSelect,
ready: this._onLoad,
scope: this
}
});
},
_onLoad: function() {
this.add({
xtype: 'rallychart',
storeType: 'Rally.data.lookback.SnapshotStore',
storeConfig: this._getStoreConfig(),
calculatorType: 'Rally.example.CFDCalculator',
calculatorConfig: {
stateFieldName: 'ScheduleState',
stateFieldValues: ['Defined', 'In-Progress', 'Completed', 'Accepted']
},
chartConfig: this._getChartConfig()
//context: this.getContext();
});
},
_onSelect: function() {
var histChart = this.down('rallychart');
histChart.refresh({
storeConfig: {
filters: [this._getOwnerFilter()]
}
});
},
_getOwnerFilter: function() {
//var userCombo = this.down('rallyusersearchcombobox');
var releaseValue = this.down('rallyreleasecombobox');
return {
property: 'Release',
operator: '=',
value: releaseValue.getValue()
};
},
/**
* Generate the store config to retrieve all snapshots for stories and defects in the current project scope
* within the last 30 days
*/
_getStoreConfig: function() {
return {
find: {
_TypeHierarchy: { '$in' : [ 'HierarchicalRequirement', 'TestSet' ] },
Children: null,
_ProjectHierarchy: this.getContext().getProject().ObjectID,
_ValidFrom: {'$gt': Rally.util.DateTime.toIsoString(Rally.util.DateTime.add(new Date(), 'day', -30)) }
},
fetch: ['ScheduleState'],
hydrate: ['ScheduleState'],
sort: {
_ValidFrom: 1
},
context: this.getContext().getDataContext(),
limit: Infinity
};
},
/**
* Generate a valid Highcharts configuration object to specify the chart
*/
_getChartConfig: function() {
return {
chart: {
zoomType: 'xy'
},
title: {
text: 'Project Cumulative Flow: User Stories & Test Sets'
},
xAxis: {
tickmarkPlacement: 'on',
tickInterval: 1,
title: {
text: 'Date'
}
},
yAxis: [
{
title: {
text: 'Count'
}
}
],
plotOptions: {
series: {
marker: {
enabled: false
}
},
area: {
stacking: 'normal'
}
}
};
}
});
Rally.launchApp('Rally.example.CFDChart', {
name: 'Historical summary: test cases, stories, and defects'
});
});
</script>
<style type="text/css">
</style>
</head>
<body></body>
</html>
Your code errors with "Uncaught TypeError: undefined is not a function" on line
histChart.refresh
I modified example of ProjectCumulativeFlow to filter by Release. Full code is in this github repo.
Instead of extending Rally.app.App, I extended Rally.app.TimeboxScopedApp.
SnapshotStore may filter by Release, but requires ObjectID.
Here is the find:
find: {
_TypeHierarchy: { '$in' : [ 'HierarchicalRequirement', 'Defect' ] },
Release: this.getContext().getTimeboxScope().record.data.ObjectID,
Children: null,
_ProjectHierarchy: this.getContext().getProject().ObjectID
}
To update the app after Release selection check if the chart already exists (if yes, destroy it):
onScopeChange: function() {
if (this.down('#mychart')) {
this.down('#mychart').destroy();
}
this.add({
xtype: 'rallychart',
itemId: 'mychart',
storeType: 'Rally.data.lookback.SnapshotStore',
storeConfig: this._getStoreConfig(),
calculatorType: 'Rally.example.CFDCalculator',
calculatorConfig: {
stateFieldName: 'ScheduleState',
stateFieldValues: ['Defined', 'In-Progress', 'Completed', 'Accepted']
},
chartConfig: this._getChartConfig()
});
},