google maps, client libraries node js, distance matrix request js - node.js

I am trying to implement a google maps distance matrix api request using, node JS google Client library. specifically
#googlemaps/google-maps-services-js
The problem am facing, I can only finds source code example for elevation in the documentation.
const client = new Client({});
client
.elevation({
params: {
locations: [{ lat: 45, lng: -110 }],
key: "asdf",
},
timeout: 1000, // milliseconds
})
.then((r) => {
console.log(r.data.results[0].elevation);
})
.catch((e) => {
console.log(e.response.data.error_message);
});
I need source code example for Distance Matrix so I can implement point to point distance calculation within node JS, using the client library.
const client = new Client({});
client
.distanceMatrixrequest()

client
.distancematrix({
params: {
key: '<YOUR_KEY>',
origins: ['Greenwich, England'],
destinations: ['Stockholm, Sweden'],
travelMode: 'DRIVING',
// Feel free to set more params
},
timeout: 1000, // milliseconds
})
.then((r) => {
console.log(r.data.rows[0]?.elements);
res.json(r.data);
})
.catch((e) => {
console.log(e.response.data.status);
});
Response comes in this format:
[
{
distance: { text: '1,880 km', value: 1880123 },
duration: { text: '20 hours 59 mins', value: 75548 },
status: 'OK'
}
]

Related

How to get random records from Strapi v4 ? (I answered this question)

Strapi doesn't have any endpoint to get random data for this purpose you should write some custom code for your endpoint
custom route for that endpoint you want
// path: ./src/api/[your-endpiont]/routes/[custom-route].js
module.exports = {
"routes": [
{
"method": "GET",
"path": "/[your-endpiont]/random", // you can define everything you want for url endpoint
"handler": "[your-endpiont].random", // random is defined as a method
"config": {
"policies": []
}
}
]
}
now you have to run yarn develop or npm ... to display a random method in your strapi panel
Save this setting and retry to reach the random endpoint.
create a function as a service for getting random data in your endpoint API services.
// path: ./src/api/[your-endpiont]/services/[your-endpiont].js
'use strict';
/**
* news-list service.
*/
const { createCoreService } = require('#strapi/strapi').factories;
module.exports = createCoreService('api::news-list.news-list', ({ strapi }) => ({
async serviceGetRandom({ locale, id_nin }) { // these parametrs come from query
function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
const elements = [];
function getRandomElement(arr) {
if (elements.length < numberOfRandomElementsToExtract) {
const index = Math.floor(Math.random() * arr.length)
const element = arr.splice(index, 1)[0];
elements.push(element)
return getRandomElement(arr)
} else {
return elements
}
}
return getRandomElement([...array])
}
const newsListArray = await strapi
.db
.query("api::news-list.news-list")
.findMany({
where: {
locale: locale, // if you have multi-language data
$not: {
id: id_nin, // depend on where this endpoint API use
},
publishedAt: {
$notNull: true,
},
},
sort: [{ datetime: 'asc' }],
limit: 10,
populate: {
content: {
populate: {
thumbnail: true,
},
},
},
//? filter object throws an error when you used populate object, everything you want to filter properly best write into where{}
// filters: {
// publishedAt: {
// $notNull: true,
// },
// locale: locale
// }
})
if (!newsListArray.length) {
return null
}
return getRandomElementsFromArray(newsListArray, 2)
}
}));
explain code:
Strapi provides a Query Engine API to interact with the database layer at a lower level
strapi.db.query("api::news-list.news-list").findMany({})
The Query Engine allows operations on database entries,
I wrote this for my purpose probably you should change based on what you needed
{
where: {
locale: locale,
$not: {
id: id_nin
},
publishedAt: {
$notNull: true,
},
},
sort: [{ datetime: 'asc' }],
limit: 10,
populate: {
content: {
populate: {
thumbnail: true,
},
},
}
}
when you get data from your query, passed it to that function getRandomElementsFromArray(newsListArray, 2) to get some random item (how many random items do you want ? pass the second parameter)
At least if your array is null return null otherwise return data
create the controller
Controllers are JavaScript files that contain a set of methods, called actions, reached by the client according to the requested route so we going to call our services in this section
// path: ./src/api/[your-endpoint]/controllers/[your-endpoint].js
'use strict';
/**
* news-list controller
*/
const { createCoreController } = require('#strapi/strapi').factories;
module.exports = createCoreController('api::news-list.news-list', ({ strapi }) => ({
async random(ctx) { // name of this methods related to something we define in route ("handler": "[your-endpiont].random",)
const entity = await strapi.service('api::news-list.news-list').serviceGetRandom(ctx.query) // call our services, you can send all query you get from url endpoint (notice that you should write your endpoint api in strapi.service("your-endpoint"))
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
// console.log(entity);
}
}));
I call this endpoint in my project nextjs & stapi cms
export const getRandomNewsItem = (id, locale) => {
return API
.get(`/news-list/random?locale=${locale}&id_nin=${id}`)
.then(res => res.data);
};
That's it, I'll hope you all get what to do
all resources you need
https://docs.strapi.io/developer-docs/latest/development/backend-customization/routes.html#creating-custom-routers
https://docs.strapi.io/developer-docs/latest/development/backend-customization/services.html#implementation
https://docs.strapi.io/developer-docs/latest/development/backend-customization/controllers.html#adding-a-new-controller
https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/query-engine-api.html
https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/query-engine/filtering.html#and
https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/entity-service/order-pagination.html#ordering
https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/entity-service/order-pagination.html#ordering
https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/query-engine/populating.html

Business discovery user media with location

i'm fetching all user details with latest media and some insights, but the posts are not including the location:
const fields =
'fields=business_discovery.username(jbalvin){id,ig_id,name,username,profile_picture_url,followers_count,media_count,biography,follows_count,media{comments_count,like_count,timestamp,media_type,media_product_type,location{city}}}';
const res = fetch(
`https://graph.facebook.com/v12.0/${id}?${fields}&access_token=${token}`
)
.then((response) => response.json())
.then((data) => console.log(data));
This is the answer i'm getting:
{
business_discovery: {
id: '17841401525860163',
ig_id: 10482862,
name: 'J Balvin',
username: 'jbalvin',
profile_picture_url: 'https://scontent.fbaq2-2.fna.fbcdn.net/v/t51.2885-15/272307439_140470511724764_4263731586488463919_n.jpg?_nc_cat=1&ccb=1-5&_nc_sid=86c713&_nc_eui2=AeErYr-NceD1DvlTdMFw7QPcrlXwvFWx4ZOuVfC8VbHhkxGyDdL5-tOIFpeIU77PgqeJvRY6gXVRGSpdxBP8SxNL&_nc_ohc=RswtWyTHU8wAX_u4pcF&_nc_ht=scontent.fbaq2-2.fna&edm=AL-3X8kEAAAA&oh=00_AT8p18_oXvJsxCQV632bq6vmDcxMrJ9HHnQdk5E-s29bDw&oe=61F82A7A',
followers_count: 51214234,
media_count: 12940,
follows_count: 1927,
media: {
data: [
{
comments_count: 1550,
like_count: 427154,
timestamp: '2022-01-25T01:00:20+0000',
media_type: 'CAROUSEL_ALBUM',
media_product_type: 'FEED',
id: '17928326101919137'
},
],
paging: {
cursors: {
after: 'QVFIUjh1cGMwNnFnbldraGtuOU5fcGNDNFF6ekdvWkhSV3o3SjdJQ25iMl9tU0ZAoNTlMVlEtcnh6VUZAKQnFoLUFTc3phREdlZAmNCR0NGMkV4QldhNkFORk5R'
}
}
}
},
i deleted the other 24 post because the response is too long. The thing is that the post that i'm showing there has a location on instagram, but the api is not responding with it, how can i get the post location?

how can we use data received through axios put request on client side in mern stack?

I have sent category Id to the Nodejs through this code
const catHandler = async (catId) => {
const data = Axios.put('/api/products/categories/filter', {catId: catId},
{
"headers": { "content-type": "application/json", },
}
).then( categoriesProducts => {
console.log(categoriesProducts.data.products)
})
}
and this is my route for this
router.put('/categories/filter', async (req, res) => {
try {
const findCategory = await Category.find({ _id: req.body.catId });
if (findCategory) {
const productsByCategory = await Product.find(
{ category: req.body.catId }
).then(products => {
res.status(200).json({ products });
})
}
} catch (error) {
console.log('categories filter error', error)
}
})
The products of specific category are being shown in the console.log(categoriesProducts.data.products) on the react front end side like below
0: {_id: "5f7c88756746363148792982", name: "Simple Pizza", price: 5.6, image: "1601996916374.jpg", countInStock: 434, …}
1: {_id: "5f7c88976746363148792983", name: "Smoked Pizza", price: 7.8, image: "1601996951114.jpg", countInStock: 88, …}
2: {_id: "5f7c88c56746363148792984", name: "Large Cheezy Pizza", price: 9.4, image: "1601996997474.jpg", countInStock: 434, …}
But I want to display these products on the front end side. I have tried to use axios.get method but with get method how can I can send category Id to backend. So if any one has any idea how to do that Plz guide me.
you can use the query params with get method in node js
you can get query params by req.query in nodeJs
example
passing category id from front end -
api/products/categories/filter?cid=1
getting query param in the backend
const catId = req.query.cid
You can use below code to pass parameter to API get method.
fetch("/api/products/categories/filter?catId" + catId)
.then((res) => res.json())
.then((json) => {
this.setState({
Items: json,
});
});
And also you first create new state named as Items such as below.
this.state = {
Items: []
};
And finally Iterate on Items.
BR

When response is embed it only returns 1 set answer out of a random selection Discord.js

I'm coding a very simple discord.js bot, and I have a command for when someone types /mahdi it returns a random response out of a list that I made. When it returned in a normal message, it would pick a random one each time, but then I made it so it sends in an embed, and now it picks one and sends that all the time, until I take the bot offline which then picks another one to send all the time when it goes back online.
Does anyone know what I'm doing wrong?
Code to randomly select a phrase from a list:
const mahdis = ['phrase1', 'phrase2', 'phrase3', 'phrase4', 'phrase5', 'phrase6', 'phrase7', 'phrase8'];
const mahdi = Math.floor(Math.random() * mahdis.length);
Code to send it as an embed:
const mahdiEmbed = {
color: 'c0ffee',
author: {
name: 'supreme sauce 3.0',
icon_url: 'https://cdn.discordapp.com/avatars/733259381898215495/739b2c90fbfab048abb236b0e89770be.webp?size=256',
},
fields: [
{
name: mahdis[mahdi],
value: '- mahdi',
},
],
footer: {
text: 'supreme sauce 3.0 --- developed by ed#6969',
icon_url: 'https://media.discordapp.net/attachments/693559044329177151/733614790567788574/kirbmelon.gif',
},
};
client.on('message', message => {
if(message.content === '/mahdi') {
message.channel.send({ embed: mahdiEmbed });
}
});
Thanks :)
Since you defined mahdi (which should be random every message) outside of your message event, it will be randomized only once, and that's when your bot starts.
If you put it in your message event, it will be randomized every new message. And that's what you want.
const mahdis = ['phrase1', 'phrase2', 'phrase3', 'phrase4', 'phrase5', 'phrase6', 'phrase7', 'phrase8'];
client.on("message", message => {
const mahdi = Math.floor(Math.random() * mahdis.length);
if (message.content.toLowerCase() == "mahdi") {
const mahdiEmbed = {
color: 'c0ffee',
author: {
name: 'supreme sauce 3.0',
icon_url: 'https://cdn.discordapp.com/avatars/733259381898215495/739b2c90fbfab048abb236b0e89770be.webp?size=256',
},
fields: [
{
name: mahdis[mahdi],
value: '- mahdi',
},
],
footer: {
text: 'supreme sauce 3.0 --- developed by ed#6969',
icon_url: 'https://media.discordapp.net/attachments/693559044329177151/733614790567788574/kirbmelon.gif',
},
};
message.channel.send({embed: mahdiEmbed});
}
})

Why isn't data being written to my Amazon DynamoDB table?

I'm currently creating an amazon alexa skill that lets users create lists and recall them later with help from AWS's DynamoDB. When my skill attempts to put items into the database table, things turn up green and no errors happen. However, when checking the database table, nothing is written there. Here is the code from my skill where I try to take a slot value and put it into the database:
// query DynamoDB to see if the item exists first
docClient.get(checkIfItemExistsParams).promise().then(data => {
console.log('Get item succeeded', data);
const groceryItem = data.Item;
if (groceryItem) {
const errorMsg = `Grocery item ${name} already exists!`;
this.emit(':tell', errorMsg);
throw new Error(errorMsg);
}
else {
// no match, add the recipe
return docClient.put(dynamoParams);
}
})
.then(data => {
console.log('Add item succeeded', data);
this.emit(':tell', `Grocery item ${name} added!`);
})
.catch(err => {
console.error(err);
});
And here are the server logs first for my skill preparing the request, then for the request actually being sent. No errors occur before or after:
2018-05-21T02:19:53.937Z 72ba8ffb-5c9d-11e8-83b7-af0480d5c4a1 Attempting to add item to list { TableName: 'Groceries',
Item:
{ Name: 'apples',
UserId: 'userid was here, not sure if I should show that publically' } }
host: 'dynamodb.us-east-1.amazonaws.com',
port: 443,
hostname: 'dynamodb.us-east-1.amazonaws.com',
pathname: '/',
path: '/',
href: 'https://dynamodb.us-east-1.amazonaws.com/' },
_clientId: 1 },
operation: 'putItem',
params:
{ TableName: 'Groceries',
Item:
{ Name: 'apples',
UserId: 'userid was here, not sure if I should show that publically' } },
Anyone have any ideas on what might be happening? Thanks.

Resources