How to change the marker image on click of the symbol in ARCGIS API JS? - arcgis

I tried this approach but its highlighting the symbol. How can i change marker image on click of the symbol.
My code:
let centroidRenderer = {
type: "simple",
symbol: {
type: "picture-marker",
// url: "https://static.vecteezy.com/system/resources/previews/000/582/855/original/vector-location-pin-icon.jpg",
url: "images/Location-map.png",
width: "26",
height: "26"
}
};
let locationpin = new FeatureLayer({
url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/Centroids/FeatureServer/0",
renderer: centroidRenderer
});
// var privateSchoolsPoly = new FeatureLayer({
// url:
// "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/PrivateSchoolEnrollmentNoRendering/FeatureServer/0",
// outFields: ["*"],
// opacity: 0.8,
// renderer: renderer,
// });
let symbol;
view.when(async () => {
const layerView = await view.whenLayerView(locationpin);
view.on('click', async (e) => {
const {results} = await view.hitTest(e);
try {
const { graphic } = results.find(x => x.graphic.attributes.OBJECTID);
if(symbol.url=="images/Location-map.png"){
(symbol.url==" https://static.vecteezy.com/system/resources/previews/000/582/855/original/vector-location-pin-icon.jpg")
}
else{
symbol.url==" images/Location-map.png"
}
// fWidget.graphic = graphic;
symbol = layerView.highlight(graphic);
} catch(err) {}
});
});
view.when(function() {
map.addMany([locationpin]);
});
Expected O/P:

It seems there is some syntax errors in your code.
Try this:
view.on("click", function (evt) {
// Search for symbols on click's position
view.hitTest(evt.screenPoint).then(function(response) {
//loop over each graphics clicked
response.results.forEach(function(result) {
if (result.graphic.symbol.url=="images/Location-map.png"){
result.graphic.symbol.url = "https://static.vecteezy.com/system/resources/previews/000/582/855/original/vector-location-pin-icon.jpg";
} else {
result.graphic.symbol.url = "images/Location-map.png";
}
});
});
});

Related

Fileupload - Get image resolution

I am trying to get the resolution (height, width) of the images I am sending to the backend. Attention, in this example several images are sent to the backend at once. So, we are working with loops!
I tried to find a solution in the backend, but couldn't find anything. Here is the corresponding stackoverflow question I asked.
Now I am asking for a way to do this in the frontend. When I console.log(file) following example will be outputed:
lastModified: 1657671728196
lastModifiedDate: Wed Jul 13 2022 02:22:08 GMT+0200 (Mitteleuropäische Sommerzeit) {}
name: "Example.png"
size: 3128
type: "image/png"
webkitRelativePath: ""
Too bad that the resolution is not callable this way. Furthermore I would like to save the img-type in the db but not as image/png but as png or jpeg etc. only.
async submitFiles() {
const formData = new FormData()
for (let i = 0; i < this.files.length; i++) {
const file = this.files[i]
formData.append('files', file)
console.log(file)
}
try {
const response = await this.$axios.post('/api/upload-files', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
this.uploadPercentage = parseInt(
Math.round((progressEvent.loaded / progressEvent.total) * 100)
)
},
})
const result = response.data
if (result.success) {
if (this.uploadPercentage === 100) {
this.$nuxt.refresh()
this.$emit('exit', true)
}
}
} catch (err) {
console.log(err)
}
},
Checking for resolution in the browser is pretty straightforward. All you need to do is create an Image element out of the user provided file.
export default {
data() {
return {
files: [],
formData: null
}
},
watch: {
formData() {
if (this.formData.getAll('files').length === this.files.length) {
this.submitFiles()
}
},
},
mounted() {
this.formData = new FormData()
},
methods: {
async submitFiles() {
try {
const data = this.formData
const response = await this.$axios.post(
'/api/upload-files', data,
{
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
this.uploadPercentage = parseInt(
Math.round((progressEvent.loaded / progressEvent.total) * 100)
)
},
}
)
const result = response.data
if (result.success) {
if (this.uploadPercentage === 100) {
this.$nuxt.refresh()
this.$emit('exit', true)
}
}
} catch (err) {
console.log(err)
}
},
processFiles() {
for (let i = 0; i < this.files.length; i++) {
const file = this.files[i]
const img = new Image()
const vm = this
img.onload = function () {
file.width = this.width
file.height = this.height
console.log(file)
vm.formData.append('files', file)
}
img.src = URL.createObjectURL(file)
}
},
},
}
As for the mime type of the image you could split the string by / and save the right half:
const [,type] = file.type.split('/')
EDIT:
The callbacks will not be called when you try to post your data (inside the try block), so it would be a good idea to watch the formData until it's length matches the length of the files array. Then we know all of the images are processed and it's safe to send data to our backend.

How to call a function right after another function has executed without button onpress

I have two functions and I am trying to call GetReceipt when the button (with uploadphoto function) has been clicked and right after the UploadPhoto function like getting data right after uploading a photo.
I tried putting this.GetReceipt() inside the UploadPhoto() function somehow it does not work but if i separate them into two different buttons both functions work perfectly.
Here is the code:
UploadPhoto=(pickedImagePath)=> {
var pickedImagePath = this.state.pickedImagePath;
console.log(pickedImagePath);
var APIURL="http://10.0.2.2/api/postform.php";
let uriParts = pickedImagePath.split('/');
let image = uriParts[uriParts.length - 1];
var ImageData= new FormData();
ImageData.append('photo', {
uri:pickedImagePath,
name: image,
type: 'image/jpeg'
})
fetch(APIURL,
{
headers:{
'Accept':'application/json',
'Content-Type':'multipart/form-data'
},
method:'POST',
body: ImageData
})
.then((response)=>
{
console.log('succ ')
console.log(response)
})
.catch((error)=>
{
console.log('err ')
console.log(error)
}
)
}
GetReceipt=()=> {
var title = this.state.title;
var amount = this.state.amount;
var transactionType = this.state.transactionType;
var note = this.state.note;
var date = this.state.date;
var APIURL="http://10.0.2.2/api/getform.php";
var headers2={
'Accept':'application/json',
'Content-Type':'application.json'
}
fetch(APIURL,
{
method:'POST',
headers: headers2,
})
.then((response)=>response.text())
.then((response)=>
{
// this.setState({array:response});
this.setState({title:response[3]});
this.setState({amount:response[0]});
this.setState({date:response[1]});
this.setState({note:response[2]});
// this.setState({results:response});
console.log("results:",response[2]);
console.log("merchant:",this.state.title);
console.log("results:",response);
})
.catch((error)=>
{
alert("Error"+error);
}
)
}

How to share screen using webRTC

I need to get the screen sharing working. It is working if it is video sharing. This is the code:
public n = navigator as any;
ngAfterViewInit(): void {
const video = this.myVideo.nativeElement;
let peerx: any;
this.n.getUserMedia =
this.n.getUserMedia ||
this.n.webkitGetUserMedia ||
this.n.mozGetUserMedia ||
this.n.msGetUserMedia;
}
this.n.getUserMedia( // this.n.mediaDevices.getDisplayMedia
{
video: {
madatory: {
chromeMediaSource: 'screen',
maxWidth: 1920,
maxHeight: 1080,
minAspectRatio: 1.77
},
}
},
(stream: any) => {
peerx = new SimplePeer({
initiator: location.hash === '#init',
trickle: false,
stream,
});
peerx.on('signal', (data) => {
const strData = JSON.stringify(data);
console.log(strData);
this.targetpeer = data;
});
peerx.on('stream', (streamX: any) => {
if ('srcObject' in video) {
video.srcObject = streamX;
} else {
video.src = window.URL.createObjectURL(streamX);
}
const playPromise = video.play();
if (playPromise !== undefined) {
playPromise
.then((_) => {
video.play();
})
.catch((error) => {
console.log(`Playing was prevented: ${error}`);
});
}
});
If I change the line 'this.n.getUserMedia(....)' to this 'this.n.mediaDevices.getDisplayMedia(...)', I do not get the 'signal' (the key that I need to paste on the client to connect).
You are attempting to mix a constraints style that was needed years ago when a Chrome extension was required with getDisplayMedia. That isn't going to work.
const stream = await navigator.mediaDevices.getDisplayMedia({video: true})
See here for a canonical sample.

Hapi Js File Upload Struggling

today i trying to get some file upload with Hapi Js, i follow all Google Result with similarity of code.
this the code :
server.route({
method: "POST",
path: `${PUBLIC_URL}${THEME_URL}/create`,
handler: async (request: any, reply: ResponseToolkit) => {
console.log(request.payload.file, 'payload')
return reply.response(request.payload)
},
options: {
payload: {
output: 'stream',
allow: 'multipart/form-data',
parse: false,
}
}
})
with thats code i cant get request.payload my file or data, this is my request with postman:
post file with postman
enter image description here
i got undifined at request.payload.file
if i turn payload :{parse:true} i get unsuported media types
thanks for attention
If you are using the below version then you must be using the following syntax
#hapi/hapi: 18.x.x +
payload: {
parse: true,
multipart: {
output: 'stream'
},
maxBytes: 1000 * 1000 * 5, // 5 Mb
}
Also, you can also try using Joi to validate your payload.
{
method: 'POST',
path: '/upload',
options: {
payload: {
maxBytes: 209715200,
output: 'stream',
parse: true,
allow: 'multipart/form-data',
multipart: true // <-- this fixed the media type error
},
handler: async (req, reply) => {
try {
// await importData(req.payload)
// return reply.response("IMPORT SUCCESSFULLY")
const data = await req.payload;
// let final = await importFile(data)
// return reply.response("final", final)
if (data.file) {
let name = await data.file.hapi.filename;
console.log("FIlename: " + name);
let path = await __dirname + "/uploads/" + name;
let file = await fs.createWriteStream(path);
await data.file.pipe(file);
await data.file.on('end', async function (err) {
// var ret = {
// filename: data.file.hapi.filename,
// headers: data.file.hapi.headers
// }
if (typeof require !== 'undefined')
XLSX = require('xlsx');
const workbook = await XLSX.readFile(path);
var sheetName = workbook.SheetNames;
console.log("row======>>>>");
await sheetName.forEach(async () => {
let xlData = await XLSX.utils.sheet_to_json(workbook.Sheets[sheetName[0]]);
console.log("xlData", xlData);
for (let i = 0; i < xlData.length; i++) {
console.log("if condition", xlData[i].phone)
const userCheck = await getUserIdService({ where: { phone: xlData[i].phone } });
console.log("userCheck", userCheck.data)
console.log("test", !(userCheck.data === null));
if (!(userCheck.data === null)) {
console.log("finally ", userCheck.data?.phone)
await uploadUpdateService(xlData[i], { where: { phone: userCheck.data?.phone } });
// return finalUpdate
// return reply.response("updated")
}
else if (!xlData[i].customerID) {
await uploadCreate(xlData[i]);
// return finalCreate
}
}
})
})
}
} catch (err) {
console.log('Err----------------------' + err);
// error handling
return reply.response(Boom.badRequest(err.message, err))
// return reply.response(Boom.badRequest(err.message, err));
}
}
}
}

TypeError: instance.web.core is undefined

I can not add new action in Odoo9
openerp.pr_finance = function(instance, local) {
var _t = instance.web._t, _lt = instance.web._lt;
var QWeb = instance.web.qweb;
var Widget = instance.web.Widget;
var core = instance.web.core;
var data = instance.web.data;
var session = instance.web.session;
var utils = instance.web.utils;
var Model = instance.web.Model;
var ControlPanelMixin = instance.web.ControlPanelMixin;
instance.web.ListView.include({
init: function() {
//console.log('JS loaded');
this._super.apply(this, arguments);
},
render_buttons: function(data) {
console.log('JS loaded load_list');
console.log(data);
this._super(data);
if (this.$buttons) {
this.$buttons.find('.oe_my_button').click(this.proxy('do_import_file_csv_ya_tz')) ;
}
},
do_import_file_csv_ya_tz: function () {
console.log('123123123123123123 ooops....');
this.do_action(
{
name: _t("IMPORT MY FILE"),
type: "ir.actions.client",
tag: 'import_csv',
params: {}
}
);
}
});
var import_csv_yandex = Widget.extend({
template: 'ImportViewYaTC',
start: function () {
console.log("ImportViewYandexTC page loaded");
},
});
var DataImport = Widget.extend(ControlPanelMixin, {
template: 'ImportView',
init: function(parent, action) {
console.log("init ImportView");
this._super.apply(this, arguments);
action.display_name = _t('Import a File');
},
start: function () {
console.log("ImportView page loaded");
},
});
console.log("core.action_registry.add");
try {
instance.web.core.action_registry.add('import_csv', DataImport);
} catch (err) {
console.log(err);
}
console.log("core.action_registry.add - OK!");
}
I received error here:
instance.web.core.action_registry.add('import_csv', DataImport);
Error:
TypeError: instance.web.core is undefined Stack trace:
openerp.pr_finance#http//localhost:8069/web/content/2798-e13ba1c/web.assets_backend.js:4579:1276
start_modules#http//localhost:8069/web/content/2798-e13ba1c/web.assets_backend.js:3235:1
.init#http//localhost:8069/web/content/2798-e13ba1c/web.assets_backend.js:3229:3951
OdooClass.extend/Class.include/
Why this variable is undefined?
You need to use require to get the variables of the env: ie.
odoo.define('yourmodulename.pr_finance', function (require) {
"use strict";
var core = require('web.core');
});
a good place to look at to understand inheritance in odoo is the github.com/oca/web repo.