It's seems to be very easy but i can not make it works. I have an array con 2 var inside that i get from Jquery.
var features = [long, lat ]
i would like to get all the valores in the loop and i need
fetures[i]
that will give me long1 and lat1 but when i try
alert( features[0] )
i get all the long values.
and when i try with [1] i get all the lat values.
How can i solve this issue?
I can not make it work, maybe you can have a look at my code:
$.ajax({
url : "https://api.foursquare.com/v2/venues/search?limit=3&radius=1000&client_id=J22NHX41TJBJ2PZM4NBTLDWLDYIBWLMIF4LJCFWNAXK1WALY&client_secret=RS110L4OYLY1XFCEMV30UB2JJ1JRFQZ0E3P0USSIMSCA45RZ&v=20120101&ll=" + ui.item.y +"," + ui.item.x,
dataType : "jsonp",
success : function(data) {
$.each(data.response.venues, function( index, value ) {
//alert( index + ": " + value.name + " , "+ value.location.lng);
var Name = value.name
var VenueLati = value.location.lat
var VenueLong = value.location.lng
//alert( VenueLong );
var features = [];
for(var i = 0; i < features[0].length; i++) {
feature[i] = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(VenueLong, VenueLati).transform('EPSG:4326', 'EPSG:3857'),
{some:'data'},
{
foo :
}, {
fillColor : '#008040',
fillOpacity : 0.8,
strokeColor : "#ee9900",
strokeOpacity : 1,
strokeWidth : 1,
pointRadius : 8
});
}
When i put a number intead features[0].length then i can see the points but can see only one popup :/
$.ajax({
url : "https://api.foursquare.com/v2/venues/search?limit=3&radius=1000&client_id=J22NHX41TJBJ2PZM4NBTLDWLDYIBWLMIF4LJCFWNAXK1WALY&client_secret=RS110L4OYLY1XFCEMV30UB2JJ1JRFQZ0E3P0USSIMSCA45RZ&v=20120101&ll=" + ui.item.y +"," + ui.item.x,
dataType : "jsonp",
success : function(data) {
$.each(data.response.venues, function( index, value ) {
//alert( index + ": " + value.name + " , "+ value.location.lng);
var Name = value.name
var VenueLati = value.location.lat
var VenueLong = value.location.lng
alert( VenueLong );
var features = [];
for(var i = 0; i<50; i++) {
features[i] = new OpenLayers.Feature.Vector(
toMercator(new OpenLayers.Geometry.Point(VenueLong,
VenueLati)),
{
ulica : Name
}, {
fillColor : '#008040',
fillOpacity : 0.8,
strokeColor : "#ee9900",
strokeOpacity : 1,
strokeWidth : 1,
pointRadius : 8
});
}
// create the layer with listeners to create and destroy popups
var vector = new OpenLayers.Layer.Vector("Points",{
eventListeners:{
'featureselected':function(evt){
var feature = evt.feature;
var popup = new OpenLayers.Popup.FramedCloud("popup",
OpenLayers.LonLat.fromString(feature.geometry.toShortString()),
null,
"<div style='font-size:.8em'>Name: " + feature.id +"<br>Address: " + feature.attributes.ulica+"</div>",
null,
true
);
feature.popup = popup;
map.addPopup(popup);
},
'featureunselected':function(evt){
var feature = evt.feature;
map.removePopup(feature.popup);
feature.popup.destroy();
feature.popup = null;
}
}
});
vector.addFeatures(features);
// create the select feature control
var selector = new OpenLayers.Control.SelectFeature(vector,{
hover:true,
autoActivate:true
});
map.addLayers([vector]);
map.addControl(selector);
center = new OpenLayers.LonLat(lon, lat).transform('EPSG:4326', 'EPSG:3857');
map.setCenter(center, 15);
You have 2 array in one array like this:
var features = [ [100, 200, 300, 400], ["A", "B", "C", "D"];
if you want to get the long s, you should do this:
for(var i=0;i<features[0].length;i++){
alert(features[0][i]);
}
and for the lat s:
for(var j=0;j<features[1].length;j++){
alert(features[1][j]);
}
but I think you are expecting something else, like an array of json objects with long and lat as its keys, although you can map these 2 array based on their order, if both lists are ordered:
var newArray = [];
for(var i=0;i<features[0].length;i++){
newArray.push({"long":features[0][i], "lat":features[1][i]});
}
Instead of literal values in your array, you will want objects:
var features = [{long: 123, lat: 234}, {long: 545, lat: 677}];
Then,
features[0]
will give you
{long: 123, lat: 234}
Which you can access by
features[0].long
features[0].lat
I hope this helps. Let me know if you have further questions.
Related
I wrote my code down to a small fiddle: http://jsfiddle.net/V8dyd/266/
I am able to render region labels as strings on the map but unable to render them as HTML.
$(function(){
var Jsondata = {
LK: " Region : Asia, Feedback : 228, Good : 34.00%, Normal : 33.00%, Bad : 30.00% ",
IN: "Total Responses : 228"
};
var map = $('#map').vectorMap({
map: 'world_mill_en',
zoomMin: 1,
zoomMax: 1,
regionLabelStyle: {
initial: {
fill: '#B90E32'
},
hover: {
fill: 'black'
}
},
labels: {
regions: {
render: function (code) {
if (code==="LK") {
var a = Jsondata[code];
var array = a.split(',');
var s = "<html><body><div><small>" + array[0] +"</small><br><small>" + array[1] + "</small><br><small>" + array[2] + "</small><br><small>" + array[3] + "</small></div</body></html>";
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
return htmlObject;
// return s
}
}
}
}
});
});
The labels are rendered using svg TEXT-Tags and do not allow HTML.
In the current version this is not supported but i used a Hook in the Region Function for realize line breaks:
https://github.com/bjornd/jvectormap/blob/master/src/region.js
Like this:
jvm.Region = function(config){
var bbox,
text,
offsets,
labelDx,
labelDy;
this.config = config;
this.map = this.config.map;
this.shape = config.canvas.addPath({
d: config.path,
'data-code': config.code
}, config.style, config.canvas.rootElement);
this.shape.addClass('jvectormap-region jvectormap-element');
bbox = this.shape.getBBox();
myHook(bbox, text, offsets, config);
return false;
...
}
function myHook(bbox, text, offsets, config){
// Create your own Label like this
text = this.getLabelText(config.code);
if (this.config.label && text) {
offsets = this.getLabelOffsets(config.code);
this.labelX = bbox.x + bbox.width / 2 + offsets[0];
this.labelY = bbox.y + bbox.height / 2 + offsets[1];
this.label = config.canvas.addText({
text: text,
'text-anchor': 'middle',
'alignment-baseline': 'central',
x: this.labelX,
y: this.labelY,
'data-code': config.code
}, config.labelStyle, config.labelsGroup);
this.label.addClass('jvectormap-region jvectormap-element');
}
}
Thats not the best way but maybe it helps you!
Hi trying to create this array dynamically. This is the static way:
var pieData = [
{
value: 300,
color:getRandomColor(),
highlight: getRandomColor(),
},
{
value: 50,
color: getRandomColor(),
highlight: "#fac878",
},
{
value: 100,
color: getRandomColor(),
highlight: getRandomColor(),
},
{
value: 120,
color: getRandomColor(),
highlight: getRandomColor(),
}
];
This is what I achieved:
$.ajax({
method: "POST",
url: "getPieChartData"
})
.done(function(data){
obj = $.parseJSON(data);
var pieData = []; i = 0;
$.each(obj, function(key, item) {
pieData[i].value = item.total + " - " + item.d_name;
pieData[i].color = getRandomColor();
pieData[i].highlight = getRandomColor();
i++;
});
});
I am getting value from my function that is not a problem. My issue is that I am getting in the console that this part:
pieData[i].value = item.total +" - " + item.d_name; TypeError: pieData[i] is undefined
What am I doing wrong? thx
You can simple use .push() method. No meed to use indexer.
The push() method adds one or more elements to the end of an array and returns the new length of the array.
$.each(obj, function(key, item) {
pieData.push({
value: item.total + " - " + item.d_name,
color : getRandomColor(),
highlight : getRandomColor()
});
});
You need to create the pieData[i] object first;
var pieData = []; i = 0;
$.each(obj, function(key, item) {
pieData[i] = {}; // added line
pieData[i].value = item.total + " - " + item.d_name;
pieData[i].color = getRandomColor();
pieData[i].highlight = getRandomColor();
i++;
});
Before pieData[i].value .., you should first have a line:
pieData[i] = {};
I am using multi-select grid functionality in my application and it is working as i expected. But the issue is i need to get all the selected records across the pagination in external javascript function. Below is my code,
function createCommodity(){
$.ajax({
url : 'commoditycategory.do?method=listCommodity' + '&random='
+ Math.random(),
type : "POST",
async : false,
success : function(data) {
$("#list2").jqGrid('GridUnload');
var newdata = jQuery.parseJSON(data);
var wWidth = $(window).width();
var dWidth = wWidth * 0.7;
var wHeight = $(window).height();
var dHeight = wHeight * 0.5, idsOfSelectedRows = [];
jQuery("#list2").jqGrid({
data : newdata,
datatype : "local",
colNames : [ "id", "Commodity Code",
"Commodity Description", "Commodity Category" ],
colModel : [
{
name : 'id',
index : 'id',
hidden : true,
editable : true
},
{
name : 'commodityCode',
index : 'commodityCode',
align : "center",
editable : true,
editrules : {
required : true
}
},
{
name : 'commodityDesc',
index : 'commodityDesc',
align : "center",
editable : true,
editrules : {
required : true
}
},
{
name : 'commodityCategoryId',
index : 'commodityCategoryId',
align : "center",
// hidden : true,
editable : true,
edittype : "select",
editoptions : {
dataUrl : 'commoditycategory.do?method=parentCategory'
+ '&random=' + Math.random()
},
editrules : {
edithidden : true,
required : true
// custom : true
}
} ],
pager : "#pager2",
rowNum : 10,
rowList : [ 10, 20, 50 ],
height : "230",
width : dWidth,
onSelectRow: function (id, isSelected) {
var p = this.p, item = p.data[p._index[id]], i = $.inArray(id, idsOfSelectedRows);
item.cb = isSelected;
if (!isSelected && i >= 0) {
idsOfSelectedRows.splice(i,1); // remove id from the list
} else if (i < 0) {
idsOfSelectedRows.push(id);
}
},
loadComplete: function () {
var p = this.p, data = p.data, item, $this = $(this), index = p._index, rowid, i, selCount;
for (i = 0, selCount = idsOfSelectedRows.length; i < selCount; i++) {
rowid = idsOfSelectedRows[i];
item = data[index[rowid]];
if ('cb' in item && item.cb) {
$this.jqGrid('setSelection', rowid, false);
}
}
},
multiselect : true,
cmTemplate : {
title : false
}
});
$grid = $("#list2"),
$("#cb_" + $grid[0].id).hide();
$("#jqgh_" + $grid[0].id + "_cb").addClass("ui-jqgrid-sortable");
cbColModel = $grid.jqGrid('getColProp', 'cb');
cbColModel.sortable = true;
cbColModel.sorttype = function (value, item) {
return typeof (item.cb) === "boolean" && item.cb ? 1 : 0;
};
}
});
}
Till now its working great. Its holding correct rows which are selected across pagination.
And My external JS function where i need to get the selected rowids include pagination is,
function updateCommodity() {
var grid = jQuery("#list2");
var ids = grid.jqGrid('getGridParam', 'selarrrow'); // This only returns selected records in current page.
if (ids.length > 0) {
var html = "<table id='commodityTable' class='main-table' width='100%' border='0' style='border:none;border-collapse:collapse;float: none;'><thead><td class='header'>Commodity Code</td><td class='header'>Commodity</td><td class='header'>Action</td></thead><tbody>";
for ( var i = 0, il = ids.length; i < il; i++) {
var commodityCode = grid.jqGrid('getCell', ids[i],
'commodityCode');
var commodityDesc = grid.jqGrid('getCell', ids[i],
'commodityDesc');
html = html
+ "<tr class='even' id='row" + i + "'><td><input type='text' name='commodityCode' id='geographicState"+i+"' class='main-text-box' readonly='readonly' value='" + commodityCode + "'></td>";
html = html
+ "<td><input type='text' name='commodityDesc' id='commodityDesc"+i+"' class='main-text-box' readonly='readonly' value='" + commodityDesc + "'></td>";
html = html
+ "<td><a style='cursor: pointer;' onclick='deleteRow(\"commodityTable\",\"row"
+ i + "\");' >Delete</a></td></tr>";
}
html = html + "</tbody></table>";
$("#commodityArea").html(html);
}
}
Update I have fiddled the issue for providing more clarity about the issue.
First of all I want remind that you use the code which I posted in the answer.
I see that the solution of your problem is very easy. The list of options of jqGrid can be easy extended. If you just include new property in the list of options
...
data : newdata,
datatype : "local",
idsOfSelectedRows: [],
...
you will don't need more define the variable idsOfSelectedRows (see the line var dHeight = wHeight * 0.5, idsOfSelectedRows = []; of you code). To access new option you can use
var ids = grid.jqGrid('getGridParam', 'idsOfSelectedRows');
instead of var ids = grid.jqGrid('getGridParam', 'selarrrow');. To make the code of onSelectRow and loadComplete callbacks working with idsOfSelectedRows as jqGrid option you should just modify the first line of the callbacks from
var p = this.p, ...
to
var p = this.p, idsOfSelectedRows = p.idsOfSelectedRows, ...
It's all.
UPDATED: See http://jsfiddle.net/OlegKi/s2JQB/4/ as the fixed demo.
I am using flot charts. I want to plot chart which is updated per second and also want to add the feature of turning off and on the data series.
I am able to make it work but has problems which I did not expect, like color of one series change when other series is turned off; other is when I update the array of data series the charts seems to move but it removes element from the right,at the same time the new value is plotted on the right hand side ...
var d1 = [] ;
var d2 = [] ;
var d3 = [] ;
$(function(){
{%for reading in readings%}
var time_stamp = parseFloat({{reading['timestamp']}} + 19800.00) * 1000
var A = parseFloat({{reading['values']['A']}}) ;
var V = parseFloat({{reading['values']['VLN']}}) - 50 ;
var W = parseFloat({{reading['values']['W']}}) / 1000 ;
d1.push([time_stamp,A]);
d2.push([time_stamp,V]);
d3.push([time_stamp,W]);
{%endfor%}
var datasets = {
"current":{
label : "A",
data : d1
},
"voltage":{
label : "V",
data : d2
},
"power":{
label : "W",
data : d3
},
}
var i = 0;
$.each(datasets, function(key, val) {
val.color = i;
++i;
});
// insert checkboxes
var choiceContainer = $("#choices");
$.each(datasets, function(key, val) {
choiceContainer.append("<br/><input type='checkbox' name='" + key +
"' checked='checked' id='id" + key + "'></input>" +
"<label for='id" + key + "'>"
+ val.label + "</label>");
});
choiceContainer.find("input").click(plotAccordingToChoices);
function plotAccordingToChoices() {
var data = [];
choiceContainer.find("input:checked").each(function () {
var key = $(this).attr("name");
if (key && datasets[key]) {
data.push(datasets[key]);
}
});
if (data.length > 0) {
$.plot("#placeholder", data, {
series: {
shadowSize: 0,
lines: {
show: true
},
},
yaxis: {
min: 0
},
xaxis: {
tickDecimals: 0,
mode:"time"
}
});
}
setTimeout(getNextDataset,1000);
}
plotAccordingToChoices();
});
function getNextDataset()
{
$.ajax({url : '/newdata' , success:function(result){
reading =JSON.parse(result);
var time_stamp = (parseFloat(reading.timestamp) + 19800.00) * 1000
var A = parseFloat(reading.values.A) ;
var W = parseFloat(reading.values.W) / 1000 ;
var V = parseFloat(reading.values.VLN) - 50 ;
d1.shift();d2.shift();d3.shift();
d1.push([time_stamp,A]);
d2.push([time_stamp,V]);
d3.push([time_stamp,W]);
var datasets = {
"current":{
label : "A",
data : d1
},
"voltage":{
label : "V",
data : d2
},
"power":{
label : "W",
data : d3
},
}
var data = [] ;
var choiceContainer = $("#choices");
choiceContainer.find("input:checked").each(function () {
var key = $(this).attr("name");
if (key && datasets[key]) {
data.push(datasets[key]);
}
});
if (data.length > 0) {
$.plot("#placeholder", data, {
series: {
shadowSize: 0,
lines: {
show: true
},
points:{
show:false
},
},
yaxis: {
min: 0
},
xaxis: {
tickDecimals: 0,
mode:"time"
}
});
}
}
});
setTimeout(getNextDataset,1000) ;
}
`
I am making use of code available in flot charts examples.Where am I going wrong ??
Thank you ?
Problem 1 : Color updating every time a checkbox was checked or unchecked
Reason: Every time the checkbox click event was triggered,some how the color used to get updated
Solution : Removed setTimeout(getNextDataset,1000); call from the function plotAccordingToChoices()
Problem 2: The data elements are removed from the right instead of left.
Reason : (Very dumb) Data was coming in descending order and I was using pushing data in that order only.So latest point was at location 0 of the array and oldest point was at location n-1.And I was removing (n-1)th point.
Solution : Replaced push in the beginning with unshift().Did the magic :P
I have this Javascript that displays a map via Openlayers and plots points with a text on the map. For some reason, the text layer doesn't work on the first click. Here is the link to the site. This is also my first project working with Javascript, and I would appreciate any help.
Thanks!
Code:
//---------------------------------------------------------------------
// creates a filtered point vector layer, the base of the text layer
// and also genetates a table
//
function createVector( ajaxUrl ) {
console.log( ajaxUrl );
//remove all the layers except the base (google) layers
while( map.layers.length > 4 )
map.removeLayer(map.layers[map.layers.length - 1]);
var date = $('#datepicker').val();
var filter = $('input:radio[name=filter]:checked').val();
//json, ajax, and kml urls
var jsonUrl = "/map/desc/";
var url = "/map/test-";
url += date;
jsonUrl += date;
url += "/"+filter;
jsonUrl += "/"+filter;
url += ".kml"
//create a new layer for the points
points = new OpenLayers.Layer.Vector("Albedo Data Points", {
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: url,
format: new OpenLayers.Format.KML({
extractStyles: true,
extractAttributes: true
})
}),
});
//create a style map layer for the text. Empty at this point
text = new OpenLayers.Layer.Vector("Text Layer", {
styleMap: new OpenLayers.StyleMap({'default':{
pointerEvents: "visiblePainted",
label : "${val}",
fontColor: "${color}",
fontSize: "12px",
fontFamily: "Courier New, monospace",
fontWeight: "bold",
labelAlign: "${align}",
labelXOffset: "${xOffset}",
labelYOffset: "${yOffset}",
labelOutlineColor: "white",
labelOutlineWidth: 3
} }),
});
//get the json from the model
$.getJSON(jsonUrl, function(json, textStatus, jqXHR) {
data = json;
});
//load this function after the map has been processed
points.events.register( 'loadend', points, function (e) {
addTextLayer( filter );
});
//add all the layers to the map
map.addLayers( [points, text] );
//and the control
selectControl = new OpenLayers.Control.SelectFeature(points);
map.addControl(selectControl);
selectControl.activate();
points.events.on({
'featureselected': onFeatureSelect,
'featureunselected': onFeatureUnselect
});
//generate the table
ajaxUrl += '?q=';
$( '#results' ).html( ' ' ).load( ajaxUrl + date );
}
//---------------------------------------------------------------------
// loops through the points layer to grab the coordiantes, and
// adds features to the text layer
//
function addTextLayer( filter ) {
for( var i = 0; i < points.features.length; i++ ) {
var value;
if( filter == "albedo" )
value = data[i].fields.albedo;
else
value = data[i].fields.snow_Density;
var temp = new OpenLayers.Geometry.Point(
points.features[i].geometry.x,
points.features[i].geometry.y
);
var textFeature = new OpenLayers.Feature.Vector( temp );
textFeature.attributes = {
val: value,
color: 'blue',
align: "cm",
xOffset: 20,
yOffset: 10,
};
text.addFeatures( textFeature );
};
}