Country name converter to ISO - javascript

I am trying to make a World chart that also shows how many transactions are coming from certain country's. But i need to translate the name of the country's to ISO because that is the only way this chart will work. Also the transactions is String (It is actually type of transactions) so i am trying to kind of convert the strings to numbers as well. I don't know if i am doing that right as well.
Here is my code:
<script>
var xmlURL = "some url";
var xml;
var xmlData;
var countryCodeColumn = "Counterparty country";
var categoryColumn = "Type of transaction";
var map;
var jsonText = "{";
var mapData;
var regionStyling = {initial: {fill: '#93959b'}};
$j.ajax({
url:xmlURL,
dataType:"xml",
beforeSend: function(){
$j('#loader').show();
},
success: function(data){
xml = data;
drawMap();
$j('#loader').hide();
}
});
function drawMap(){
console.log("xml as text", (new XMLSerializer()).serializeToString(xml));
var columns = {};
var columnNames = [];
var xmlColumns = $j('head', xml);
xmlColumns.find('headColumn').each(function(){
var columnName = $j(this).find('columnValue').text();
var columnID = $j(this).attr('columnid');
columns[columnName] = columnID;
console.log("column",columnName,columnID);
});
var xmlData = $j('data', xml);
var countryCode;
var category;
var categoryColor;
var url;
xmlData.find('item').each(function(){
itemId = $j(this).find('itemID').text();
url = "./injectColumnViewItemPage.action?metaData.channelID=9&metaData.siteID=723&metaData.sheetId=4640&metaData.itemId=" + itemId + "&metaData.sheetViewID=0&metaData.viewMode=0&view=readonly&sheetItemLinkView=true";
console.log("url", url);
console.log("itemid", itemId);
$j(this).find('column').each(function(){
var colID = $j(this).attr("columnid");
console.log(colID);
var value = $j(this).find('displayData').text();
console.log("field:", colID,value);
if(colID == columns[countryCodeColumn]){
countryCode = value;
}else if(colID == columns[categoryColumn]){
if(value != 0){
category++;
}
category = value;
categoryColor = $j(this).find('rawData').find('choice').attr('style');
}
});
jsonText += '"' + countryCode + '":{' + '"Transactions":"' + category + '","Color":"' + categoryColor + '","ItemID":' + itemId + '},';
});
jsonText = jsonText.substring(0,jsonText.length-1) + "}";
console.log("jsontext", jsonText);
mapData = JSON.parse(jsonText);
console.log("json", JSON.stringify(mapData));
map = new jvm.Map({container: $j('#isheet-map'),
map: 'world_mill_en',
series:{
regions: [{
normalizeFunction: 'polynomial'
}]
},
zoomOnScroll: true,
regionStyle: regionStyling,
backgroundColor: "#ffffff",
onRegionTipShow: function(e,el,code)
{
if(mapData[code])
{
el.html('<div style = "line-height:50%;"><span class="map-tip-title">' + el.html() + '</span><p></p><span class="map-tip-label">Transactions:</span>' + mapData[code]["Transactions"] + '<p></p></div>');
}else{
return false;
}
},
onRegionClick: function(e, code){
if(mapData[code]){
var href ="./injectColumnViewItemPage.action?metaData.channelID=9&metaData.siteID=" + 723 + "&metaData.sheetId=" + 4640 + "&metaData.itemId=" + mapData[code]["itemId"] + "&metaData.sheetViewID=0&metaData.viewMode=0&view=readonly&sheetItemLinkView=true";
$j("#iframe-Map").attr('src', href);
$j("#map-dialog").dialog({modal: true, title: map.getRegionName(code), width:600, height:500});
}
else{
return false;
}
}
});
map.series.regions[0].setValues(getColors());
function getColors(){
var colors = {};
$j.each(mapData,function(code,val){
colors[code] = mapData[code]["Color"];
});
console.log("colors", colors);
return colors;
}
}
</script>
There is nothing wrong with my ajax code since if i link it to another url it works fine

Related

Tooltipster not showing on initial hover

I am using tooltipster for th3 first time.
https://github.com/iamceege/tooltipster
I have this code
$('body').on('mouseenter', '.doreming-task', function(e) {
var documentWidth = $(document).width();
var documentHeight = $(document).height();
var currentID = $(this).attr("event_id");
var atr = scheduler.getEvent(currentID);
var taskTitle = atr.text;
var taskDesc = atr.description;
var taskstartDuration = atr.start_date;
var taskendDuration = atr.end_date;
var taskdatetimeduration = scheduler.templates.tooltip_date_format(taskstartDuration).split(" ")[1] + " " + scheduler.templates.tooltip_date_format(taskstartDuration).split(" ")[2] + " - " +
scheduler.templates.tooltip_date_format(taskendDuration).split(" ")[1] + " " + scheduler.templates.tooltip_date_format(taskendDuration).split(" ")[2];
var taskAssign = atr.person;
var taskProject = atr.project_id;
var taskGroup = atr.management_id;
var taskLocation = atr.work_location_name;
var taskContent = atr.work_category;
var contents_name = "";
var management_name = "";
$.each(workContentsHolder, function(key, val) {
if (taskContent == val['id']) {
contents_name = val['name'];
return false;
} else {
contents_name = " ";
}
});
$.each(departmentHolder, function(key, val) {
if (taskGroup == val['id']) {
management_name = val['name'];
return false;
} else {
management_name = " ";
}
});
$("#task-title-holder").text(taskTitle);
$("#task-duration").text(taskdatetimeduration);
$("#task-description-holder").text(taskDesc);
$("#task-assign-holder").text(taskAssign);
$("#task-project-holder").text(taskProject);
$("#task-group-holder").text(management_name);
$("#work-content-holder").text(contents_name);
$("#work-location-holder").text(taskLocation);
$(this).tooltipster({
animation: "fade",
delay: 100,
trigger: 'hover',
content: $('#tooltip_content'),
arrow: false,
contentAsHTML: true,
repositionOnScroll: true,
trackTooltip: true,
contentCloning: true,
theme: 'tooltipster-shadow',
multiple: false,
})
});
Basically, I just get the "event_id", get all the details, append in the HTML holder and put it on the content, it is working fine but it is always on the second hover
Any help and assistance will be appeciated

Post restful method java error

Can anyone tell me why this error?
Server Log:
StandardWrapperValve[ws_site.ApplicationConfig]: Servlet.service() for servlet ws_site.ApplicationConfig threw exception
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 5
at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
at com.google.gson.Gson.fromJson(Gson.java:791)
Javascript function, responsible for capturing the data of the filled form and sending to the server:
function save()
{
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name}';
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: obj
}).done(function (data)
{
alert(data);
});
}
Restful Java method:
#POST
#Path("data")
#Produces(MediaType.TEXT_PLAIN)
#Consumes({MediaType.APPLICATION_JSON})
public String registerUser(Gson json)
{
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
u.setAddress(a);
userDAO.save(u);
return "Saved successfully!";
}
Save userDAO method:
public void save(User u) {
EntityManager em = JPAUtil.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (u.getId_User() == null) {
em.persist(u);
} else {
em.merge(u);
}
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
if (tx != null && tx.isActive()) {
tx.rollback();
}
} finally {
em.close();
}
}
Using Gson to convert json into an object
You're not sending an object to the server, you're just sending a string:
var obj = '...';
Instead, send an object:
var objdata = {
"email_user": str_email,
"name_user": str_name
};
var objlocation = {
"country": str_country,
"state": str_state,
"city": str_city,
"neighborhood": str_neighborhood,
"street": str_street,
"number": str_number,
"zipcode": str_zipcode
};
var obj = {
"user": [objdata],
"endereco": [objlocation]
};
A string that looks like an object is still a string.
objdata was not populating correctly as valid json. Try with this:
function save() {
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name + '"}';
console.log(objdata);
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
console.log(objlocation);
var obj = '{"user":[' + objdata + '],"endereco":[' + objlocation + ']}';
console.log(obj);
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: JSON.parse(obj)
}).done(function (data) {
alert(data);
});
}
In your server side you are trying bind JSON data.
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
It mean user and endereco should be a JSON objects like below.
{
"user":{
"email_user":"str_mail","name_user":"nameeee"
},
"endereco":{
"country":"str_country","state":"str_state","city":"str_city","neighborhood":"str_neighborhood","street":"str_street","number":"str_number","zipcode":"str_zipcode"
}
}
But in your case user and endereco are actually a JSONArray's(See the square brackets.).
{
"user":[
{
"email_user":"str_mail",
"name_user":"nameeee"
}
],
"endereco":[
{
"country":"str_country",
"state":"str_state",
"city":"str_city",
"neighborhood":"str_neighborhood",
"street":"str_street",
"number":"str_number",
"zipcode":"str_zipcode"
}
]
}
So change below line
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
to
var obj = '{"user":'+objdata+',"endereco":'+objlocation+'}';

Google Visualization : How to call and draw sequential query with table?

I have to draw a side by side table with 2 different sql query data. I am sending in the given below format. However, it was drawn first query data into second table container instead with first table container.
var sqlQuery = "sql?tq=select Section, SubSection, Id, Question, Answer, Others where " +
"SubSection = '1.1' &sqlQueryID=questions_bank";
var query1 = new google.visualization.Query(sqlQuery);
TABLE_LOCATION = 'tableProductDeploymentContainer';
query1.send(drawQuestions);
var sqlQuery = "sql?tq=select Section, SubSection, Id, Question, Answer, Others where " +
"SubSection = '1.2' &sqlQueryID=questions_bank";
var query2 = new google.visualization.Query(sqlQuery);
TABLE_LOCATION = 'tableProductDeploymentContainer';
query2.send(drawQuestions);
break;
function drawQuestions(queryResponse) {
if (queryResponse.isError()) {
alert('Error in query: ' + queryResponseData.getMessage() + ' ' + queryResponseData.getDetailedMessage());
return;
}
var questionBankResponse = queryResponse.getDataTable();
if (questionBankResponse === null) {
alert('Empty rows in query: ' + questionBankResponse.getNumberOfRows());
return;
}
var questionDataTable = new google.visualization.DataTable();
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
var questionDataTableRow = new Array();
var rowCounter;
for (rowCounter = 0; rowCounter < questionBankResponse.getNumberOfRows() ; rowCounter++) {
var count = 0 * 1;
var chbQuestion;
var questionId = questionBankResponse.getValue(rowCounter, 2);
var questionName = questionBankResponse.getValue(rowCounter, 3);
var answerValue = questionBankResponse.getValue(rowCounter, 4);
var answerOthers = questionBankResponse.getValue(rowCounter, 5);
if (answerOthers !== null)
answerOthers = answerOthers.toString();
if (answerValue === null)
answerValue = 0;
if (answerValue.toString() === "1")
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\"" + " checked />";
else
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\"" + " />";
questionDataTableRow[count++] = chbQuestion;
questionDataTableRow[count++] = questionName;
questionDataTableRow[count++] = answerOthers;
questionDataTable.addRow(questionDataTableRow);
}
var tableObject = new google.visualization.Table(document.getElementById(TABLE_LOCATION));
tableObject.draw(questionDataTable, { allowHtml: true, 'cssClassNames': cssClasses, width: '100%', sort: 'disable' });
}
I believe, there is some error in setting the TABLE_LOCATION global variable. Is there any way to pass the table container dynamically without maintaining in the global level.
Thanks for your help.
since the callback for Query.send is called asynchronously,
cannot guarantee one finishes before the other
as you point out, send the table id within the callback, rather than using global scope...
see following snippet...
var sqlQuery = "sql?tq=select Section, SubSection, Id, Question, Answer, Others where " +
"SubSection = '1.1' &sqlQueryID=questions_bank";
var query1 = new google.visualization.Query(sqlQuery);
query1.send(function (queryResponse) {
drawQuestions(queryResponse, 'tableProductDeploymentContainer');
});
var sqlQuery2 = "sql?tq=select Section, SubSection, Id, Question, Answer, Others where " +
"SubSection = '1.2' &sqlQueryID=questions_bank";
var query2 = new google.visualization.Query(sqlQuery2);
query2.send(function (queryResponse) {
drawQuestions(queryResponse, 'tableProductDeploymentContainer2');
});
function drawQuestions(queryResponse, TABLE_LOCATION) {
if (queryResponse.isError()) {
alert('Error in query: ' + queryResponseData.getMessage() + ' ' + queryResponseData.getDetailedMessage());
return;
}
var questionBankResponse = queryResponse.getDataTable();
if (questionBankResponse === null) {
alert('Empty rows in query: ' + questionBankResponse.getNumberOfRows());
return;
}
var questionDataTable = new google.visualization.DataTable();
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
var questionDataTableRow = new Array();
var rowCounter;
for (rowCounter = 0; rowCounter < questionBankResponse.getNumberOfRows() ; rowCounter++) {
var count = 0 * 1;
var chbQuestion;
var questionId = questionBankResponse.getValue(rowCounter, 2);
var questionName = questionBankResponse.getValue(rowCounter, 3);
var answerValue = questionBankResponse.getValue(rowCounter, 4);
var answerOthers = questionBankResponse.getValue(rowCounter, 5);
if (answerOthers !== null)
answerOthers = answerOthers.toString();
if (answerValue === null)
answerValue = 0;
if (answerValue.toString() === "1")
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\"" + " checked />";
else
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\"" + " />";
questionDataTableRow[count++] = chbQuestion;
questionDataTableRow[count++] = questionName;
questionDataTableRow[count++] = answerOthers;
questionDataTable.addRow(questionDataTableRow);
}
var tableObject = new google.visualization.Table(document.getElementById(TABLE_LOCATION));
tableObject.draw(questionDataTable, { allowHtml: true, 'cssClassNames': cssClasses, width: '100%', sort: 'disable' });
}

Sorting xml data by date in jQuery

I am getting a 'date' element from a RSS feed. I am having trouble with sorting and displaying the information. Can someone have a look? Thanks!
$('#feedContainer').empty();
$.ajax({
type: 'GET',
url: categoryURL,
dataType: 'xml',
success: function (xml) {
var data = [];
$(xml).find("item").each(function () {
var dateText = $(this).find("Date").text().substr(0,5);
var title = $(this).find("title").text();
var region = date.substr(6);
if (region.length < 3) { region = "ALL"; }
var description = $(this).find("description").text();
var descriptdisplay = description.substr(0, description.indexOf(",")+6); //Parsed DATE from description
if (descriptdisplay.length > 35) { descriptdisplay = "See event for details"; }
//var locationdisplay = description.substr(description.indexOf(",")+6,4); //Parsed the location from description
var category = $(this).find("category").text();
var linkUrl = $(this).find("link").text();
var item={ title: $(this).find("title").text(), dateText: $(this).find("Date").text().substr(0,5), date : new Date( dateText) }
data.push(item);
// var displaytitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>" ;
// $('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+"Event Date: "+descriptdisplay+'</p><p>'+"Location: "+region+'</p');
data.sort(function(a,b){ return a.date > b.date;});
$.each(data, function(index, item) { $('#feedContainer').append('<h3>'+item.title+'</h3><p>'+"Event Date: "+item.dateText+'</p><p>'+"Location: "+item.date+'</p'); });
});
}
});
You're sorting date objects, try sorting the epoch timestamp instead:
data.sort(function(a,b){
return a.date.getTime() > b.date.getTime();
});

How to change google maps marker icon dynamically

I am using ajax and php and I grabbing all of the points out of my database and plotting them on the map. Which works fine. However I want to change the icon of the marker depending on if status in the database is 100 or 200 or 300 for each record. I can't seem to get anything to work. Here is my code:
if (localStorage.getItem('type2') !== null) {
$(function ()
{
var radius2 = localStorage.getItem("radius2");
var lat2 = localStorage.getItem("lat2");
var long2 = localStorage.getItem("long2");
var type2 = localStorage.getItem("type2");
var city2 = localStorage.getItem("city2");
var rep2 = localStorage.getItem("rep2");
var size2 = localStorage.getItem("size2");
var status2 = localStorage.getItem("status2");
$.ajax({
url: 'http://example.com/Test/www/22233333.php',
data: "city2=" + city2 + "&rep2=" + rep2 + "&status2=" + status2 + "&size2=" + size2 + "&type2=" + type2 + "&long2=" + long2 + "&lat2=" + lat2 + "&radius2=" + radius2,
type: 'post',
dataType: 'json',
success: function (data) {
$.each(data, function (key, val) {
var lng = val['lng'];
var lat = val['lat'];
var id = val['id'];
var name = val['name'];
var address = val['address'];
var category = val['category'];
var city = val['city'];
var state = val['state'];
var rep = val['rep'];
var status = val['status'];
var size = val['size'];
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': 'images/hospital.png'
}).click(function () {
$('div#google-map').gmap('openInfoWindow', {
'backgroundColor': "rgb(32,32,32)",
'content': "<table><tr><td>Name:</td><td>" + name + "</td></tr><tr><td>Address:</td><td>" + address + ", " + city + " " + state + "</td></tr><tr><td>Category:</td><td>" + category + "</td></tr><tr><td>Rep:</td><td>" + rep + "</td></tr><tr><td>Status:</td><td>" + status + "</td></tr><tr><td>Size:</td><td>" + size + "</td></tr></table>"
}, this);
});
})
}
});
})
}
Looks like you are using jquery-ui-map?
I haven't used this abstraction
You can call the setIcon function - on a marker you can set it's icon this way for the main API
https://developers.google.com/maps/documentation/javascript/reference#Marker
So your addMarker method will return a marker instance by the look of it so once you have that run setIcon
Do something like this in your success function with in $.each.
Status is the database field
var size = val['size'];
var status = val['status'];
var icon = '';
if (status == 100){
icon = 'images/icon1.png'; //your icon1
}else if (status == 100){
icon = 'images/icon1.png'; //your icon2
}
...
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': icon //your dynamic icon
})
Hope this helps

Categories

Resources