I need a way to store two values only within an array or object and limit its length to two values. The reason is that I am using a jQuery Vectormap to calculate the distance and a draw line between two coordinates x1/y1 & x2/y2.
Whenever a region/country is clicked, corresponding markers are loaded and added to the map
map.addMarker(id ,{latLng: [val.lat, val.long], name:val.name}) ; ect///
Now, whenever a marker is clicked I should be able to track count of two markers's selection and store their coordinates in an array then do the calculations..
onMarkerClick:function(e, code){
var coordinates = map.markers[code].config.latLng;
// latitude = coordinates[0]
// longitude = coordinates[1]
}
So if I were to use myArray.push([coordinates[0],coordinates[1]]) for each marker clicked then I end up with countless number of coordinates and thus making it impossible to draw my line.. Is there a way to set myArray length to 2 then when I push more values overwrite the existing one?
Thanks
If you want to be fancy about it, you can create your custom class that does this...
function CappedArray(Size)
{
this.push = function(Value) {
if(this.length==Size)
{
this.shift();
}
CappedArray.prototype.push.call(this, Value);
}
}
CappedArray.prototype = new Array();
//How you use it
var SomeArray = new CappedArray(2);
SomeArray.push([coordinates[0],coordinates[1]]);
...
Alternatively, if you want to force the fact that points should only be associated in successive pairs of insertions:
function PairArray()
{
this.push = function(Value) {
if(this.length==2)
{
this.splice(0, 2);
}
PairArray.prototype.push.call(this, Value);
}
}
PairArray.prototype = new Array();
//How you use it
var SomeArray = new PairArray();
SomeArray.push([coordinates[0],coordinates[1]]);
You could use an object like this:
var coords =
{
"c1": [x1,y1],
"c2": [x2,y2]
}
then when adding coordinates you could:
coords.c1 = coordinates[0];
coords.c2 = coordinates[1];
Related
The 2D array I created is not accepted by D3.js as coordinates (The map example I'm using is at http://bl.ocks.org/phil-pedruco/6522279.)
Here are the facts:
1.) The JSON input I am supplied with is a string of latitude and longitude (e.g. "37.3879 -134.96376").
2.) The output required is a 2D array that must be in this form [[lat,long],[lat,long],...].
3.) console.log(typeof(lat)); returns that the lat and long values are indeed numbers (not strings)
4.) console.log("Coordinates: " + JSON.stringify(points)); returns [[37.3879,-134.96376],[13.5,-45],...] - which appears to be in the correct form, yet no points are displayed on the map
5.) If I hardcode the values in the array the points are displayed.
var points = [];
//var dotSpot = [[1.4440, 32.442], [12.222, 4.893]];
window.onload = function () {
getJSON();
}
function getJSON(supplierID) {
//retrieves JSON perfectly
//calls make() with Supplier data
}
function make(jdata) {
for (var i = 0; i < jdata.length; i++) {
//Splits string by space
var temp = jdata[i].latLong.split(/[ ,]+/)
//Converts lat and long strings to floats
var lat = parseFloat(temp[0]);
var long = parseFloat(temp[1]);
console.log(typeof(lat));
//Add "curr" coordinates array to "points" array
var curr = new Array(lat, long);
points.push(curr);
}
console.log("Coordinates: " + JSON.stringify(points));
}
You have specified your coordinates to be [latitude, longitude]. However, unlike many other applications D3 uses coordinates with longitude as the first value followed by latitude. From the docs:
The point must be specified as a two-element array [longitude, latitude] in degrees.
Changing you data accordingly should yield the desired rendering:
var curr = new Array(long, lat); // instead of new Array(lat, long)
points.push(curr);
My code :
var appsAndScopes=[
['1',['A','B','C','D']],
['2 ',['E','F','G','H']],
['3',['I']],
['4',['J']]
];
function getAllElements(id){return document.getElementById(id);}
function buildDropdowns(){
var applications=getAllElements('application').options; //Gets all applications names from appsAndScopes array.
for(var applicationsIndex=0;applicationsIndex<appsAndScopes.length;applicationsIndex++){
applications[applications.length]=new Option(appsAndScopes[applicationsIndex][0],appsAndScopes[applicationsIndex][0]);
}
getAllElements('application').onchange=function(){
this.blur();
var currentApplication=this.value;
if(!currentApplication){return;}
var scopes=getAllElements('scope').options;
scopes.length=1;
for(var scopesIndex=0;scopesIndex<appsAndScopes.length;scopesIndex++){
if(appsAndScopes[scopesIndex][0]!==currentApplication){continue;}
else{
var temp=appsAndScopes[scopesIndex][1];
for(var valueIndex=0;valueIndex<temp.length;valueIndex++){
scopes[scopes.length]=new Option(temp[valueIndex],temp[valueIndex]);
}
break;
}
}
}
}
$(function() {
buildDropdowns();
});
In this code, I am generating dynamic drop downs (i.e. dependent drop downs). This code is working fine. It's using 2d array to populate the values of drop downs. I want to implement a map instead of 2d array. That will change the whole process of iterating also.
I am very new to javascript. I don't know any of the syntax for javascript. Please help me doing that.
declare a map object
var map = new Map(); // or var map = {};
inserting a new item
map.set(key, value);
in your case you can use like map.set(1,['a','b','c','d']);
retrieving a item
map.get(key); // will return value
for more detailed uses see this https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
I currently have an app that creates an array of markers. But it is not useful, because I would like to see a group of markers and a custom property summed based on the distance between markers (depending on the zoom level).
I've said that maybe with MarkerClusterPlus I could accomplish something like this:
This even shows a custom icon, I don't need that, I only need the number over the cluster.
But I don't know where to start. Could someone place an example or a link?
You must define a custom property on the Marker object, so you can override the Calculator function in markercluster.js
MarkerClusterer.CALCULATOR = function (markers, numStyles) {
var index = 0;
var title = "";
var count = markers.length.toString();
var valueToSum=0;
for(var m=0;m<markers.length;m++){
//This is the custom property called MyValue
valueToSum+=Number(markers[m].MyValue);
}
var dv = val;
while (dv !== 0) {
dv = parseInt(dv / 10, 10); //you could define your own rules
index++;
}
index = Math.min(index, numStyles);
return {
text: valueToSum,
index: index,
title: title
};
};
I have a complex Javascript array which when written to the console looks like this :
function Standing(flagsmall, teamname, won, drawn, lost, goalsfor, goalsagainst, points) {
this.flagSmall = flagsmall;
this.teamName = teamname;
this.won = won;
this.drawn = drawn;
this.lost = lost;
this.goalsFor = goalsfor;
this.goalsAgainst = goalsagainst;
this.points = points;
}
var arrStandings = new Array();
serviceUrl = "http://cloudapp.net/odata/Standings?$expand=Team,Stage&$filter=Team/Group/GroupName eq 'A'";
var line = "";
$.getJSON(serviceUrl, function (results) {
$.each(results['value'], function (i, item) {
//calculate points
var points = (item.Won * 3) + (item.Drawn * 1);
var standing = new Standing(item.Team.FlagSmall, item.Team.TeamName, item.Won, item.Drawn, item.Lost, item.GoalsFor, item.GoalsAgainst, points);
arrStandings.push(standing);
arrStandings.sort(sortfunction);
});
});
Yet when I try to iterate through it I cannot and when I check it's length it returns 0 :
console.dir(arrStandings.length);
arrStandings.forEach(function (index) {
...
});
How do I access the objects within the array?
It's not a 100% clear from your code but looks like you are trying to print the length of the array before it has been populated.
$.getJSON is an asynchronous operation, so at the point in time when you're writing to the console it has not yet been populated.
The representation displayed in the javascript console is rendered after the array is created, when it is first accessed.
I had a similar problem when i initilized an array but i put a string key, the array was casted to Object. Return this code lenght of your array/object?
Object.keys(myArray).length
You can iterate the object using for statement:
for ( index in arrStanding ){
// your code
}
EDIT:
// here you have an array
arrStandings.push(standing);
// ...and after this line?
arrStandings.sort(sortfunction);
Regards,
Kevin
I'm currently working on drawing up a tilemap using a set of images loaded inn to an array.
I've defined a tile as an object like this:
function tile(gfx){
this.tile = gfx;
this.drawSelf = function(x,y)
this.tile.x = x;
this.tile.y = y;
}
Then I filled up an array with several tile objects which through the debugger displays correctly.
Now when I start drawing up the images using this code:
for (var x = 0; x < mapArray.length; x++){
xN = 183 + (50*x);
mapArray[x].drawSelf(xN, 134);
gameStage.addChild(mapArray[x].tile);
mapArray[x].tile.visible = true;
}
The problem is that all the "objects" in the array recive the same x and y coords. So what i suspect is that every single object in the array referes to each other.
What I'm trying to do is create a 20x10 map of tiles. And I need to be able to refer to each tile as a single object.
Shout out if I'm not making sense.
If you create all the tiles like this :
var gfx = new ...
for (...) {
mapArray[x].tile = new tile(gfx);
}
Then all of them share the same gfx object.
You should change your initialization like this :
for (...) {
var gfx = new ...
mapArray[x].tile = new tile(gfx);
}