Leaflet: Moving the map doesn't move the icons with it, instead the icons stay fixed to the same position on the page - leaflet

Moving the map doesn't move the icons with it, instead the icons stay fixed to the same position on the page.
My icons get added to the correct latitude and longitude on my map. However, when I drag the map, the icons stay fixed on the same position on the page and are no longer being displayed at the correct latitude and longitude.
let sMap;
let ciLayer;
let neutralMarkers = [];
let gVesselIcons = {};
let numOfVessels = 0;
let ROI;
let nwLat;
let nwLon;
let seLat;
let seLon;
window.indexedDB =
window.indexedDB ||
window.mozIndexedDB ||
window.webkitIndexedDB ||
window.msIndexedDB;
//prefixes of window.IDB objects
window.IDBTransaction =
window.IDBTransaction ||
window.webkitittIDBTransaction ||
window.msIDBTransaction;
window.IDBKeyRange =
window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
let db;
const [dbPromise, dbResolve, dbReject] = (() => {
let resolve, reject;
return [
new Promise((res, rej) => {
resolve = res;
reject = rej;
}),
resolve,
reject
];
})();
let dbGSTSStore = window.indexedDB.open('GSTSStore', 1);
let dbVessels;
let dbTransactions;
let dbMessages;
dbGSTSStore.onerror = function(event) {
dbReject();
console.log('error: ');
};
dbGSTSStore.onsuccess = function(event) {
dbResolve();
db = dbGSTSStore.result;
};
dbGSTSStore.onupgradeneeded = function(event) {
const db = event.target.result;
dbVessels = db.createObjectStore('vessels', {
keyPath: 'mmsi'
});
dbMessages = db.createObjectStore('messages', {
keyPath: 'id'
});
dbTransactions = db.createObjectStore('transactions', {
keyPath: 'id'
});
};
async function InitializeSimple(
pBuildNumber,
pSysPersonId,
pSysOrganizationId
){
await GetOrganizationPrefs(pSysOrganizationId);
await GetPersonPrefs(pSysPersonId);
SetLabelText('lblBuildNumber', `Build: ${pBuildNumber}`);
dragElement(document.getElementById("vessel-info"));
nwLat = gOrganizationPrefs.roinwse.nwlat || gPersonPrefs.aoi.nwlat;
nwLon = gOrganizationPrefs.roinwse.nwlon || gPersonPrefs.aoi.nwlon;
seLat = gOrganizationPrefs.roinwse.selat || gPersonPrefs.aoi.selat;
seLon = gOrganizationPrefs.roinwse.selon || gPersonPrefs.aoi.selon;
try {
sMap = L.map('map-content', {
fullscreenControl: false,
zoomControl: false,
zoom: 6,
attributionControl: false,
preferCanvas: true
}).setView([19, 55]);
ciLayer = L.canvasIconLayer({}).addTo(sMap);
L.tileLayer(MapUrl[0], {
attribution: MapAttribution[0],
zoom: 5,
minZoom: 4,
maxNativeZoom: 13,
maxZoom: 20
}).addTo(sMap);
}
catch (error) {
console.log("error initializing map\n");
}
// SetVesselUpdate();
if(gOrganizationPrefs) await SetROI(gOrganizationPrefs.roinwse);
else await SetROI(gPersonPrefs.aoi);
await CreateNeutralLayer();
}
function SetLabelText(pLabel, pText) {
const lLabel = document.getElementById(pLabel);
if (lLabel !== undefined) lLabel.textContent = pText;
}
function CreateNeutralLayer(){
return new Promise((resolve, reject) => {
try {
const lTransaction = db.transaction(['vessels'], 'readonly');
let vessels = lTransaction.objectStore('vessels');
const countRequest = vessels.count();
countRequest.onsuccess = function() {
numOfVessels = countRequest.result;
}
vessels.openCursor().onsuccess = function(e) {
let cursor = e.target.result;
if (cursor !== null) {
let value = cursor.value;
let latitude = value.lat;
let longitude = value.lon;
let canInclude = checkROIBoundaries(latitude, longitude);
if (canInclude && cursor.value !== undefined) {
AddToLayers(cursor.value);
}
cursor.continue();
}
}
resolve('OK');
}
catch (err) {
console.log("error is: ", err, "\n");
reject({ error: err, function: 'CreateNeutralLayer()'});
}
});
}
function AddToLayers(vessel) {
let vesselRotationDegree = vessel.headingdegree.toString().padStart(2, '0');
if (vesselRotationDegree == '32') vesselRotationDegree = '00';
let vesselIconType = 'type-3';
let gBaseRiskIconURL = `./public/img/vessel/${vesselIconType}/vessel-`;
let gBaseRiskNeutralUrl = `${gBaseRiskIconURL}neutral-`;
var vIcon = L.icon({
iconUrl: `${gBaseRiskNeutralUrl}${vesselRotationDegree}.svg`,
iconSize: [24, 24],
iconAnchor: [24, 24]
});
const marker = L.marker([vessel.lat, vessel.lon], { icon: vIcon});
marker.properties = {
vesselname: vessel.shipname,
mmsi: vessel.mmsi,
imo: vessel.imo,
lat: vessel.lat,
lon: vessel.lon,
datetime: vessel.received_time,
heading: vessel.hdg,
sog: vessel.sog,
shiptype_descr: vessel.shiptype_descr,
last_positional_update: vessel.last_updated
};
marker.bindPopup(popupNeutralMarker, {
maxWidth: 392,
className: `map-info`
});
neutralMarkers.push(marker);
if (neutralMarkers.length >= numOfVessels) {
ciLayer.addLayers(neutralMarkers);
const vesselsInROI = document.getElementById('vessels-in-roi');
vesselsInROI.innerHTML = numOfVessels;
}
}
function checkROIBoundaries(latitude, longitude) {
let canInclude = false;
const lLatOK =
latitude >= Math.min(nwLat, seLat) &&
latitude <= Math.max(nwLat, seLat);
const lLonOK =
longitude >= Math.min(nwLon, seLon) &&
longitude <= Math.max(nwLon, seLon);
if (lLatOK && lLonOK) canInclude = true;
else numOfVessels--;
return canInclude;
}
function SetROI(pROI) {
return new Promise((resolve, reject) => {
try {
if (pROI.nwlat + pROI.nwlon + pROI.selat + pROI.selon === 0) return;
const defaultBoundaryStyle = {
color: 'blue',
fillColor: 'lightblue',
fillOpacity: 0.2
}
ROI = new L.rectangle(
[
[pROI.selat, pROI.selon],
[pROI.nwlat, pROI.selon],
[pROI.selat, pROI.selon],
[pROI.selat, pROI.nwlon]
],
defaultBoundaryStyle
)
sMap.addLayer(ROI, true);
// Center ROI
sMap.fitBounds([
[gOrganizationPrefs.roinwse.nwlat, gOrganizationPrefs.roinwse.nwlon],
[gOrganizationPrefs.roinwse.selat, gOrganizationPrefs.roinwse.selon]
]);
resolve('OK');
}
catch (err) {
console.log("error is: ", err, "\n");
reject({ error: err, function: 'SetROI'});
}
})
}

Related

How to get nodes in OpenStreetMap using Leaflet strictly contained in my current view?

I'm able to correctly query data from the OSM api.
I can also show highways and trunks correctly on the map.
However, the query gives me back always results for a fixed zoom even if my current zoom is higher.
this is how i do my call:
var opl = new L.OverPassLayer({
minZoom: 14,
query: '(way({{bbox}})["highway"~"^(' + query + ')$"];);(._;>;);out geom;',
onSuccess: function (data) {
console.log(data);
urlxml = data.urlxml;
data = data.result;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
//document.getElementById("demo").innerHTML = xhttp.responseText;
$("#fileData").text(xhttp.responseText);
console.log(xhttp.responseText);
}
};
xhttp.open("GET", urlxml, true);
console.log(urlxml);
xhttp.send();
console.log(urlxml);
for (let i = 0; i < data.elements.length; i++) {
let pos;
let marker;
const e = data.elements[i];
if (e.id in this._ids) {
continue;
}
this._ids[e.id] = true;
if (e.type === "way") {
let posWay = [];
for (let j = 0; j < e.geometry.length; j++) {
pos = L.latLng(e.geometry[j].lat, e.geometry[j].lon);
posWay.push(pos);
}
var polyline = L.polyline(posWay, { color: "blue" }).addTo(map);
}
console.log("DATA: " + JSON.stringify(data.elements));
}
},
});
How can i get results from the current view only?
Thank you.

Refresh sticky mobile leaderboard ad slot by changing the content URL in infinite scroll

I want to refresh sticky mobile leaderboard slot when the URL changes in infinite scroll. What do you think is the best way to go? Please let me know if you have any suggestions.
class DFPAds {
constructor() {
this.slots = [];
this.onScroll = throttle(this.loopAds, 300);
this.addEvents();
this.createAdObject = this.createAdObject.bind(this);
this.createSlotForAd = this.createSlotForAd.bind(this);
this.displayAd = this.displayAd.bind(this);
}
static get() {
return DFPAds._instance;
}
static set() {
if (!DFPAds._instance) {
DFPAds._instance = new DFPAds();
return DFPAds._instance;
} else {
throw new Error("DFPAds: instance already initialized");
}
}
addEvents() {
window.addEventListener("scroll", e => this.onScroll());
}
loopAds() {
this.slots.map(slot => this.displayAd(slot));
}
createAdObject(ad) {
let id = ad.id;
let attributes = getDataSet(ad);
let sizes = JSON.parse(attributes.sizes);
let sizeMapping;
if (attributes.sizemapping) {
attributes.sizemapping.length
? (sizeMapping = JSON.parse(attributes.sizemapping))
: (sizeMapping = null);
}
attributes.id = id;
attributes.sizes = sizes;
attributes.sizemapping = sizeMapping;
return attributes;
}
createSlotForAd(adObject) {
let {
id,
adtype,
position,
slotname,
sizes,
sizemapping,
shouldlazyload,
pagenumber,
pageid
} = adObject;
googletag.cmd.push(() => {
let slot = googletag.defineSlot(slotname, sizes, id);
if(position){
slot.setTargeting("position", position);
}
if(pagenumber){
slot.setTargeting("pagenumber", pagenumber);
}
if(pageid){
slot.setTargeting("PageID", pageid)
}
if (sizemapping) {
let mapping = googletag.sizeMapping();
sizemapping.map(size => {
mapping.addSize(size[0], size[1])
});
slot.defineSizeMapping(mapping.build());
}
slot.addService(googletag.pubads());
googletag.display(id);
shouldlazyload
? this.slots.push({ slot: slot, id: id })
: googletag.pubads().refresh([slot]);
console.log("SlotTop", slot)
});
}
displayAd(slot) {
console.log("Slottwo", slot)
let item = document.getElementById(slot.id);
if (item) {
let parent = item.parentElement;
let index = this.slots.indexOf(slot);
let parentDimensions = parent.getBoundingClientRect();
if (
(parentDimensions.top - 300) < window.innerHeight &&
parentDimensions.top + 150 > 0 &&
parent.offsetParent != null
) {
googletag.cmd.push(function() {
googletag.pubads().refresh([slot.slot]);
});
this.slots.splice(index, 1);
}
}
}
setUpAdSlots(context = document) {
let ads = [].slice.call(context.getElementsByClassName("Ad-data"));
if (ads.length) {
ads.map(ad => compose(this.createSlotForAd, this.createAdObject)(ad));
}
}
}
export default DFPAds;
And this is my Infinite Scroll code:
export default class InfiniteScroll {
constructor() {
this._end = document.getElementById('InfiniteScroll-End');
this._container = document.getElementById('InfiniteScroll-Container');
if(!this._end || !this._container)
return;
this._articles = { };
this._triggeredArticles = [];
this._currentArticle = '';
this._apiUrl = '';
this._count = 1;
this._timedOut = false;
this._loading = false;
this._ended = false;
this._viewedParameter = "&alreadyViewedContentIds=";
this._articleSelector = "InfiniteScroll-Article-";
this._articleClass = "Article-Container";
this.setStartData();
this.onScroll = throttle(this.eventScroll, 200);
this.addEvents();
}
addEvents(){
setTimeout(()=>{
window.addEventListener('scroll', (e) => this.onScroll() );
}, 2000);
}
addToStore(article){
this._articles["a" + article.id] = article;
}
addToTriggeredArticles(id){
this._triggeredArticles.push(id);
}
getRequestUrl(){
return this._apiUrl + this._viewedParameter + Object.keys(this._articles).map(key => this._articles[key].id).join();
}
getLastArticle(){
return this._articles[Object.keys(this._articles)[Object.keys(this._articles).length-1]];
}
setStartData() {
let dataset = getDataSet(this._container);
if(dataset.hasOwnProperty('apiurl')){
let article = Article.get();
if(article){
this._apiUrl = dataset.apiurl;
this._currentArticle = "a" + article.id;
this.addToStore(article);
}else{
throw(new Error('Infinite Scroll: Article not initialized.'));
}
}else{
throw(new Error('Infinite Scroll: Start object missing "apiurl" property.'));
}
}
eventScroll() {
if(this.isApproachingNext()){
this.requestNextArticle();
}
if(!this.isMainArticle(this._articles[this._currentArticle].node)){
this.updateCurrentArticle();
}
}
eventRequestSuccess(data){
this._loading = false;
if(data != ''){
if(data.hasOwnProperty('Id') && data.hasOwnProperty('Html') && data.hasOwnProperty('Url')){
this.incrementCount();
let node = document.createElement('div');
node.id = this._articleSelector + data.Id;
node.innerHTML = data.Html;
node.className = this._articleClass;
this._container.appendChild(node);
this.initArticleUpNext({
img: data.Img,
title: data.ArticleTitle,
category: data.Category,
target: node.id
});
this.addToStore(
new Article({
id: data.Id,
node: node,
url: data.Url,
title: data.Title,
count: this._count,
nielsenProps: {
section: data.NeilsenSection,
sega: data.NeilsenSegmentA,
segb: data.NeilsenSegmentB,
segc: data.NeilsenSegmentC
}
})
);
}else{
this._ended = true;
throw(new Error('Infinite Scroll: Response does not have an ID, Url and HTML property'));
}
}else{
this._ended = true;
throw(new Error('Infinite Scroll: No new article was received.'));
}
}
eventRequestError(response){
this._loading = false;
this._ended = true;
throw(new Error("Infinite Scroll: New article request failed."));
}
requestNextArticle(){
if(!this._loading){
this._loading = true;
return API.requestJSON(this.getRequestUrl())
.then(
(response)=>{this.eventRequestSuccess(response)},
(response)=>{this.eventRequestError(response)}
);
}
}
triggerViewEvent(article){
if(article.count > 1 && !this.isAlreadyTriggeredArticle(article.id)){
this.addToTriggeredArticles(article.id);
Tracker.pushView(article.url, article.count);
if(isFeatureEnabled('Nielsen') && Nielsen.get()){
Nielsen.get().eventInfiniteScroll({
id: article.id,
url: article.url,
section: article.nielsenProps.section,
sega: article.nielsenProps.sega,
segb: article.nielsenProps.segb,
segc: article.nielsenProps.segc
});
NielsenV60.trackEvent(article.title);
}
}
}
updateCurrentArticle(){
Object.keys(this._articles).map( key => {
if(this._currentArticle !== key && this.isMainArticle(this._articles[key].node)){
this._currentArticle = key;
this.updateUrl(this._articles[key]);
this.triggerViewEvent(this._articles[key]);
}
});
}
updateUrl(article){
try{
if(history.replaceState){
if(window.location.pathname !== article.url){
history.replaceState('', article.title, article.url);
}
}
}catch(e){}
}
incrementCount(){
this._count = this._count + 1;
}
initArticleUpNext(data){
this.getLastArticle().initUpNext(data);
}
isApproachingNext(){
return window.pageYOffset > this._end.offsetTop - (window.innerHeight * 2) && !this._ended && this._end.offsetTop >= 100;
}
isMainArticle(node){
if(node.getBoundingClientRect){
return (node.getBoundingClientRect().top < 80 && node.getBoundingClientRect().bottom > 70);
}else{
return false;
}
}
isAlreadyTriggeredArticle(id){
return this._triggeredArticles.indexOf(id) > -1;
}
}

Famo.us not loading Constructor of Strip View in Timbre Example

I am working no Timbre View Example of Famo.us, and what I am trying to achieve is simply open the page by clicking on strip view options in the app and closing the Menu Drawer as soon as I click on the Strip View option
for achieving this functionality I've read the Broad Cast and Listing from the Famo.us documentation. and wrote the following code in my example.
1) created a function to Broadcasting from an event handler with emit method and called it in Constructor of the Strip View.
Strip View:
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var ImageSurface = require('famous/surfaces/ImageSurface');
var HeaderFooter = require('famous/views/HeaderFooterLayout');
var FastClick = require('famous/inputs/FastClick');
var check = true;
Boolean(check);
function StripView() {
View.apply(this, arguments);
_createBackground.call(this);
_createIcon.call(this);
_createTitle.call(this);
_setListenersForStripView.call(this);
}
StripView.prototype = Object.create(View.prototype);
StripView.prototype.constructor = StripView;
StripView.DEFAULT_OPTIONS = {
width: 320,
height: 55,
angle: -0.2,
iconSize: 32,
iconUrl: 'img/strip-icons/famous.png',
title: 'Famo.us',
fontSize: 26,
onload: 'StripView()'
};
function allFunctions()
{
_createBackground();
_createIcon();
_createTitle();
}
function _createBackground() {
this.backgroundSurface = new Surface({
size: [this.options.width, this.options.height],
properties: {
backgroundColor: 'black',
boxShadow: '0 0 1px black'
}
});
var rotateModifier = new StateModifier({
transform: Transform.rotateZ(this.options.angle)
});
var skewModifier = new StateModifier({
transform: Transform.skew(0, 0, this.options.angle)
});
this.add(rotateModifier).add(skewModifier).add(this.backgroundSurface);
// this.backgroundSurface.on("touchend", function(){alert("Click caught")})
}
function _createIcon() {
var iconSurface = new ImageSurface({
size: [this.options.iconSize, this.options.iconSize],
content: this.options.iconUrl,
pointerEvents: 'none'
});
var iconModifier = new StateModifier({
transform: Transform.translate(24, 2, 0)
});
this.add(iconModifier).add(iconSurface);
// iconSurface.on("click", function(){alert("Click caught")})
}
function _createTitle() {
this.titleSurface = new Surface({
size: [true, true],
pointerEvents: 'none',
content: this.options.title,
properties: {
color: 'white',
fontFamily: 'AvenirNextCondensed-DemiBold',
fontSize: this.options.fontSize + 'px',
textTransform: 'uppercase',
// pointerEvents : 'none'
}
});
var titleModifier = new StateModifier({
transform: Transform.thenMove(Transform.rotateZ(this.options.angle), [75, -5, 0])
});
this.add(titleModifier).add(this.titleSurface);
}
function _setListenersForStripView() {
this.backgroundSurface.on('touchend', function() {
this._eventOutput.emit('menuToggleforStripView');
alert('clicked on title');
}.bind(this));
}
module.exports = StripView;
});
2) Then created a Trigger Method in App View
App View:
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Modifier = require('famous/core/Modifier');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var Easing = require('famous/transitions/Easing');
var Transitionable = require('famous/transitions/Transitionable');
var GenericSync = require('famous/inputs/GenericSync');
var MouseSync = require('famous/inputs/MouseSync');
var TouchSync = require('famous/inputs/TouchSync');
GenericSync.register({'mouse': MouseSync, 'touch': TouchSync});
var PageView = require('views/PageView');
var StripView = require('views/StripView');
var MenuView = require('views/MenuView');
var StripData = require('data/StripData');
function AppView() {
View.apply(this, arguments);
this.menuToggle = false;
this.pageViewPos = new Transitionable(0);
this.stripViewPos = new Transitionable(0);
_createPageView.call(this);
_StripView.call(this);
_createMenuView.call(this);
_setListeners.call(this);
_handleSwipe.call(this);
_setListenersForStripView.call(this);
}
AppView.prototype = Object.create(View.prototype);
AppView.prototype.constructor = AppView;
AppView.DEFAULT_OPTIONS = {
openPosition: 276,
transition: {
duration: 300,
curve: 'easeOut'
},
posThreshold: 138,
velThreshold: 0.75
};
function _createPageView() {
this.pageView = new PageView();
this.pageModifier = new Modifier({
transform: function() {
return Transform.translate(this.pageViewPos.get(), 0, 0);
}.bind(this)
});
this._add(this.pageModifier).add(this.pageView);
}
function _StripView() {
this.stripView = new StripView();
this.stripModifier = new Modifier({
transform: function() {
return Transform.translate(this.stripViewPos.get(), 0, 0);
}.bind(this)
});
this._add(this.stripModifier).add(this.stripView);
}
function _createMenuView() {
this.menuView = new MenuView({stripData: StripData});
var menuModifier = new StateModifier({
transform: Transform.behind
});
this.add(menuModifier).add(this.menuView);
}
function _setListeners() {
this.pageView.on('menuToggle', this.toggleMenu.bind(this));
}
function _setListenersForStripView() {
this.stripView.on('menuToggleforStripView', this.toggleMenu.bind(this));
}
function _handleSwipe() {
var sync = new GenericSync(
['mouse', 'touch'],
{direction: GenericSync.DIRECTION_X}
);
this.pageView.pipe(sync);
sync.on('update', function(data) {
var currentPosition = this.pageViewPos.get();
if (currentPosition === 0 && data.velocity > 0) {
this.menuView.animateStrips();
}
this.pageViewPos.set(Math.max(0, currentPosition + data.delta));
}.bind(this));
sync.on('end', (function(data) {
var velocity = data.velocity;
var position = this.pageViewPos.get();
if (this.pageViewPos.get() > this.options.posThreshold) {
if (velocity < -this.options.velThreshold) {
this.slideLeft();
} else {
this.slideRight();
}
} else {
if (velocity > this.options.velThreshold) {
this.slideRight();
} else {
this.slideLeft();
}
}
}).bind(this));
}
AppView.prototype.toggleMenu = function() {
if (this.menuToggle) {
this.slideLeft();
} else {
this.slideRight();
this.menuView.animateStrips();
}
};
AppView.prototype.slideLeft = function() {
this.pageViewPos.set(0, this.options.transition, function() {
this.menuToggle = false;
}.bind(this));
};
AppView.prototype.slideRight = function() {
this.pageViewPos.set(this.options.openPosition, this.options.transition, function() {
this.menuToggle = true;
}.bind(this));
};
module.exports = AppView;
});
now what this code does, is create another strip overlapping the previous strips and it only works on the newly created strip view but not on the other strips which means when it comes back to srip view it loads only the DEFAULT_OPTIONS of strip view because the strip which is being generated newly and overlaping is titled famo.us
Please let me know where I am going wrong and how can I open a new view in my application by closing menu drawer.
Do you have a folder named 'data' with the 'StripData.js' file on your famo.us project?
I'm asking because I downloaded the the Starter Kit and I didn't find that file inside.

chrome.serial receiveTimeout Not working.

Below code is a copy with minor edits from https://github.com/GoogleChrome/chrome-app-samples/tree/master/serial/ledtoggle. I am able to send a byte and receive a reply. I am not able to get an TimeoutError event in case of reply is not sent by the client. I have set timeout to 50 ms.
this.receiveTimeout = 50;
Entire code follows.
const DEVICE_PATH = 'COM1';
const serial = chrome.serial;
var ab2str = function(buf) {
var bufView = new Uint8Array(buf);
var encodedString = String.fromCharCode.apply(null, bufView);
return decodeURIComponent(escape(encodedString));
};
var str2ab = function(str) {
var encodedString = unescape((str));
var bytes = new Uint8Array(1);
bytes[0] = parseInt(encodedString);
}
return bytes.buffer;
};
var SerialConnection = function() {
this.connectionId = -1;
this.lineBuffer = "";
this.receiveTimeout =50;
this.boundOnReceive = this.onReceive.bind(this);
this.boundOnReceiveError = this.onReceiveError.bind(this);
this.onConnect = new chrome.Event();
this.onReadLine = new chrome.Event();
this.onError = new chrome.Event();
};
SerialConnection.prototype.onConnectComplete = function(connectionInfo) {
if (!connectionInfo) {
log("Connection failed.");
return;
}
this.connectionId = connectionInfo.connectionId;
chrome.serial.onReceive.addListener(this.boundOnReceive);
chrome.serial.onReceiveError.addListener(this.boundOnReceiveError);
this.onConnect.dispatch();
};
SerialConnection.prototype.onReceive = function(receiveInfo) {
if (receiveInfo.connectionId !== this.connectionId) {
return;
}
this.lineBuffer += ab2str(receiveInfo.data);
var index;
while ((index = this.lineBuffer.indexOf('$')) >= 0) {
var line = this.lineBuffer.substr(0, index + 1);
this.onReadLine.dispatch(line);
this.lineBuffer = this.lineBuffer.substr(index + 1);
}
};
SerialConnection.prototype.onReceiveError = function(errorInfo) {
log('Error');
if (errorInfo.connectionId === this.connectionId) {
log('Error');
this.onError.dispatch(errorInfo.error);
log('Error');
}
log('Error');
};
SerialConnection.prototype.connect = function(path) {
serial.connect(path, this.onConnectComplete.bind(this))
};
SerialConnection.prototype.send = function(msg) {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.send(this.connectionId, str2ab(msg), function() {});
};
SerialConnection.prototype.disconnect = function() {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.disconnect(this.connectionId, function() {});
};
var connection = new SerialConnection();
connection.onConnect.addListener(function() {
log('connected to: ' + DEVICE_PATH);
);
connection.onReadLine.addListener(function(line) {
log('read line: ' + line);
});
connection.onError.addListener(function() {
log('Error: ');
});
connection.connect(DEVICE_PATH);
function log(msg) {
var buffer = document.querySelector('#buffer');
buffer.innerHTML += msg + '<br/>';
}
document.querySelector('button').addEventListener('click', function() {
connection.send(2);
});
Maybe I'm reading the code incorrectly, but at no point do you pass receiveTimeout into chrome.serial. The method signature is chrome.serial.connect(string path, ConnectionOptions options, function callback), where options is an optional parameter. You never pass anything into options. Fix that and let us know what happens.

highcharts can't render

I use Ajax to get data, when I debug with firebug, the result shows highcharts option's data has data. But the chart can't render correctly. The charts background is rended correctely, but there is no chart.
here is my code.
// # author:wang
var chart;
var element;
var chart_type_element;
var y_title_1;
var y_title_2;
var y_title_3;
var date = new Date();
var y = date.getUTCFullYear();
var m = date.getUTCMonth();
var d = date.getUTCDate()-1;
var h = date.getUTCHours();
var minute = date.getUTCMinutes();
/**
* 返回图表的类型
*
*/
function chart_type(element){
var type;
var wind = '风向风速';
var t_h = '温湿度';
if ( element== 'wind' ){
type = wind;
} else if ( element == 't_h') {
type = t_h;
}
return type;
}
/**
*
*return y-axis title
*
*/
function y_title(element, serie){
var title;
if ( element== 'wind' ){
switch (serie){
case 1: title = '风速'; break;
case 2: title = '阵风'; break;
case 3: title = '风向'; break;
}
} else if ( element == 't_h') {
switch (serie){
case 1: title = '温度'; break;
case 2: title = '湿度'; break;
default: title = '';
}
}
return title;
}
function getLocTime(nS) {
return new Date(parseInt(nS)).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}
/**
* 气压配置选项
*/
var option_p = {
chart: {
renderTo: 'station_curve',
zoomType: 'x'
},
title:{
text:'气压序列图'
},
subtitle: {
text: '信科气象台'
},
xAxis: {
type: 'datetime',
maxZoom: 3600000, // one hour
title: {
text: null
}
},
yAxis: {
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}],
min:980,
max:1040
},
tooltip: {
formatter: function() {
return getLocTime(this.x) +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'left',
x: 220,
verticalAlign: 'top',
y: 30,
floating: true,
backgroundColor: '#FFFFFF'
},
series: [{
name: '海平面气压',
color: '#4572A7',
type: 'line',
pointInterval: 60 * 1000,
pointStart: Date.UTC(y,m,d,h,minute),
marker: {
enabled: false
}
}, {
name: '甲板气压',
type: 'line',
color: '#AA4643',
pointInterval: 60 * 1000,
pointStart: Date.UTC(y,m,d,h,minute),
marker: {
enabled: false
}
}/*, {
name: '3',
color: '#89A54E',
pointInterval: 60 * 1000,
pointStart: Date.UTC(y,m,d,h,minute),
type: 'spline',
marker: {
enabled: false
}
}*/]
};
function draw_curve(platformID,element){
option.series[0].data = [];
option.series[1].data = [];
option_th.series[0].data = [];
option_th.series[1].data = [];
jQuery.getJSON('get_last_3d.php',{platformID:platformID,element:element}, function(data) {
var serie=[];
var serie1=[];
if (element == 'wind_dir'){
$.each(data,function(i,value){
serie[i]=parseInt(value.wd);
});
option.series[0].data = serie.reverse();
} else if (element == 'wind_speed'){
$.each(data,function(i,value){
serie[i]=parseInt(value.ws);
serie1[i]=parseInt(value.ws_max);
});
option_wind_speed.series[0].data = serie.reverse();
option_wind_speed.series[1].data = serie1.reverse();
} else if (element == 't_h') {
$.each(data,function(i,value){
serie[i]=parseInt(value.t);
serie1[i]=parseInt(value.h);
});
option_th.series[0].data = serie.reverse();
option_th.series[1].data = serie1.reverse();
} else if (element == 'p') {
$.each(data,function(i,value){
serie[i]=parseInt(value.sea_p);
serie1[i]=parseInt(value.deck_p);
});
option_p.series[0] = serie.reverse();
option_p.series[1] = serie1.reverse();
} else if (element == 'wave_height') {
$.each(data,function(i,value){
serie[i]=parseInt(value.wave_height);
});
option.series[0].data = serie.reverse();
} else if (element == 'visibility') {
$.each(data,function(i,value){
serie[i]=parseInt(value.visibility);
});
option.series[0].data = serie.reverse();
} else if (element == 'cloudheight') {
$.each(data,function(i,value){
serie[i]=parseInt(value.cloud_height);
});
option.series[0].data = serie.reverse();
}
switch(element){
case 'p' :
chart = new Highcharts.Chart(option_p);
break;
case 't_h':
chart = new Highcharts.Chart(option_th);
break;
case 'wind_speed':
chart = new Highcharts.Chart(option_wind_speed);
break;
default:
chart = new Highcharts.Chart(option);
}
/* old code, will be replaced with switch
if (element == 'p')
chart = new Highcharts.Chart(option_p);
else {
chart = new Highcharts.Chart(option);
}
*/
});
}
$( function(){
draw_curve(105,'t_h');
})//end of jquery function
![the chart][1]
thank you advance
The reason it doesn't work is because you didn't provide the values for y,m,d,h,minute for the Date.UTC(y,m,d,h,minute) in the pointStart property for your series. See working: http://jsfiddle.net/LzfM3/