Populating Google Map Markers from Node Mongodb model - json

I need some help to populate google map markers by using data on my Mongodb with NodeJS.
This is my Model Schema (models/listing.js):
var restful = require('node-restful');
var mongoose = restful.mongoose;
// Schema
var listingSchema = new mongoose.Schema({
category: String,
title: String,
location: String,
latitude: Number,
longitude: Number,
url: String,
type: String,
type_icon: String
},
{ collection: 'listing' }
);
// Return Model
module.exports = restful.model('Listing', listingSchema);
When I use postman to GET /api/listing, this is what I have
[{
"_id": "57092ca64f43442f0bcd6a95",
"category": "services",
"title": "Musa 24 hours Printing",
"location": "16 Bali Lane, Singapore 189852",
"latitude": 1.3007598,
"longitude": 103.8588499,
"url": "http://www.musa-group.com/24hrsinternet/printing.html",
"type": "Printing",
"type_icon": "assets/icons/media/text.png",
"gallery": [
"http://i.imgur.com/HwiyMCK.png"
]},
{
"_id": "57092ca64f43442f0bcd6a96",
"category": "services",
"title": "Rocket Printers SG",
"location": "146 Jalan Bukit Merah, Singapore 160146",
"latitude": 1.2778769,
"longitude": 103.8308443,
"url": "http://www.rocketprinters-sg.com/",
"type": "Printing",
"type_icon": "assets/icons/media/text.png",
"gallery": [
"http://i.imgur.com/XPYgZ7a.jpg"
]
}]
On my index.ejs file, the markers are currently pulled from an items.json.txt file
<script>
var _latitude = 1.36080344;
var _longitude = 103.81565094;
var jsonPath = 'assets/json/items.json.txt';
// Load JSON data and create Google Maps
$.getJSON(jsonPath)
.done(function(json) {
createHomepageGoogleMap(_latitude,_longitude,json);
})
.fail(function( jqxhr, textStatus, error ) {
console.log(error);
});
// Set if language is RTL and load Owl Carousel
$(window).load(function(){
var rtl = false; // Use RTL
initializeOwl(rtl);
});
autoComplete();
</script>
How can I change the source from 'items.json.txt' to my 'Listing' database collection? Much appreciation for any help at all!

Assuming your JSON files has the same structure as the JSON returned by /api/listing, you can simply replace the URL of your JSON file by yourserver.com:XX/api/listing, assuming the server yourserver.com is running your API on port XX.
I suspect the jQuery.getJson method is just a wrapper around jQuery.get that adds parameters to the request such as an appropriate Content-Type header.

Related

Parsing objects of a JSON for input validation

I want to use a database of valid ICAO and IATA airport codes for a discord bot input in typescript. However, I am not quite sure how to call the "icao" and "iata" contstructor of all objects, as each one is defined differently and there are thousands: e.g.:
"00AK": {
"icao": "00AK",
"iata": "",
"name": "Lowell Field",
"city": "Anchor Point",
"state": "Alaska",
"country": "US",
"elevation": 450,
"lat": 59.94919968,
"lon": -151.695999146,
"tz": "America\/Anchorage"
},
"00AL": {
"icao": "00AL",
"iata": "",
"name": "Epps Airpark",
"city": "Harvest",
"state": "Alabama",
"country": "US",
"elevation": 820,
"lat": 34.8647994995,
"lon": -86.7703018188,
"tz": "America\/Chicago"
},
The bot uses the following to provide the METAR of a specific airport:
name: 'metar',
description: 'Provides the METAR report of the requested airport',
category: CommandCategory.UTILS,
executor: async (msg) => {
const splitUp = msg.content.replace(/\.metar\s+/, ' ').split(' ');
if (splitUp.length <= 1) {
await msg.reply('please provide an ICAO airport code.');
return Promise.resolve();
}
const icaoArg = splitUp[1];
if (icaoArg.length !== 4) {
await msg.reply('please provide an ICAO airport code.');
return Promise.resolve();
}
request({
method: 'GET',
url: `https://avwx.rest/api/metar/${icaoArg}`,
headers: {
Authorization: process.env.METAR_TOKEN },
}, async (error, response, body) => {
const metarReport = JSON.parse(body);å
const metarEmbed = makeEmbed({
title: `METAR Report | ${metarReport.station}`,
description: makeLines([
'**Raw Report**',
metarReport.raw,
,
'**Basic Report:**',
`**Time Observed:** ${metarReport.time.dt}`,
`**Station:** ${metarReport.station}`,
`**Wind:** ${metarReport.wind_direction.repr} at ${metarReport.wind_speed.repr}kts`,
`**Visibility:** ${metarReport.visibility.repr}${metarReport.units.visibility}`,
`**Temperature:** ${metarReport.temperature.repr}C`,
`**Dew Point:** ${metarReport.dewpoint.repr}C`,
`**Altimeter:** ${metarReport.altimeter.value.toString()} ${metarReport.units.altimeter}`,
]),
fields: [
{
name: 'Unsure of how to read the raw report?',
value: 'Type \'**.metarhow**\' to learn how to read raw METARs',
inline: false
},
],
footer: { text: 'This METAR report may not accurately reflect the weather in the simulator. However, it will always be similar to the current conditions present in the sim.' },
});
await msg.channel.send({ embeds: [metarEmbed] });
});
},
};
Currently, if a user provides an ICAO that's not valid the bot crashes, or if they provide a valid IATA, the discord api throws the user an error to provide a valid ICAO code. How would I go about cross referencing the user argument with the JSON so the bot does not crash when inputting an invalid ICAO? Thanks

getting the error like JSON schema is not correct. Enter specified JSON scehma.,Create an Array of Favorite fruits Object

0
I have the following assessment which is to Create Array of Favorite Food items object in data.json file.
The Array of Objects should have the following fields :
Name
Type
Price
After writing the JSON data, this file should be imported in loopobject.js.
I tried the above request with the below data.json
data.json
"{[{\"Name\":\"Apple\",\"Type\":\"fruit\",\"Price\":123},{\"Name\":\"pizza\",\"Type\":\"italian\",\"Price\":360},{\"Name\":\"burger\",\"Type\":\"mac&cheese\",\"Price\":321},{\"Name\":\"jangri\",\"Type\":\"sweet\",\"Price\":329}]}"
loopObject.js
var json = require('./data.json');
json.forEach(function(object) { console.log(object.Name); });
verify.js
const Joi = require('joi');
const fss =require('fs');
const schema = Joi.array().min(3).has({
Name: Joi.string().required(),
Type: Joi.string().required(),
Price: Joi.number().required(),
});
var data;
try{
data = require("./data.json");
}catch(e)
{
data={};
}
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
const result = Joi.validate(data, schema);
// You can also pass a callback which will be called synchronously with the validation result.
Joi.validate(data, schema, function (err, value) {
if(err==null)
{ console.log("JSON is valid.");
}else{
console.log("JSON schema is not correct. Enter specified JSON scehma.");
}
});
i have tried couple of ways, everything looks good,but don't know where i am doing mistake. Could you please help on this??
The JSON format is not correct, try this one:
data.json
[
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
}
]
The JSON data describes an array, and each element of that array is an object.

AngularJS getting in trouble with my JSON

I have got a JSON object from my website:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”},
}
and AngularJS to manage the dynamic content but it doesn't seem to be working:
var app = angular.module('myApp', []);
function PeopleCtrl($scope, $http) {
$scope.people = [];
$scope.loadPeople = function () {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function (data, status) {
$scope.people = data;
});
};
}
Here is a JSFiddle.
Can anybody help me with displaying data?
#qqruza to get the callback working properly in your jsfiddle.net/1zuteco7, change the url to this:
http://test.eventident.com/api/last_posts/siteid=&callpage=1&perpage=10&callback=JSON_CALLBACK
Notice the JSON_CALLBACK in the end. The rest of your app will still not work though cause you are not picking the right bindings from the returned data in your repeat directive. Try console.log(data) in the success function to click through the returned object and get to the right paths.
There were a number of issues with your JSON, I have resolved them.
It had different types of quotes in there. I have replaced them with ".
It now looks like this:
[{         
"ID": "100",
"role": {            
"subscriber": true         
},
"first_name": "Test",
"last_name": "Test2",
"custom_fields": {            
"job_title": "subscriber"         
},
}, {   
"ID": "102",
"role": {            
"subscriber": true         
},
"first_name": "Test 3",
"last_name": "Test 4",
"custom_fields": {            
"job_title": "testing"         
},       
}]
Also, you were not referencing the model fields correctly in your view.
Here is the updated working fiddle: http://jsfiddle.net/kmmmv83y/1/
You had a comma at the end of the last property, that will typically error everything out, the below JSON should work:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”}
}

How to get JSON objects from web service response

I am very new to use web services, javascript, JSON technologies and I need to use a URL to get some data to use in my HTML file.
The url that I am trying to get value of is something like this.
the result of this url in browser is like below:
{
"transactionid": "asdf",
"status": 0,
"poilist": [
{
"id": 123,
"name": "some company",
"address": "address",
"latitude": 333333,
"longitude": 333333,
"distance": 4869
},
{
.... // lots of similar nodes to above
}
}
I need to get some properties of poilist list such as longitude, latitude etc. and use them in my HTML file which includes only Javascript and HTML codes.
I made some research on internet but couldn't find a appropriate example for my situation. I don't know where to start. Any help will be appreciated.
Thank you.
You could to it this way:
var url = 'http://www.locationbox.com.tr/locationbox/services?Key=key&Cmd=PoiSearch&Typ=JSON&Latitude=30&Longitude=30&Radius=10000&Brand=SomeBrand&Keyword=';
$('#test').on('click', function () {
$.ajax({
url: url,
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// work with the response
success: function (response) {
//response is an object. use it here
console.log(response); // server response
}
});
});
http://jsfiddle.net/hlapidez/sm64g/
Hope this helps for u.
Here poilist is an JsonArray.
So u have to iterate poilist and get poilist properties
javascript example
var response = "{ "transactionid": "asdf", "status": 0, "poilist": [ { "id": 123, "name": "some company", "address": "address", "latitude": 333333, "longitude": 333333, "distance": 4869 },... ";
var poiList = response.poilist;
for(var i=0;i<poiList.length;i++){
var name = poiList[i].name;
var id= poiList[i].id;
var lat = poiList[i].latitutde;
var long = poiList[i].longitude;
console.log(lat);
console.log(long);
}
This code will print all properties of poilist in browser's console.
I would start with jQuery, specificaly with jQuery.getJSON(). Read about it here.
If you haven't used jQuery and don't know how to use it. I would look at here first.
Very basic example of loading the data and showing them in console would look like this:
$(document).ready(function() {
var url = ""; //enter an url here
$.getJSON(url, function( data ) {
console.log(data);
});
});

backbone collection fetch error

I'm trying to fetch a collection from a .json file. Here is my collection code
define(['jquery', 'underscore', 'backbone', 'vent'], function($, _, Backbone, vent) {
'use strict';
var Wine = Backbone.Model.extend({
urlRoot: "js/models/wines.json",
defaults: {
"id": null,
"name": "",
"grapes": "",
"country": "USA",
"region": "California",
"year": "",
"description": "",
"picture": ""
}
});
return Backbone.Collection.extend({
model: Wine,
url: "js/models/wines.json",
});
});
I'm fetching the collection like this:
var _wine = new wineCollection();
_wine.fetch({
success : function(data) {
console.log("ON SUCCESS");
console.log(data);
},
error: function(response) {
console.log("ON ERROR");
console.log(response);
}
});
In the console it's always showing the "ON ERROR" message:
ON ERROR
child
_byCid: Object
_byId: Object
_callbacks: Object
length: 0
models: Array[0]
__proto__: ctor
And here is one item of my wines.json file
{"id":"9","name":"BLOCK NINE","year":"2009","grapes":"Pinot Noir","country":"USA","region":"California","description":"With hints of ginger and spice, this wine makes an excellent complement to light appetizer and dessert fare for a holiday gathering.","picture":"block_nine.jpg"}
What am I doing wrong?
Have you tried inspecting the collection class in the fetch method (what is actually send over).
You might need to override the parse method in order to access an inner part of the data send over.
For instance:
Wine.Collection = Backbone.Collection.extend({
//we need to parse only the inner list
parse : function (response) {
this.cursor = response.cursor;
return response.list;
}
Where the array is an inner list: {list: [{item: one}, {item: two}]}