We are using the Google Places API to add places and those should reflect in the Map loaded with the API key from the same console project. However, the added places do not reflect on the map, even after a long period of time.
https://developers.google.com/places/webservice/add-place
if somebody has used these APIs, please suggest some insight as to why this is happening. I had enabled the APis from the console project.
Thanks
Code is as follows:
function addPlaceToGoogle(data, callback) {
var request = require('request');
var requestUrl = 'https://maps.googleapis.com/maps/api/place/add/json?key=' + config.get("google_key");
var type = "store";
if (data.type) {
type = data.type;
}
var newData =
{
"location": {
"lat": data.latitude,
"lng": data.longitude
},
"accuracy": 50,
"name": data.address,
"address": data.address,
"types": [type]
};
var request = require('request');
var options = {
uri: requestUrl,
method: 'POST',
json: newData
};
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the shortened url.
if (body.status == 'OK') {
data.placeId = body.place_id;
} else {
data.placeId = "";
}
data.type = type;
callback(null, data);
}
});
}
Related
I'm trying to show JSON data got from API in Google Data Studio.
so I created community connector and in script verified JSON data from api.
here is script code.
function getFields(request) {
var cc = DataStudioApp.createCommunityConnector();
var fields = cc.getFields();
var types = cc.FieldType;
// var aggregations = cc.AggregationType;
fields.newDimension()
.setId('username')
.setType(types.TEXT);
fields.newMetric()
.setId('version')
.setType(types.NUMBER);
fields.newDimension()
.setId('address')
.setType(types.TEXT);
return fields;
}
function getSchema(request) {
var fields = getFields(request).build();
return { schema: fields };
}
function responseToRows(requestedFields, response) {
// Transform parsed data and filter for requested fields
var row = [];
requestedFields.asArray().forEach(function (field) {
switch (field.getId()) {
case 'username':
return row.push(response.result.user.createdByName);
case 'version':
return row.push(response.result.user.version);
case 'address':
return row.push(response.result.user.address);
default:
return row.push('');
}
});
return { values: row };
}
function getData(request) {
var requestedFieldIds = request.fields.map(function(field) {
return field.name;
});
var requestedFields = getFields().forIds(requestedFieldIds);
// Fetch and parse data from API
var options = {
'method' : 'post',
'contentType': 'application/json',
"headers":{ "api-key": request.configParams.api_key },
"payload": "{username:\""+username+"\", password: \""+password+"\"}",
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
var parsedResponse = JSON.parse(response);
var rows = responseToRows(requestedFields, parsedResponse);
console.log('getData request', parsedResponse);
return {
schema: requestedFields.build(),
rows: rows
};
}
this is JSON file
{
"result": {
"user": {
"type": "User",
"id": 1073787385,
"address": null,
"version": 1675247127459332096,
"createdBy": 310055,
"createdByName": "Jeirick Hiponia",
}
}
}
Result in data studio.
why don't address show?
And why no data? I think row.push in responseToRows() function is issue.
I'd like to show data like this.
I created api connector myself.
This is Code.gs file.
var cc = DataStudioApp.createCommunityConnector();
function getAuthType() {
var AuthTypes = cc.AuthType;
return cc
.newAuthTypeResponse()
.setAuthType(AuthTypes.NONE)
.build();
}
function getConfig(request) {
var config = cc.getConfig();
config.newInfo()
.setId('instructions')
.setText('Enter api url to get data , api token , username and password');
config.newTextInput()
.setId('api_url')
.setName('Enter a api url')
.setPlaceholder('https://');
config.newTextInput()
.setId('api_key')
.setName('Enter a Api Key')
.setHelpText('e.g. xxxxxxxxxxxxxxxxx');
config.newTextInput()
.setId('username')
.setName('Enter a username');
config.newTextInput()
.setId('password')
.setName('Enter a username')
.setType('password');
return config.build();
}
function getFields(request) {
var cc = DataStudioApp.createCommunityConnector();
var fields = cc.getFields();
var types = cc.FieldType;
var aggregations = cc.AggregationType;
fields.newDimension()
.setId('username')
.setType(types.TEXT);
fields.newMetric()
.setId('version')
.setType(types.NUMBER);
fields.newDimension()
.setId('address')
.setType(types.TEXT);
return fields;
}
function getSchema(request) {
var fields = getFields(request).build();
return { schema: fields };
}
function responseToRows(requestedFields, response) {
// Transform parsed data and filter for requested fields
return response.map(function(data) {
var row = [];
requestedFields.asArray().forEach(function (field) {
switch (field.getId()) {
case 'username':
return row.push(data.result.user.createdByName);
case 'version':
return row.push(data.result.user.version);
case 'address':
return row.push(data.result.user.address);
default:
return row.push('');
}
});
return { values: row };
});
}
function getData(request) {
var requestedFieldIds = request.fields.map(function(field) {
return field.name;
});
var requestedFields = getFields().forIds(requestedFieldIds);
// Fetch and parse data from API
const API_KEY = request.configParams.api_key;
var url = request.configParams.api_url;
var options = {
'method' : 'post',
'contentType': 'application/json',
"headers":{ "api-key": API_KEY },
"payload": "{username:\""+request.configParams.username+"\", password: \""+request.configParams.password+"\"}",
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
var parsedResponse = JSON.parse(response);
var rows = responseToRows(requestedFields, parsedResponse);
return {
schema: requestedFields.build(),
rows: rows
};
}
data from api in postman.
{
"result": {
"user": {
"type": "User",
"id": 1073787385,
"address": null,
"version": 1675221634311192576,
"createdBy": 310055,
"createdByName": "Jeirick Hiponia",
}
}
}
In the Apps Script development environment, Clicked on Deploy > Test deployments to open the Test deployments dialog.
To load your connector in Looker Studio, replace the <HEAD_DEPLOYMENT_ID> placeholder in the following link with your connector's Head Deployment ID and follow the link in your browser:
what is the issue?
I am trying to send direct message through twitter api using Twitter-Lib through App-Script. Below is the definition of sendMsg fucntion
function sendMsg(user, tweet) {
var twitterKeys = {
TWITTER_CONSUMER_KEY: "<<>>",
TWITTER_CONSUMER_SECRET: "<<>>",
TWITTER_ACCESS_TOKEN: "<<>>",
TWITTER_ACCESS_SECRET: "<<>>",
}
var props = PropertiesService.getScriptProperties();
// props.deleteAllProperties()
props.setProperties(twitterKeys);
var service = new Twitterlib.OAuth(props);
if ( service.hasAccess() ) {
var user_id = '77773855';
var dm_link = 'https://api.twitter.com/1.1/direct_messages/events/new.json'
var response = service.fetch(dm_link, {
method: "POST",
muteHttpExceptions: true,
data: {"event":
{"type": "message_create",
"message_create": {
"target": {"recipient_id": user_id},
"message_data": {"text": "Hello"}
}
}
}
});
console.log(response.getResponseCode())
}
}
But when I execute this code, the response is always empty and response.getResponseCode() returns 422. Any leads on what I am doing wrong?
How to convert the below JAVA code to apps script?
I want the quote to be pulled into my sheet
Ticker symbol is in A2
I want the price in B2
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://rest.yahoofinanceapi.com/v6/finance/quote/AAPL"))
.header("x-api-key", "YOUR-PERSONAL-API-KEY")
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
try the following script
const YOUR_PERSONAL_API_KEY = '... Your API KEY ...';
function fetch_yfapi(ticker_symbol){
let urlToFetch = `https://yfapi.net/v6/finance/quote?region=US&lang=en&symbols=${ticker_symbol}`,
options = {
method: 'get',
headers: {
'accept' : 'application/json',
'X-API-KEY' : YOUR_PERSONAL_API_KEY, },
muteHttpExceptions: true
},
fetched = {
code: null,
body: null,
}
try{
const response = UrlFetchApp.fetch(urlToFetch, options);
fetched.code = response.getResponseCode();
fetched.body = response.getContentText();
if (fetched.code !== 200) {
console.log(Utilities.formatString("Request failed. Expected 200, got %d: %s", fetched.code, fetched.body))
}
} catch(e) {
console.log('Method call error UrlFetchApp.fetch : %s',e)
}
return fetched.body
}
function getTickerData(){
let sheet = SpreadsheetApp.getActive().getSheetByName('... sheet name ...'),
ticker_symbol = sheet.getRange('A2').getValue();
if (ticker_symbol.length) {
let ticker_data = fetch_yfapi(ticker_symbol);
if (ticker_data) {
console.log(ticker_data);
sheet.getRange('B2').setValue(JSON.parse(ticker_data).quoteResponse.result[0].ask)
}
}
}
I didn't know exactly what price you wanted to get in the end - so I put 'ask'. In the console you can see the whole body of the returned response
I'm struggling with trying to figure out what I'm doing wrong, mostly down to not having a good understanding of AngularJS due to being new. The main goal is that I'm trying to list out all the values in the additionalText list out on the front-end, but it seems to be causing issue with this error:
Error: [$http:badreq] Http request configuration url must be a string or a $sce trusted object. Received: []
Context:
I have table in my application that relies on the API, this variable contains a list and outputs the following:
{
"name": "TEST",
"description": "TEST",
"additionalText": [
{
"name": "TEST",
"description": "TEST",
"lockId": 0
}
{
"name": "TEST",
"description": "TEST",
"lockId": 0
}
],
"lockId": 0
}
The API is working as expected, I can carry out all the necessary REST calls successfully. So I'm not struggling with that, the front-end is where I am having some difficulty.
HTML:
<td data-title="'additionalTexts'" sortable="'additionalTexts'">
<span ng-repeat="additionalText in additionalTextList[entity.name]">
<i>{{additionalText.name}}</i><br>
</span>
</td>
AngularJS:
$scope.refreshTextTable= function() {
SpringDataRestService.query(
{
collection: "APIURL"
},
function (response) {
var additionalTextRoles = response;
$scope.textTableOptions = new NgTableParams({}, {
dataset: additionalTextRoles,
counts: [],
});
// Also populate a list of all linked roles
for (var i = 0; i < additionalTextRoles.length; i++) {
var additionalTextRole = additionalTextRoles[i];
// This approach allows you to inject data into the callback
$http.get(additionalTextRole.additionalText).then((function (additionalTextRole) {
return function(response) {
$scope.additionalTextList[additionalTextRole.name] = response.additionalText;
};
})(additionalTextRole));
}
},
function (response) {
// TODO: Error Handling
}
);
};
Any help would be greatly appreciated, I'm really struggling with this one.
Can you try this below code:
$scope.refreshTextTable = function() {
SpringDataRestService.query({
collection: "APIURL"
},
function(response) {
var additionalTextRoles = response;
$scope.textTableOptions = new NgTableParams({}, {
dataset: additionalTextRoles,
counts: [],
});
// Also populate a list of all linked roles
for (var i = 0; i < additionalTextRoles.length; i++) {
var additionalTextRole = additionalTextRoles[i];
// This approach allows you to inject data into the callback
$http.get(additionalTextRole.additionalText).then((function(additionalTextRole) {
return function(response) {
$scope.additionalTextList = response.additionalText;
};
})(additionalTextRole));
}
},
function(response) {
// TODO: Error Handling
}
);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.3/angular.min.js"></script>
<td data-title="'additionalTexts'" sortable="'additionalTexts'">
<span ng-repeat="additionalText in additionalTextList">
<i>{{additionalText.name}}</i><br>
</span>
</td>
The error message says the url must be a string.
For debugging purposes, console.log the URL:
for (var i = 0; i < additionalTextRoles.length; i++) {
var additionalTextRole = additionalTextRoles[i];
// This approach allows you to inject data into the callback
var url = additionalTextRole.additionalText;
console.log(i, url);
$http.get(url).then((function (additionalTextRole) {
return function(response) {
$scope.additionalTextList[additionalTextRole.name] = response.additionalText;
};
})(additionalTextRole));
}
Also note that the response object returned by the $http service does not have a property named additionalText. So it is likely that the intention is response.data.additionalText. To avoid the IIFE, use the forEach method:
additionalTextRoles.forEach( role => {
var url = role.additionalText;
console.log(url);
$http.get(url).then((function(response) {
$scope.additionalTextList[role.name] = response.data.additionalText;
});
});