How to pass LatlngBounds object to nodejs server using javascript - javascript

I want to pass a LatlngBounds object from a client to nodejs server.
var bounds = map.getBounds();
socket.emit('sendbounds', bounds);
In the server:
socket.on('sendbounds',function(data){
console.log(data);
data.getNorthEast();// undefined method getNorthEast()
}
The server can get the data sent from the client. However I am unable to use method getNorthEast().
My solution is to create an object LatlngBounds:
bounds = new google.maps.LatLng(data.Ea.k, data.va.j),
new google.maps.LatLng(data.Ea.j, data.va.k));
However this is not recommended because we cannot sure the key names are always 'Ea' and 'va'.
I notice that sometimes the key names are "Fa" and wa". They are "undocumented properties". They change with API releases.
Any solution to solve this problem?

I tried it that way, too, but had the same problem: Can't rely on the variable names.
Instead, I passed it to the server as a string instead of an object:
corners = map.getBounds();
var c = corners.toString();`
Then use whatever AJAX library to send the string to the server.
It looks something like this:
((33.94310833405608, -118.44952616442868), (33.985820303992334, -118.34120783557125))
You will have to pick it apart using a regexp, but at least it's reliably formatted.

Related

How to initialize z object to use z.JSON.parse function in a code Zap?

I'm developing a Zapier zap. The source is Google calendar. I collect the event description. It is a json string. I want to turn it into an object to process it in a Zap code (in JavaScript). The doc recommends to use the z.JSON.parse() function. I do it but at run time the error z is not initialized is sent. How to JSON parse a string to make an object ?
I tried to add z = new Z(), but it didn't work.
var eventDescriptorString = {
codeEvt: 'ID-LGC-02/21/2019-testoon_mail',
appCible: 'SIB',
action: 'testoon_mail',
parametre: 'ID-LGC-02/21/2019-testoon_mail-presents'
}
var eventDescriptorObject = z.JSON.parse(inputData.eventDescriptorString);
console.log('action', eventDescriptorObject.action);
output = [{
'action': eventDescriptorObject.action
}];
I expect action to equal 'testoon_mail'
David here, from the Zapier Platform team.
The docs you found are probably for the app scripting environment. While similar, it's got access to a separate set of functions (and the z object itself). Code steps (which is what you're using here) are "plain" javascript environments.
If you change z.JSON.parse -> JSON.parse it should work as expected.

API Connect - 500 error when including basic Javascript

I'm trying some basic API Connect tutorials on IBM's platform (running locally using loopback) and have got completely stuck at an early point.
I've built a basic API service with some in-memory data and setter / getter functions. I've then built a separate API which takes two GET parameters and uses one of my getter functions to perform a search based on two criteria. When I run it, I successfully get a response with the following JSON object:
[{"itemId":1,"charge":9,"itemSize":2,"id":2}]
I've then tried to add a piece of server logic that modifies the response data - at this point, I'm just trying to add an extra field. I've added a Javascript component in the Assemble view and included the following code (taken from a tutorial), which I thought should modify the message body returned by the API while still passing it through:
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
Instead of getting an extra JSON parameter ("platform"), all I get is a 500 error when I call the service. I'm guessing that I'm doing something fundamentally wrong, but all the docs suggest these are the right variable names to use.
You can't access json.platform but at that point json variable is json type. Are you sure that you can add a property to a json type variable if your json object lacks of that property? I mean: What if you first parse the json variable of json type to a normal object, then add new property, and finally stringify to json type again for body assigning purposes?
var json = JSON.parse(apim.getvariable('message.body')); //convert to normal object
json.platform = 'Powered by IBM API Connect'; //add new property
apim.setvariable('message.body', JSON.stringify(json)); //convert to json again before setting as body value
You need to get the context in some determined format, and in this function do your logic. For example if your message is in json you need to do:
apim.readInputAsJSON(function (error, json) {
if (error)
{
// handle error
apim.error('MyError', 500, 'Internal Error', 'Some error message');
}
else
{
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
if(json){
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
}
}
});
Reference:
IBM Reference
You have the message.body empty, put a invoke/proxy policy before your gateway/javascript policy for example.

JSPlumb diagram to JSON

I've been developing a diagramming tool, I used JSPlumb.
I made shapes using css and connections are made through JSplumb.
I need to save the diagram as json or xml format. But I am having a hard time.
For example, this is the function for saving the diagram
$(function save() {
//$("#editor").resizable("destroy");
Objs = [];
$('#editor').each(function(){
Objs.push({id:$(this).attr('id'), html:$(this).html(), left:$(this).css('left'), top:$(this).css('top'), width:$(this).css('width'), height:$(this).css('height')});
});
console.log(Objs);
});
Also, I've been trying the stringify for getting the data and parse for loading but I still can't figure it out.
Is there a way that I can save jsplumb to json or xml?
Whenever a connection is established, "connection" event is triggered. You need to store the connection endpoints details in that triggered function so that you can retrieve them later.
First make sure that you have set proper id for your endpoints. You can manually set at time of endpoint creation as:
var e0 = jsPlumb.addEndpoint("div1",{uuid:"div1_ep1"}), // You can also set uuid based on element it is placed on
e1 = jsPlumb.addEndpoint("div2",{uuid:"div2_ep1"});
Now bind the connection event where you will store the established connections info:
var uuid, index=0; // Array to store the endpoint sets.
jsPlumb.bind("connection", function(ci) {
var eps = ci.connection.endpoints;
console.log(eps[0].getUuid() +"->"+ eps[1].getUuid()); // store this information in 2d-Array or any other format you wish
uuid[index][0]=eps[0].getUuid(); // source endpoint id
uuid[index++][1]=eps[1].getUuid(); // target endpoint id
}
});
You can convert the array information to JSON format and store it. On restoring, connect the endpoints based on uuid. code:
jsPlumb.connect({ uuids:["div1_ep1","div2_ep1"] });
Here is the jsFiddle for making connections based on endpoints.
NOTE: The above code is only for restoring the connection and endpoints information after you have restored the div's css. You can store the css properties of all div's by using the same method which you wrote in your question.
I just recently tied this and its working
function createJSON(){
var data = new Object();
$("input[class = process]").each(function(){
data[$(this).attr("name")] = $(this).val();
jsonString = JSON.stringify(data);
});
console.log(jsonString);
}

Can't save polygon in google maps

I have a google maps polygon object:
var poly = new google.maps.Polygon({
paths: [
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.75737)
]
});
I'm trying to send it to MySQL db via jquery's AJAX:
$.post("savePolygon.php", {polygon: poly});
I get this error in console:
TypeError: Cannot call method 'lat' of undefined
I've seen some other posts about saving polygons, and they all say to extract the latLng's from the poly's and save them in a db. When I do this though:
var latLngs = poly.getPath().getArray();
$.post("savePolygon.php", {polygon: latLngs});
I get the same error. It seems there is a function in array's prototype called 'lat'. I'd like to know how exactly can I extract those values and send them via AJAX, and also why do I get this error?
Use google.maps.geometry.encoding.encodePath() to encode the path. This method returns a string, perfect for storing into a DB. For reuse decode the string by using google.maps.geometry.encoding.decodePath()
Please note: the geometry-library isn't loaded by default, you must load it by appending &libraries=geometry to the src of the maps-API-script.
To explain why you can't store the path directly(e.g. as JSON):
when you store the path(array), which contains the LatLng's, you will lose the prototype of the LatLng's, which is essential because it defines the methods for retrieving the properties(lat() and lng() )

How to pass a "new" object in JavaScript in Socket.IO

I'm trying to pass objects from one client to another client, e.g. pieces in a multiplayer board game. I have a working solution using JSON.parser and __proto__, but I'm curious to know if there is a better way.
Client sends:
var my_piece = new BoardPiece();
// ... my_piece is assigned data, like x-y coordinates
socket.send(JSON.stringify(my_piece));
Server forwards the piece to others:
client.broadcast(piece);
Another client receives:
var your_piece = JSON.parse(json);
your_piece.__proto__ = BoardPiece.prototype; // provide access to BoardPiece's functions
It's the last step where I use __proto__ that I'm concerned I may be shooting myself in the foot. Is there a better suggestion?
// clientone.js
var piece = new BoardPiece();
// ...
socket.send(JSON.stringify(piece));
// clienttwo.js
var piece = BoardPiece.Create(JSON.parse(json));
...
// BoardPiece.js
function BoardPiece() {
}
BoardPiece.prototype.toJSON = function() {
var data = {};
data.foo = this.foo;
...
return data;
};
BoardPiece.Create = function(data) {
var piece = new BoardPiece();
piece.foo = data.foo;
...
return piece;
}
Firstly using the toJSON method on your objects allows JSON.stringify to immediatly convert your object to JSON. This is part of the JSON API. The JSON API will call the toJSON method if it exists and converts that object to JSON.
This basically allows you to serialize your object as and how you want.
The second part is adding a factory method as a property of your constructor which takes your serialized JSON data and creates a new boardpiece. It will then inject your serialized data into that boardpiece object.
So your serializing only the data you care about and then passing that data through a factory method. This is the best way to send custom objects from one client to another.
There are a bunch of object syncing projects for node that might make life easier. For starters, check out:
NowJS
node-object-sync
Re-using Backbone.js Models on the server with Node.js and Socket.io to build real-time apps
Have tou tried jQuery's $.extend() method? http://api.jquery.com/jQuery.extend/

Categories

Resources