Javascript doesn't work the first click - Openlayers - javascript

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 );
};
}

Related

How to display custom tooltips on line chart using Rickshaw Library

I am developing a realtime graph system which will display the memory usage at particular time using data from json file . I am using Rickshaw Library which accepts tool tip in numeric type else the hard coded value supplied as a property to graph .
I have a json object as :
[
{
"memory": 444.08203125,
"memoryInfo": {
"rss": 444.08203125,
"vsize": 1271.125
},
"cpu": 0.2,
"url": [
"/admin/company/approved"
],
"time": "2/12/2016, 10:42:09 AM"
},
...
...
]
I want to show in tool tip at particular time what was the url served by server so that i can get proper information like which route is consuming more memory.
I will share my so far js code with you so that it will be better to understand .
script.js
$(function(){
var json = null;
console.log("Document Ready");
$.ajax({
url: 'data.json',
type: 'get',
success: function (data) {
console.log("Got data");
json = data
drawGraph()
}
});
var interval = 250;
//function to use from populating new values to graph
var getMemory = function(index) {
return json[index].memory
}
var getUrl = function(index) {
return json[index].url[0]
}
var getToolTip = function(){
console.log("getting tooltip")
return "api/login"
}
var drawGraph = function(){
// instantiate our graph!
graph = new Rickshaw.Graph( {
element: document.getElementById("chart"),
width: 900,
height: 400,
renderer: 'line',
interpolate:'basis',
series: new Rickshaw.Series.FixedDuration([{ name: 'memory' ,color:'steelblue',tooltip:"/api/login"}], undefined, {
timeInterval: interval,
maxDataPoints: 500,
timeBase: new Date().getTime() / 1000,
})
})
//tooltip is hardcoded should be dynamic when fetching each object from json
graph.render();
// get Recent log data using socket and feed it to graph
var i = 0;
var iv = setInterval( function() {
i++
var data = { memory: getMemory(i)};
graph.series.addData(data);
graph.render();
}, interval );
//hover details
var hoverDetail = new Rickshaw.Graph.HoverDetail( {
graph: graph,
formatter: function(series, x, y) {
var date = '<span class="date">' + new Date(x * 1000).toUTCString() + '</span>';
var swatch = '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>';
var content = swatch + series.tooltip + ": " + parseInt(y) + '<br>' + date;
console.log(series)
return content;
}
});
}
});//jQuery
Can you give us some further information regarding your problem/error?
From a quick look that I had, your tooltips (Rickshaw.Graph.HoverDetail) won't be able to render because you are asking in formatter for inputs "series,x,y" and you haven't set each element of the data array to have a x and y value.
example:
data: [ { x: 0, y: 5 }, { x: 1, y: 10 } ]
Take a look at rickshaw example here.

TypeError: g is not a function

While re-writing one of my applications from scratch (to go from legacy to AMD) I'm encountering an error which I can't figure out. It is driving me crazy. I'm probably just misspelling something or have another minor mistake, but I just can't figure out what. Any help would be highly appreciated!
I'm still in development mode, so my code isn't that pretty at this time. You can see it live in action at here: http://tpgrf.nl/testserver/alpha/topotrainer/flevoland
The javascript code:
//Define area and url's
var currentPath = window.location.pathname.split('/');
var AREA = currentPath[currentPath.length - 2];
if (AREA == 'europa' || AREA == 'wereld' || AREA == 'nederland') {
var AREAURL = AREA;
var AREAisProvince = false;
} else {
AREAURL = 'nederland';
var AREAisProvince = true;
}; //Ondervang provincies
var basemapURL = window.location.protocol + "//tiles.arcgis.com/tiles/nSZVuSZjHpEZZbRo/arcgis/rest/services/Topografie_in_de_klas_" + AREAURL + "_ondergrond/MapServer";
var contentFeatureURL = window.location.protocol + "//services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_" + AREAURL + "/FeatureServer/0";
var CONTENT = 'cito100'; //Default to 'cito100', user can adjust manually
var TYPES = ''; //empty for now, will be defined later by the user
var TYPES = 'plaats'; //for testingunction's//
//
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
});
return uuid;
};
//
//Figure something out here to detect if the user as a new or returning visitor
//
//////////////////////////////////////
//Create a basemap and load features//
//////////////////////////////////////
var dojoConfig = { parseOnLoad: true };
var map;
require(["esri/geometry/Extent", "esri/SpatialReference", "esri/map", "esri/graphic", "esri/layers/ArcGISTiledMapServiceLayer", "esri/tasks/query", "esri/tasks/QueryTask", "esri/tasks/FeatureSet", "esri/layers/GraphicsLayer", "esri/Color", "esri/symbols/SimpleMarkerSymbol", "esri/symbols/SimpleLineSymbol", "esri/symbols/PictureMarkerSymbol", "esri/renderers/UniqueValueRenderer", "esri/renderers/ClassBreaksRenderer",
"dijit/layout/BorderContainer", "dijit/layout/ContentPane", "dijit/TitlePane",
"dojo/domReady!", "dojo/dom", "dojo/on"],
function (Extent, SpatialReference, Map, Graphic, Tiled, Query, QueryTask, FeatureSet, GraphicsLayer, Color, SimpleMarkerSymbol, SimpleLineSymbol, PictureMarkerSymbol, UniqueValueRenderer, ClassBreaksRenderer, dom, on) {
//#TODO: Can we actually define this on the basemap mapserver?
if (AREA == 'nederland' || AREAisProvince == true) {
var initExtent = new Extent(-165715, 6453119, 1435181, 7205260, new SpatialReference({ wkid: 102100 }));
}
if (AREA == 'europa') {
var initExtent = new Extent(-2827847, 2851709, 6838658, 11375669, new SpatialReference({ wkid: 102100 }));
}
if (AREA == 'wereld') {
var initExtent = new Extent(-19705424, -14849545, 21700207, 21624981, new SpatialReference({ wkid: 102100 }));
}
map = new Map("map", {
extent: initExtent
});
//let's add a basemap
var tiled = new Tiled(basemapURL);
map.addLayer(tiled);
where = 'Cito100_onderdeel=1';
if (AREAisProvince == true) {
where += ' AND Provincie=\'' + AREA + '\'';
}
map.on("load", getFeaturesToMapAndStorage(where));
function getFeaturesToMapAndStorage(whereClause) {
console.log(whereClause);
//query the featureService
var query = new Query();
query.returnGeometry = true;
query.outFields = ["*"];
query.outSpatialReference = new SpatialReference({ wkid: 102100 });
query.where = whereClause;
var queryTask = new QueryTask(contentFeatureURL);
queryTask.on("complete", function (event) {
//map.graphics.clear();
var featureGraphicsLayer = new GraphicsLayer();
//#TODO: Can't we find a way to use the symbols from the featurservice directly, instead of the url's?
defaultSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 10,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
new Color([255, 0, 0]), 1),
new Color([0, 255, 0, 0.25]));
var renderer = new UniqueValueRenderer(defaultSymbol, "Type");
renderer.addValue("Plaats", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/89e5f81878a69f9cc0525c841f98af54", 11, 11));
renderer.addValue("Gebied", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/165c76bd4465728a34f6d18df4a1ec03", 28, 28));
renderer.addValue("Water", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/f9c146a401f48c4f38202e83c2e4582a", 22, 22));
renderer.addValue("Provincie", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/7a5373d8f1dcd1ecc03cefbab687b97c", 38, 32));
renderer.addValue("Land", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_europa/FeatureServer/0/images/7a5373d8f1dcd1ecc03cefbab687b97c", 38, 32));
renderer.addValue("Werelddeel", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_wereld/FeatureServer/0/images/48f2256a49253388488d813d721c054b", 32, 38));
var features = event.featureSet.features;
var featureCount = features.length;
for (var i = 0; i < featureCount; i++) {
var graphic = features[i];
featureGraphicsLayer.add(graphic);
}
featureGraphicsLayer.renderer = renderer;
map.addLayer(featureGraphicsLayer);
//#TODO: Update localstorage
}); //end on queryTask complete
queryTask.execute(query, queryComplete);
function queryComplete() {
console.log("fire function queryComplete");
//#TODO: reset progressbar
}; //End function queryComplete
} //end function getFeaturesToMapAndStorage
//The two closing tags below are essential and close the complete DOJO part.
} //end function after require (AMD style)
); //end require
Your issue is with: map.on("load", getFeaturesToMapAndStorage(where));
You're calling getFeaturesToMapAndStorage which returns undefined, and passing that in as the "load" handler. I'm guessing that the minified version of whatever it is that you're using uses g as a reference to your handler.
Since g is undefined, you're basically saying undefined(loadEvent).
EDIT: I'm guessing you meant to do something like this:
map.on("load", function(){
getFeaturesToMapAndStorage(where);
});
EDIT 2: For clarity, I'll explain what was wrong in more detail.
The difference between what you had and what I suggested above, is that you were calling getFeaturesToMapAndStorage on the line containing map.on("load", getFeaturesToMapAndStorage(where)); (as opposed to calling it after map's load event). In order to call your function getFeaturesToMapAndStorage with a predetermined parameter, you need to call it from a function (like the anonymous function above - function(){...}) that would then be passed in as the event handler.
Alternatively, due to how you have things scoped, you could reference your where inside of getFeaturesToMapAndStorage in place of having a whereClause parameter.

Arrays variable - how to get the first var

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.

Elabel undefined error in Google Maps V3

I have been porting a script I have from V2 to V3 and I have hit a snag. I am getting an Elabel undefined error but I am not sure why I am getting this. I have updated the Elabel.js to V3 which is here...ELABLE.JS I am not sure if this is not a good copy of ELabel.js or what. I have tried a couple of different other copies with no success.
Here is the working example of it using V2
V2 EXAMPLE
Here is the V3 example. As you can see in V3 the range rings are not drawn and the map doesn't update and the table doesn't populate. I know it is related to the ELabel.js but I am not sure why and I can't find the issue to why I am getting the undefined error. I know it is related to this because when I remove the script include for the ELable.js I have the same problems on V2 that I am seeing on V3.
V3 EXAMPLE
Since the code is too long to post here, the link to the relevant code is in the link below. Line 135 is where the ELabel error is coming from. This worked great in V2 but not V3. So I don't know if I am overlooking something that has changed in V2 to V3.
EXAMPLE CODE
So can anyone offer any insight on why I am getting this undefined error and shed some light on what I may be doing wrong and overlooking?
-Thanks
Texan, here's te script from my local file, which is working as far as getting the circles and labels to show. All ajax aspects are untested.
The script below should be pasted into the document head, immediately before the closing </head> tag.
This replaces various other inline scripts. The only remaining scripts in the document body should be the google analytics (2 scripts) and StatCounter (1 script). No external scripts should be removed.
<script>
var map;
jQuery(function($) {
var llCenter = new google.maps.LatLng(32.8297,-96.6486);
var URLToKML = 'http://www.mesquiteweather.net/NSGMap/GMStrikes.kml';
var Sec2Update = 30;
var KMLdate = 1372820133;
//var NSdate = 1372927434;
var NSdate = 0; //Force KML file creation on first update
var TZString = 'CDT';
var TZOffset = -5;
var nyLayer;
var lcolor = 'white';//This defines the line color for the target circle
//Check if user wants debug mode
dbg = (gup('dbg')=='y') ? 'y' : 'n';
var force = (gup('force')=='y') ? 'y' : 'n'; //Force updates regardless of NSStrikes.txt date
var mapReady = false;
function initialize() {
var mapOptions = {
center: llCenter,
panControl: false,
zoom: 6,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_TOP
},
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var radarOptions = {
gmap: map,
name: 'Radar',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function(){
if (map.overlayMapTypes.length==0) {
map.overlayMapTypes.push(null); // create empty overlay entry
map.overlayMapTypes.setAt("1", tileNEX);
}
else {
map.overlayMapTypes.clear();
}
}
}
var radarButton = new buttonControl(radarOptions);
tileNEX = new google.maps.ImageMapType({
getTileUrl: function(tile, zoom) {
return "http://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-900913/" + zoom + "/" + tile.x + "/" + tile.y +".png?"+ (new Date()).getTime();
},
tileSize: new google.maps.Size(256, 256),
opacity: 0.70,
name: 'NEXRAD',
isPng: true
});
function MyLogoControl() {
var logo = $('<img/>').attr('src', 'images/watermark_MW_GMap.png').css('cursor', 'pointer').get(0);
google.maps.event.addDomListener(logo, 'click', function() {
window.location = 'http://www.mesquiteweather.net';
});
return logo;
}
var logoControlDiv = $('<div/>').css('padding','5px').append(MyLogoControl()).get(0);
logoControlDiv.index = 0; // used for ordering
map.controls[google.maps.ControlPosition.TOP_LEFT].push(logoControlDiv);
var nyLayer = new google.maps.KmlLayer(URLToKML + "?rand=" + (new Date()).valueOf(), {
suppressInfoWindows: false,
map: map,
preserveViewport: true
});
google.maps.event.addListenerOnce(map, 'idle', function() {
//You can add circles, or change other parameters
//radials should be set to true for the maximum distance if you want radials
//doDrawCircle(circleUnits, center, circleRadius, lineColor, lineWidth, lineOpacity, fillColor, fillOpacity, opts, radials)
doDrawCircle('MI', llCenter, 62, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 124, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 187, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 249, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 312, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 374, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
//doDrawCircle('MI', llCenter, 374, lcolor, 1, .7, '#00FF00', 0, { clickable: false }, true); // This would add the radials
UpdateKML();//Get the first set of data
});
}
//Function to draw circles
function doDrawCircle(circleUnits, center, circleRadius, liColor, liWidth, liOpa, fillColor, fillOpa, opts, radials) {
var polyLineOptions = {
map: map,
path: null,//added with jQuery.extend()
strokeColor: liColor,
strokeOpacity: liOpa,
strokeWeight: liWidth
};
var bounds = new google.maps.LatLngBounds();
var circlePoints = [];
var d = circleRadius / ((circleUnits == 'KM') ? 6378.8 : 3963.189);
var d2r = Math.PI/180;
var lat1 = d2r * center.lat();//radians
var lng1 = d2r * center.lng();//radians
for (var a=0; a<361; a++ ) {
var tc = d2r * a;
var sin_lat1 = Math.sin(lat1),
cos_lat1 = Math.cos(lat1),
sin_d = Math.sin(d),
cos_d = Math.cos(d),
sin_tc = Math.sin(tc),
cos_tc = Math.cos(tc);
var y = Math.asin(sin_lat1 * cos_d + cos_lat1 * sin_d * cos_tc);
var dlng = Math.atan2(sin_tc * sin_d * cos_lat1, cos_d - sin_lat1 * Math.sin(y));
var x = ((lng1 - dlng + Math.PI) % (2 * Math.PI)) - Math.PI ; // MOD function
var point = new google.maps.LatLng(y/d2r, x/d2r);
circlePoints.push(point);
bounds.extend(point);
if(a==0) {
var offset = new google.maps.Size((circleRadius < 100) ? -5 : -8, 0);
//ELabel(map, point, html, classname, pixelOffset, percentOpacity, isFloatShadow, overlap);
var label = new ELabel(map, point, circleRadius, "style1", offset, 100, false);
label.setMap(map);
}
if (radials && ((a==0) || (a==45) || (a==90) || (a==135) || (a==180) || (a==225) || (a==270) || (a==315))) {
new google.maps.Polyline($.extend({}, polyLineOptions, {
path: [center, point]
}));
}
}
new google.maps.Polyline($.extend({}, polyLineOptions, {
path: circlePoints
}));
map.fitBounds(bounds);//This sets the map bounds to be as big as the target circles, comment out if you don't want it
}
//This function is called on page load to start the refresh of the strikes
function cycle() {
setInterval(CountDown, 1000);
}
var intvl = Sec2Update;
function CountDown() {
intvl -= 1;
if(intvl < 1) {
intvl = Sec2Update;
UpdateKML();
}
$("#cntdwn").html(intvl);
}
//This calls genkml.php on every refresh cycle to generate a new kml file
function UpdateKML() {
$.ajax({
url: 'genkml.php',
type: "GET",
data: {
force: force,
ofd: KMLdate,
nsd: NSdate,
dbg: dbg
},
cache: false,
dataType: '',//????
}).done(function(resp, textStatus) {
var $debugDiv = $("#div1");
if (dbg == 'y') {//Check if we want debug info
if (!$debugDiv.length) {//Check if debug div exists, if not add it to end of body
$debugDiv = $("<div/>").attr('id', 'div1').appendTo('body');
}
var tmpresp = resp || ' ';
$debugDiv.html('Response Status: ' + textStatus + '<br />' + tmpresp);
} else {//Else empty the debug div
$debugDiv.empty();
}
var dates = resp.split("|")[0].split("~");
KMLdate = dates[0];
NSdate = dates[1];
updateHTML(resp);//This calls the updateHTML function if info was returned
});
if(map) {
if(nyLayer) {
map.removeOverlay(nyLayer); //Remove overlays
}
//nyLayer = new KmlLayer(URLToKML + "?rand="+(new Date()).valueOf() );
nyLayer = new google.maps.KmlLayer(URLToKML + "?rand=" + (new Date()).valueOf(), {
suppressInfoWindows: false,
map: map,
preserveViewport: true
});
}
// Time overlayed on map - could be in updateHTML() to just show when .kml read last
$('#currenttime').innerHTML = CurrentTime ("B", "12a", true, TZOffset);
}
function CurrentTime (type, hours, secs, ofs) {
/*
type (char) hours (char) secs (bool) ofs (num)
"U"-UTC "24"=24 hr time true=hh:mm:ss 0=hours from UTC
"B"-User's Browser "12"=12 hr time false=hh:mm
"S"-Web Site "12a"=am/pm
*/
if (type == null){ type = "B"; } // These are the defaults
if (hours == null){ hours = "12a"; }
if (secs == null){ secs = true; }
if (ofs == null){ ofs = 0; }
var currentHour = 0;
var currentMinute = 0;
var currentSecond = 0;
var time = [];
var currentDate = new Date();
if (type == "U") {
currentHour = currentDate.getUTCHours();// UTC
} else if (type == "B") {
currentHour = currentDate.getHours();// Viewer's time
} else {
currentHour = currentDate.getUTCHours() + ofs;// your local time
if(currentHour < 0) { currentHour = currentHour + 24;}
}
currentMinute = currentDate.getMinutes();
currentMinute = (currentMinute < 10 ? "0" : "") + currentMinute;
if (hours == "24") {
if(currentHour == 24) { currentHour = 0 };// use if wanting 24 hour time
currentHour = (currentHour < 10 ? "0" : "") + currentHour;
} else if (hours == "12") {
if(currentHour == 0) currentHour = 12;
currentHour = (currentHour < 10 ? "0" : "") + currentHour;
} else {
if(currentHour == 0) currentHour = 12;// else no leading zero for am/pm
}
time.push(currentHour, currentMinute);
if (secs) {
currentSecond = currentDate.getSeconds();
currentSecond = (currentSecond < 10 ? "0" : "") + currentSecond;
time.push(currentSecond);
}
time = time.join(' : ');
if(hours == "12a") {
time = time + " " + (currentHour > 12 ? "PM" : "AM");
}
return time;
}
//This function is only used if you leave the debug checkbox below
// You can remove this function and the checkbox and set the debug
// mode using the dbg=y query parameter
function debug(obj){
if (obj.checked) {
dbg = 'y';
} else {
dbg = 'n';
$('#div1').empty();
}
}
//This function is only used if you leave the Force Update checkbox below
// You can remove this function and the checkbox and set the force
// mode using the force=y query parameter
function forceupdate(obj) {
force = (obj.checked) ? 'y' : 'n';
}
//This function parses out the query parameter value
function gup( name ) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
return results ? results[1] : "";
}
/*
You can add custom HTML code here and get access to the additional data that is returned everytime the page calls genkml.php.
In the example below, result is an array that holds 16 values (17, if in debug mode) with each of the values explained below.
*/
function updateHTML(resp) {
var result = resp.split("|");
if (result.length < 16) return;//Make sure there is data
document.getElementById('q1').innerHTML = result[1];//Number of strikes in first quarter of diplay time
document.getElementById('q2').innerHTML = result[2];//Number of strikes in second quarter of diplay time
document.getElementById('q3').innerHTML = result[3];//Number of strikes in third quarter of diplay time
document.getElementById('q4').innerHTML = result[4];//Number of strikes in fourth quarter of diplay time
document.getElementById('numicp').innerHTML = result[6];//Number of IC+ strikes
document.getElementById('numicn').innerHTML = result[5];//Number of IC- strikes
document.getElementById('numcgp').innerHTML = result[7];//Number of CG+ strikes
document.getElementById('numcgn').innerHTML = result[8];//Number of CG- strikes
document.getElementById('ds').innerHTML = result[9];//Total displayed strikes
document.getElementById('ta').innerHTML = result[10];//Total strikes in NSStrikes
document.getElementById('dt').innerHTML = result[11];//Display time
document.getElementById('numicpd').innerHTML = result[13];//Number of IC+ strikes
document.getElementById('numicnd').innerHTML = result[12];//Number of IC- strikes
document.getElementById('numcgpd').innerHTML = result[14];//Number of CG+ strikes
document.getElementById('numcgnd').innerHTML = result[15];//Number of CG- strikes
document.getElementById('tu').innerHTML = Date();//Number of CG- strikes
document.getElementById('sec2up').innerHTML = Sec2Update;//Number of CG- strikes
var dt = result[11] / 4;
document.getElementById('q1t').innerHTML = [0, dt].split('-');//Set time frame headers
document.getElementById('q2t').innerHTML = [dt, 2*dt].split('-');
document.getElementById('q3t').innerHTML = [2*dt, 3*dt].split('-');
document.getElementById('q4t').innerHTML = [3*dt, dt].split('-');
}
//Onload event caller. Does not intefere with OnLoad event in Body tag.
//Put this is after all functions to be called
function addLoadEvent(func) {
$(window).on('load', func);
}
initialize();
FADING_SCROLLER.changecontent();
});
</script>
<script type="text/javascript">
/***********************************************
* Fading Scroller- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************
* Wrapped as module by Beetroot-Beetroot
* Converted to use jQuery calls by Beetroot-Beetroot
* Note: The "proper" approach would be to use the 'color' jQuery plugin
***********************************************/
var FADING_SCROLLER = (function($) {//Module patttern
var delay = 5000; //set delay between message change (in miliseconds)
var maxsteps = 10; //number of steps to take to change from start color to endcolor
var stepdelay = 200; //time in miliseconds of a single step
//**Note: maxsteps*stepdelay will be total time in miliseconds of fading effect
var startcolor = [201,201,201]; //start color (red, green, blue)
var endcolor = [0,0,0]; //end color (red, green, blue)
var fadelinks = 1; //should links inside scroller content also fade like text? 0 for no, 1 for yes.
// *** No need to edit below this line ***
var faderdelay = 0;
var index = 0;
function changecontent() {
var $fscroller = $("#fscroller").css('color', "rgb(" + startcolor.join(', ') + ")");
var $content = $fscroller.find(".NWSinfo div").hide().eq(index).show().end();
if(fadelinks) linkcolorchange(1);
colorfade(1, 15);
index = (index + 1) % $content.length;
}
function linkcolorchange(step) {
$("#fscroller a").each(function() {
$(this).css('color', getstepcolor(step));
});
}
// Rafael Raposo edited function
var fadecounter;
function colorfade(step) {
if(step<=maxsteps) {
$("#fscroller").css('color', getstepcolor(step));
if (fadelinks)
linkcolorchange(step);
step++;
fadecounter = setTimeout(function() {
colorfade(step);
}, stepdelay);
} else {
clearTimeout(fadecounter);
$("#fscroller").css('color', "rgb(" + endcolor.join(', ') + ")");
setTimeout(changecontent, delay);
}
}
//Rafael Raposo's new function
function getstepcolor(step) {
var diff, newcolor = [];
for(var i=0; i<3; i++) {
diff = startcolor[i] - endcolor[i];
if(diff > 0) {
newcolor[i] = startcolor[i] - (Math.round((diff/maxsteps)) * step);
} else {
newcolor[i] = startcolor[i] + (Math.round((Math.abs(diff)/maxsteps)) * step);
}
}
return "rgb(" + newcolor.join(', ') + ")";
}
// *** Expose public methods here ***
return {
changecontent: changecontent
};
})(jQuery);
</script>
I only changed the javascript, not the CSS or HTML. Some comments are included but not really enough considering the scope of the changes.
You will see I wrapped the main script in a $(function(){...}) structure and the Fading Scroller script as a Module. This was done to prevent polluting the global namespace and the possibility of contamination between scripts. I left map in the global namespace in case it's needed in any of the other scripts.
I also made some changes to a local copy of ajaxWDwx.js but I don't think any of them are relevant.

HighStocks change AJAX parameters

My highstocks chart fetches JSON data from Yahoo and data from is structured like so "www.blahAAPLblah.com".
I want to change the value of AAPL in the URL to other company ticker symbols so that I can fetch the data and display it on my chart. If I change the string manually to GOOG then it will work fine. Also if I put var ticker = 'GOOG' and change the URL to "www.blah" + ticker + "blah.com" then this also works fine.
If I have a user input box and have var ticker = document.getElementById('userInput').value; then everything stops working.
Do you have any suggestions at all?
Here is my code so far: http://jsfiddle.net/SgvQu/
UPDATE I have attempted to use JSONP to perform the request but the chart is still not loading.
var closePrices = new Array();
var dateArray = new Array();
var timeStampArray = new Array();
var timeClose = new Array();
function jsonCallback(data, ticker) {
console.log( data );
//Put all the closing prices into an array and convert to floats
for(var i=0; i < data.query.results.quote.length; i++)
{
closePrices[i] = parseFloat( data.query.results.quote[i].Close );
}
//displays the values in the closePrices array
console.log( closePrices );
//Put all the dates into an array
for(var i=0; i < data.query.results.quote.length; i++)
{
dateArray[i] = data.query.results.quote[i].date;
}
//Convert all the dates into JS Timestamps
for(var i=0; i < dateArray.length; i++)
{
timeStampArray[i] = new Date( dateArray[i] ).getTime();
}
for(var i=0; i<data.query.results.quote.length; i++)
{
timeClose.push( [timeStampArray[i], closePrices[i]] );
}
timeClose = timeClose.reverse();
console.log ( timeClose );
//displays the dateArray
console.log( dateArray );
console.log( timeStampArray );
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : ticker + ' Stock Price'
},
series : [{
name : ticker,
data: timeClose,
tooltip: {
valueDecimals: 2
}
}]
});
}
function createChart() {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22' + ticker +'%22%20and%20startDate%20%3D%20%222013-01-01%22%20and%20endDate%20%3D%20%222013-02-25%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
//Ajax call retrieves the data from Yahoo! Finance API
$.ajax( url, {
dataType: "jsonp",
success: function(data, status){
console.log(status);
jsonCallback(data, ticker);
},
error: function( jqXHR, status, error ) {
console.log( 'Error: ' + error );
}
});
}
//Function to get ticker symbol from input box.
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
Thanks to Sebastian Bochan for pointing me in the right direction with JSONP. I now have the chart functioning correctly :)

Categories