Vue Leaflet Get Color Function - vue.js

I am using VueLeaflet to create a map like in this example: https://vue2-leaflet.netlify.com/examples/geo-json.html
I like to add some colors to the polygons like in this example: https://leafletjs.com/examples/choropleth/
This is my try here: https://codesandbox.io/s/old-framework-mlc7b
getcolorFunction(d) {
return d > 1000
? "#800026"
: d > 500
? "#BD0026"
: d > 200
? "#E31A1C"
: d > 100
? "#FC4E2A"
: d > 50
? "#FD8D3C"
: d > 20
? "#FEB24C"
: d > 10
? "#FED976"
: "#FFEDA0";
},
styleFunction() {
const fillColor = this.fillColor; // important! need touch fillColor in computed for re-calculate when change fillColor
return () => {
return {
weight: 2,
color: "#ECEFF1",
opacity: 1,
fillColor: getColor(feature.properties.sales),
fillOpacity: 1
};
};
},
onEachFeatureFunction() {
if (!this.enableTooltip) {
return () => {};
}
return (feature, layer) => {
layer.bindTooltip(
"<div>Name Province:" +
feature.properties.varname_1 +
"</div><div>Sales: " +
feature.properties.sales +
"</div>",
{ permanent: false, sticky: true }
);
};
}
},
How could I Get work that function getColor in Vue.js ?

onEachFeatureFunction() {
return (feature, layer) => {
layer.options.fillColor = this.getcolorFunction(
feature.properties.sales
?feature.properties.sales
: 0
);
layer.on("click", function (e) {
console.log(e, feature);
})
};
}

Related

Row Span AutoGrouping and Bug

I've created a plnkr to auto-group row-spans the way you would really expect it to work out of the box IMHO.
Anyhow... doing this surfaces an apparent bug... the rowSpan is not consistently applied to the grid.. if you scroll up and down, it sometimes applies, and sometimes does not.
In the screenshot below... you can see 'Aaron Peirsol' is spanning... but if I scroll up and down it might not span on him... not consistent.
Here 'Aaron Peirsol' is no longer spanning all 3 rows -- all I did was scroll up and back down
See this Sample
https://plnkr.co/edit/UxOcCL1SEY4tScn2?open=app%2Fapp.component.ts
Here I've added columndefs for the grouping
{
field: 'athlete',
rowSpan: params => params.data.groupCount,
cellClassRules: {
'cell-span': "data.isFirst && data.groupCount>1",
},
width: 200,
},
{field:'groupCount', width: 20}, /* included for debugging */
{field:'isFirst', width: 20}, /* included for debugging */
And here I'm doing the auto-grouping code:
onGridReady(params: GridReadyEvent) {
this.http
.get<any[]>('https://www.ag-grid.com/example-assets/olympic-winners.json')
.subscribe((data) => {
let groupKey = 'athlete';
let sorted = data.sort((a,b) => (a[groupKey] > b[groupKey]) ? 1 :
((b[groupKey] > a[groupKey]) ? -1 : 0));
let filtered = sorted.filter(x => {
return x[groupKey] < 'Albert' && x[groupKey];
});
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
let keyValue = x[key];
if (rv[keyValue] === undefined)
{
rv[keyValue] = 0;
}
if (keyValue) {
rv[keyValue] ++;
}
return rv;
}, {});
};
let grouped = groupBy(filtered, groupKey);
let prev = '';
for (let i=0; i<filtered.length; i++)
{
let keyValue = filtered[i][groupKey];
filtered[i]['groupCount'] = grouped[keyValue];
if (keyValue == prev)
{
filtered[i]['isFirst'] = false;
}
else
{
filtered[i]['isFirst'] = true;
}
prev = keyValue;
}
this.rowData = filtered});
}
OK, found the issue...
rowSpan function must only return a span count for the first row of the span...
every other row it must return 1
I've updated the plunker
public columnDefs: ColDef[] = [
{
field: 'athlete',
rowSpan: params => params.data.groupRowCount == 1 ? params.data.groupCount: 1, //THIS IS CRUCIAL.. only return count for first row
cellClassRules: {
'cell-span': "data.groupRowCount==1 && data.groupCount>1",
},
width: 200,
},

TypeError: Cannot read properties of undefined (reading 'type') at eval ... at Array.sort (<anonymous>)

I need your help with this error I am facing colleagues. I am new to vue so I am finding it quite difficult to solve the error though I what what exactly is causing the error. I am creating a datatable in vue and I am trying to achieve data sorting with this tutorial I am following but end up getting the following error:
TypeError: Cannot read properties of undefined (reading 'type')
computed: {
filteredAccommodations(){
let accommodations = this.accommodations;
if (this.search) {
accommodations = accommodations.filter((row) => {
return Object.keys(row).some((key) => {
return String(row[key]).toLowerCase().indexOf(this.search.toLowerCase()) > -1;
})
});
}
let sortKey = this.sortKey;
let order = this.sortOrders[sortKey] || 1;
if(sortKey){
accommodations = accommodations.slice().sort((a, b) => {
let index = this.getIndex(this.columns, 'name', sortKey);
a = String(a[sortKey]).toLowerCase();
b = String(b[sortKey]).toLowerCase();
if (this.columns[index].type && this.columns[index].type === 'date') {
return (a === b ? 0 : new Date(a).getTime() > new Date(b).getTime() ? 1 : -1) * order;
} else if (this.columns[index].type && this.columns[index].type === 'number') {
return (+a === +b ? 0 : +a > +b ? 1 : -1) * order;
} else {
return (a === b ? 0 : a > b ? 1 : -1) * order;
}
});
}
return accommodations;
},
paginatedAccommodations(){
return this.paginate(this.filteredAccommodations, this.length, this.pagination.currentPage);
}
},
The reason for your error is because the value of this.columns[index] is a null value ,Adding a null check in ur if loop might help you solve this but I suggest you to check for the reason of null value.
computed: {
filteredAccommodations() {
let accommodations = this.accommodations;
if (this.search) {
accommodations = accommodations.filter((row) => {
return Object.keys(row).some((key) => {
return String(row[key]).toLowerCase().indexOf(this.search.toLowerCase()) > -1;
})
});
}
let sortKey = this.sortKey;
let order = this.sortOrders[sortKey] || 1;
if (sortKey) {
accommodations = accommodations.slice().sort((a, b) => {
let index = this.getIndex(this.columns, 'name', sortKey);
a = String(a[sortKey]).toLowerCase();
b = String(b[sortKey]).toLowerCase();
if (this.columns[index] && this.columns[index].type && this.columns[index].type === 'date') {
return (a === b ? 0 : new Date(a).getTime() > new Date(b).getTime() ? 1 : -1) * order;
} else if (this.columns[index] && this.columns[index].type && this.columns[index].type === 'number') {
return (+a === +b ? 0 : +a > +b ? 1 : -1) * order;
} else {
return (a === b ? 0 : a > b ? 1 : -1) * order;
}
});
}
return accommodations;
},
paginatedAccommodations() {
return this.paginate(this.filteredAccommodations, this.length, this.pagination.currentPage);
}
},

React-Native — How to select a start and end date using react-native-calendars (WIX)?

I am trying to enable date range using react-native-calendars. On my app, the calendar loads a few 'markedDates'; now I need to implement a start and end date functionality without affecting these initial dates. Unfortunately, I am struggling to achieve that. Any ideas on how can I do that?
Thank you in advance.
Pseudo-code
Load calendar with marked dates
Tap on start date
Tap on end date
Continue
Component
export default class Dates extends Component {
static navigationOptions = {
title: 'Choose dates',
}
constructor(props) {
super(props)
this.state = {
selected: undefined,
marked: undefined,
}
}
componentDidMount() {
this._markDate()
}
_markDate = () => {
nextDay = []
const marked = {
[nextDay]: { selected: true, marked: true },
}
Util._findShows(resp => {
resp.map(data => {
nextDay.push(data.date)
})
var obj = nextDay.reduce((c, v) => Object.assign(c, { [v]: { marked: true, dotColor: 'black' } }), {})
this.setState({ marked: obj })
})
}
_selectDate = obj => {
this.setState({ selected: obj.dateString })
}
render() {
return (
<View style={styles.container}>
<CalendarList
// Callback which gets executed when visible months change in scroll view. Default = undefined
onVisibleMonthsChange={months => {
console.log('now these months are visible', months)
}}
// Max amount of months allowed to scroll to the past. Default = 50
pastScrollRange={0}
// Max amount of months allowed to scroll to the future. Default = 50
futureScrollRange={12}
// Enable or disable scrolling of calendar list
scrollEnabled={true}
// Enable or disable vertical scroll indicator. Default = false
showScrollIndicator={true}
markedDates={
// [this.state.selected]: { selected: true, disableTouchEvent: true, selectedDotColor: 'orange' },
this.state.marked
}
onDayPress={day => {
this._selectDate(day)
}}
/>
<View style={styles.ctaArea}>
<TouchableOpacity style={styles.button} onPress={() => this.props.navigation.navigate('Dates')}>
<Text style={styles.btTitle}>Continue</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
I had the same struggle but so I decided to make my own version.
I'm sure it can be done better and have more functionalities but it works okay for me
const [dates, setDates] = useState({});
// get array of all the dates between start and end dates
var getDaysArray = function(start, end) {
for (var arr=[], dt = new Date(start); dt <= new Date(end); dt.setDate(dt.getDate() + 1)){
arr.push(useFormatDate(new Date(dt)));
}
return arr;
};
// empty object
const emptyObj = (obj: Object) => {
var props = Object.getOwnPropertyNames(obj);
for (var i = 0; i < props.length; i++) {
delete dates[props[i]];
}
}
// check if first date is smaller or equals to second date
const compareDate = function(first: string, second: string) {
return (new Date(first) <= new Date(second) ? true : false);
}
// fill with color the date between first and second date selected
const fillRangeDate = function(first: string, second: string) {
emptyObj(dates);
let newDates = dates;
newDates[first]={selected: true, Colors[colorScheme].tint};
newDates[second]={selected: true, color: Colors[colorScheme].tint};
var range = getDaysArray(first, second);
for (var i = 1; i < range.length - 1; i++)
newDates[range[i]]={color: '#70d7c7', textColor: 'white'};
setDates({...newDates})
}
const selectDate = (day) => {
let selectedDate = day.dateString;
let newDates = dates;
// if 2 dates are selected
if (Object.keys(dates).length >= 2) {
var props = Object.getOwnPropertyNames(dates);
if (compareDate(props[0], selectedDate)) {
fillRangeDate(props[0], selectedDate);
} else {
emptyObj(dates);
}
} else {
// 1 date selected
if (Object.keys(dates).length == 0) {
newDates[selectedDate]={selected: true, color: Colors[colorScheme].tint};
} else if (Object.keys(dates).length == 1) { // 2 dates selected
newDates[selectedDate]={selected: true, color: Colors[colorScheme].tint};
// if 2nd date < 1st date, cancel range
var props = Object.getOwnPropertyNames(dates);
if (compareDate(props[0], props[1])) {
var range = getDaysArray(props[0], props[1]);
for (var i = 1; i < range.length - 1; i++) {
newDates[range[i]]={color: '#70d7c7', textColor: 'white'};
}
} else {
emptyObj(dates);
}
}
}
setDates({...newDates})
}
You'll also need to add this function that I implemented as a hook:
const useFormatDate = (date: Date) => {
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
}
return [
date.getFullYear(),
padTo2Digits(date.getMonth() + 1),
padTo2Digits(date.getDate()),
].join('-');
};
Help me to improve this code and maybe create a merge request on the wix/react-native-calendar
Hope this helps

Vue.js - Input, v-model and computed property

I'm using vue-2.4 and element-ui 1.4.1.
Situation
I have a basic input which is linked with v-model to a computed property. When blur I check if the value input is greater or lower than min and max and I do what I have to do ... Nothing fancy here.
Problem
The value displayed in the input does not always equal enteredValue
Steps to reproduce
1) Input 60 --> Value displayed is the max so 50 and enteredValue is 50 (which is ok)
2) Click outside
3) Input 80 --> Value displayed is 80 and enteredValue is 50
Questions
How can I fix that so the value displayed is always the same as the enteredValue ?
Here is the minimal code to reproduce what I'm facing JSFIDDLE
<div id="app">
The variable enteredValue is {{enteredValue}}
<el-input v-model="measurementValueDisplay" #blur="formatInput($event)"></el-input>
</div>
var Main = {
data() {
return {
enteredValue: '',
max: 50,
min: 10
}
},
computed: {
measurementValueDisplay: {
get: function () {
return this.enteredValue + ' inchs'
},
set: function (newValue) {
}
},
},
methods: {
formatInput($event) {
let inputValue = $event.currentTarget.value;
if (inputValue > this.max) { this.enteredValue = this.max}
else if (inputValue < this.min) { this.enteredValue = this.min}
else this.enteredValue = inputValue
}
}
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
Reading this vuejs, will understand what happens
"computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed."
Changed some comportament of the code. Made run:
computed() method not works properly for update value in window. But if looks at console the value yes updated.
So, i remove computed (getter and setter), and put into data, without setter and getter( i dont like this in javascript).
var Main = {
data() {
return {
measurementValueDisplay:'fff',
enteredValue: '',
max: 50,
min: 10
}
},
computed: {
/*measurementValueDisplay: {
get: function () {
console.log('Computed was triggered so I assume enteredValue changed',this.enteredValue);
return this.enteredValue + ' inchs'
},
set: function (newValue) {
console.log('setter de qye', this.enteredValue);
}
},*/
},
methods: {
formatInput($event) {
this.enteredValue = 0;
let inputValue = $event.currentTarget.value;
console.log(inputValue);
if (inputValue > this.max) { this.enteredValue = this.max}
else if (inputValue < this.min) { this.enteredValue = this.min}
else this.enteredValue = inputValue
this.measurementValueDisplay = this.enteredValue + ' inchs'
console.log(this.enteredValue, 'oioioioio0');
}
}
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
Your problem is that the values used in the computed property was not updated with the validation capping at 50 (Was 50, is now updated to 50, no need to recalculate), therefore v-model did not update the input.
I've edited your jsfiddle to use two computed properties:
One with an accessor to validate the entered value, one which returns the value with " inch" appended.
Here is the interesting part:
computed: {
measurementValueDisplay: {
get: function () {
return this.enteredValue
},
set: function (newValue) {
this.enteredValue = 0;
let inputValue = parseInt(newValue);
if(Number.isNaN(inputValue)){this.enteredValue = this.min}
else if (inputValue > this.max) { this.enteredValue = this.max}
else if (inputValue < this.min) { this.enteredValue = this.min}
else this.enteredValue = inputValue
}
},
valueWithInch(){
return this.enteredValue + " inch";
}
},
In case anybody still needs a hack for this one, you can use a value that will always change ( for example a timestamp )
var Main = {
data() {
return {
enteredValue: '',
max: 50,
min: 10,
now: 1 //line added
}
},
computed: {
measurementValueDisplay: {
get: function () {
return (this.now - this.now + 1 ) * this.enteredValue + ' inchs'; //line changed
},
set: function (newValue) {
this.now = Date.now(); //line added
}
},
},
methods: {
formatInput($event) {
let inputValue = $event.currentTarget.value;
if (inputValue > this.max) { this.enteredValue = this.max}
else if (inputValue < this.min) { this.enteredValue = this.min}
else this.enteredValue = inputValue
}
}
}

ST2.1 vs ST2.2 chart sprite style renderer

With ST2.1, I had a scatter graph with a renderer function changing all sprite rotation and color based on values in the store. It was working well.
I upgraded to ST2.2.0 and now I'm having trouble rebuilding the same function.
code for ST2.1 - was working.
series: [
{
type: 'scatter',
xField: 'local_date_time',
yField: 'wind_spd_kt',
marker: { ...
},
style: {
renderer: function (target, sprite, index, storeItem) {
var sweather = Ext.getStore('Sun');
if (index < sweather.getCount() ){
target.rotationRads = storeItem.data.sun_dir;
if (storeItem.data.sun_spd_kt < 10) {
target.fill = '#ff0000'; //red
//console.log ( index + ' : <10 :' + storeItem.data.sun_spd_kt )
}
else { target.fill = '#00EE00'; } //green
}
}
},
COde in ST2.2.0 that I tried:
style: {
renderer: function (sprite, config, rendererData, index) {
sprite.rotationRads = rendererData.store.data.all[index].raw.sun_dir
sprite.attr.fillStyle = '#ff0000'
}
}
Has Anyone used "renderer" successfully in ST2.2.0?
I made up a solution to your problem. Could you try the following ?
renderer: function (sprite, config, rendererData, index) {
if (index % 2 == 0) {
return { strokeStyle: 'red' };
}
}