vectorSource.addFeatures with the parameter Array containing more than 10 features using openlayers 4.3.3 - openlayers-3

I have a map and I'd like to add features. The features are added correctly always at the end of the array. If there are more than 10 features added, the eleven one - is inserted anywhere.
draw.on('drawend', function(evt) {
var feature = evt.feature;
var anfang = ol.proj.transform(feature.getGeometry().getFirstCoordinate(), 'EPSG:3857', 'EPSG:4326');
var ende = ol.proj.transform(feature.getGeometry().getLastCoordinate(), 'EPSG:3857', 'EPSG:4326');
var url = '?lonlats='+anfang+'|'+ende+'&nogos=&profile=shortest&alternativeidx=0&format=geojson';
url = encodeURIComponent(url);
url = broutes+url;
var response = new XMLHttpRequest();
response.open('GET', url);
var onError = function() {
console.log('error');
}
response.onerror = onError;
response.onload = function() {
if (response.status == 200) {
var data = Ext.decode(response.responseText);
var arr = data.features[0].geometry.coordinates;
var arrayNew = [];
for (i=0; i<arr.length; i++){
var n = ol.proj.transform(arr[i], 'EPSG:4326', 'EPSG:3857');
arrayNew.push(n);
}
var data = new ol.geom.LineString( arrayNew );
//console.log(data);
var featureSnake = new ol.Feature({
geometry: data
});
snakeSource.addFeature( featureSnake );
var win = Ext.create('MyProject.view.window.Edit', {
record : featureSnake,
toDo: 'insert',
});
win.show();
} else {
onError();
}
}

I chanced my code like you told me (using version 4.3.3)
vectorSource = new ol.source.Vector({
useSpatialIndex: false
});
Now I have the following result vectorSource.getFeatures()
polygon1
polygon2
...
polygon15
polygon2
polygon3
...
polygon15
polygon1
I have all features twice.

Related

indexeddb on IOS devices

I have a problem with an indexeddb query with index when running on IOS devices.
$.indexedDB(dbName).objectStore(tablename).index("INDICE").each(function(itemLocal) {
itemLocal.delete();
}, [VALORINDICE]).then(function() {
callback();
}, function() {
console.log("error");
});
The problem is if there is more than one record that matches the index, it does not eliminate them, it eliminates the first one and leaves. But if for example I put console.log (itemLocal) instead of itemLocal.delete() if it shows all those that match the index. Any suggestions of something that may be leaking?
I have tried with this code and I get the same error(code without api jquery)
var request = indexedDB.open(DATABASE_NAME);
request.onsuccess = function(event) {
var db = request.result;
var transaction = db.transaction(["TABLE"], "readwrite");
var table = transaction.objectStore("TABLE");
var index = table.index("INDEX");
var req = index.openCursor();
req.onsuccess = function() {
var cursor = req.result;
if (cursor) {
console.info(cursor.value);
cursor["delete"]();
cursor["continue"]();
}
};
req.onerror = function(e) {
console.error(e, req);
};
};
request.onerror = function(e) {
console.error(e, request);
};

Images gets truncated after setting SRC Value (iOS)

I ran into a strange limitation from iOS/Safari/Chrome.
The user can select an image and it filecontent gets pasted into a input element.
The Length of the both are unequal. Is this an iOS limitation?
L.users.importConfigurations = function(options) {
var target = null;
this._getInputFileElement = function() {
var that = this;
fileInput = $('<input type="file" accept="image/*" style="display:none;" capture="camera" />');
fileInput.change(function() {
that._handleFiles(fileInput);
});
return fileInput;
};
this.showFileSelectionDialog = function() {
var fileInput = this._getInputFileElement();
fileInput.click();
};
this._handleFiles = function(fileInput) {
var files = fileInput[0].files;
if (files && files.length) this._readFile(files[0]);
};
this._readFile = function(fileInfo) {
var that = this;
var reader = new FileReader();
reader.onload = function(e) {
that._uploadFile(e.target.result);
};
reader.readAsDataURL(fileInfo);
};
this._uploadFile = function(fileData) {
var fbValue = $(options.target).closest('.fileboxframe').find(".fileboxvalue");
if (fbValue && fbValue.length > 0) {
alert("Length before: " + fileData.length.toString());
fbValue.attr('src', fileData);
alert("Length after (Should be same): " + fileData.length.toString());
alert("Length after (Should be same): " + fbValue.attr("src").length.toString());
}
};
this.showFileSelectionDialog();
};
https://jsfiddle.net/ChristophWeigert/81qu41L5/
I found an answer in this topic:
Why is the default max length for an input 524288?
Solution was to use a textare and not a textbox.

for embedded PDFs, can PDFJS support both scrolling and jump to a page number at the same time?

This seems like it should be very standard behavior.
I can display a scrollable PDF with:
var container = document.getElementById('viewerContainer');
var pdfViewer = new PDFJS.PDFViewer({
container: container,
});
PDFJS.getDocument(DEFAULT_URL).then(function (pdfDocument) {
pdfViewer.setDocument(pdfDocument);
});
and I can display the PDF page by page with something like:
PDFJS.getDocument(URL_ANNOTATED_PDF_EXAMPLE).then(function getPdfHelloWorld(pdf) {
pdf.getPage(pageNumber).then(function getPageHelloWorld(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
But can't seem to find any reference in the API to both allow scrolling and jumping to a particular page, besides:
pdfViewer.currentPageNumber = 3;
which doesn't work...
So I found a way to make this work (mixed with a little Angular code, "$scope.$watch...") I now have other problems with font decoding. But here is a solution that might help someone else.
var me = this;
PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK;
var container = document.getElementById('capso-court-document__container');
function renderPDF(url, container) {
function renderPage(page) {
var SCALE = 1;
var pdfPageView = new PDFJS.PDFPageView({
container: container,
id: page.pageIndex + 1,
scale: SCALE,
defaultViewport: page.getViewport(SCALE),
textLayerFactory: new PDFJS.DefaultTextLayerFactory(),
annotationLayerFactory: new PDFJS.DefaultAnnotationLayerFactory()
});
pdfPageView.setPdfPage(page);
return pdfPageView.draw();
}
function renderPages(pdfDoc) {
var pageLoadPromises = [];
for (var num = 1; num <= pdfDoc.numPages; num++) {
pageLoadPromises.push(pdfDoc.getPage(num).then(renderPage));
}
return $q.all(pageLoadPromises);
}
PDFJS.disableWorker = true;
return PDFJS.getDocument(url)
.then(renderPages);
}
$scope.$watch(function() {
return {
filingUrl: me.filingUrl,
whenPageSelected: me.whenPageSelected,
};
}, function(newVal, oldVal) {
if (newVal.filingUrl) {
//newVal.filingUrl = URL_EXAMPLE_PDF_ANNOTATED;
//newVal.filingUrl = URL_EXAMPLE_PDF_ANNOTATED_2;
//newVal.filingUrl = URL_EXAMPLE_PDF_MULTI_PAGE;
if (newVal.filingUrl !== oldVal.filingUrl &&
newVal.whenPageSelected &&
newVal.whenPageSelected.page) {
scrollToPage(newVal.whenPageSelected.page);
}
//HACK - create new container for each newly displayed PDF
container.innerHTML = '';
var newContainerForNewPdfSelection = document.createElement('div');
container.appendChild(newContainerForNewPdfSelection);
renderPDF(newVal.filingUrl, newContainerForNewPdfSelection).then(function() {
if (newVal.whenPageSelected &&
newVal.whenPageSelected.page) {
scrollToPage(newVal.whenPageSelected.page);
}
});
}
}, true);
function scrollToPage(pageNumber) {
var pageContainer = document.getElementById('pageContainer' + pageNumber);
if (pageContainer) {
container.scrollTop = pageContainer.offsetTop;
} else {
console.warn('pdf pageContainer doesn\'t exist for index', pageNumber);
}
}

407 Proxy Error Encountered with Fusion Tables

When I try to use the docid in place of the table id I get a 407 proxy error. My understanding is that you don't need to authenticate for selecting records, only for inserts, updates, and deletes. When I use the table id, the sql query hangs. I noticed these errors in the Firebug console window.
I am able to receive data from both tables (levels_a.txt & levels_b.txt) when the tables aren't merged. The same isn't true when they are merged. Please see below for my code.
google.load("visualization", "1", { packages: ["corechart", "annotatedtimeline"] });
var map, layer;
var tableID = 3013978;
//var tableID = "1RWnj3geWmOXHcedu8RUeyb1v4ZjZz3YWNpK0MDs";
var location_column = 'geometry';
var name, PID;
var chart;
var jqXHR;
var formatter_long;
var dt;
var rows;
var plot;
var scatter_chart;
var g;
function initialize() {
var latlng = new google.maps.LatLng(53.760861, -98.813876);
var myOptions = {
center: latlng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
mapTypeControlOptions: {
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.SATELLITE,
google.maps.MapTypeId.HYBRID,
google.maps.MapTypeId.TERRAIN
],
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
overviewMapControl: true,
overviewMapControlOptions: {
opened: true
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
layer = new google.maps.FusionTablesLayer({
query: {
select: location_column,
from: tableID
}
});
layer.setMap(map);
google.maps.event.addListener(layer, 'click', function (e) {
name = e.row['name'].value;
PID = e.row['WELL_PID'].value;
drawChart(PID, name);
});
}
function drawChart(PID, name) {
/*
var queryURL = "http://www.google.com/fusiontables/api/query?sql=";
var queryTail = '&jsonCallback=?';
var whereClause = "WHERE 'WELL_PID'=" + PID; // table id 3004502
var query = "SELECT 'Date','Level' FROM 3004502 " + whereClause;
var queryText = encodeURIComponent(query);
*/
//--------------------------------------------------------------------------------------------//
var queryUrlHead = 'http://www.google.com/fusiontables/api/query?sql=';
var queryUrlTail = '&jsonCallback=?';
var whereClause = "WHERE 'WELL_PID'=" + PID; // table id 3004502
var query = "SELECT 'Date','Level' FROM 1RrJI_dWPjrmJ7A6xD_GcZ3nxIso9ZTvOPWp0suI " + whereClause;
var queryurl = encodeURI(queryUrlHead + query + queryUrlTail);
var jqxhr = $.get(queryurl, dataHandler, "jsonp");
//console.log(jqxhr);
/*
var rows;
var items = [];
var arr = [];
var str;
$.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp',
jsonpCallback: 'jsonpCallback',
success: function (data) {
rows = data.table.rows;
for (i = 0; i < rows.length; i++) {
var temp = rows[i];
var this_date;
items.push([parseDate(temp[0]), temp[1]]);
}
processData(items);
},
error: function () { alert("Please wait until chart loads before clicking on another well location."); }
});
*/
}
function dataHandler(d) {
var items = [];
var rows = d.table.rows;
for (i = 0; i < rows.length; i++) {
var temp = rows[i];
var this_date;
items.push([parseDate(temp[0]), temp[1]]);
}
processData(items);
}
function processData(res) {
var options = {
strokeWidth: 0.0,
displayAnnotations: true,
labelsKMB: false,
rollPeriod: 14,
showRangeSelector: true,
connectSeparatedPoints: false,
drawPoints: true,
stepPlot: false,
pointSize: 1,
digitsAfterDecimal: 3
};
var dat = new google.visualization.DataTable();
dat.addColumn('date', 'Date');
dat.addColumn('number', 'Water Level');
console.log(res.toString());
if (res.toString() === "") {
alert("Sorry, there is no data available for this well. Please check back at a later time.");
$("#dg_div").empty();
} else {
dat.addRows(res);
if (g) {
g.destroy();
}
g = new Dygraph(document.getElementById("dg_div"), dat, options);
}
}
I would like to perform the following joins:
geography.kml
name | geometry | description
well_name_and_PID.csv
WELL_PID | Name_Short
levels_a.txt
WELL_PID | Date | Level
levels_b.txt
WELL_PID | Date | Level
Joins:
[geography.kml].name -> [well_name_and_PID.csv].Name_Short
[well_name_and_PID.csv].WELL_PID -> [levels_a.txt].WELL_PID
[well_name_and_PID.csv].WELL_PID -> [levels_b.txt].WELL_PID
The rationale behind having two level files is that this file would othewise exceed the 100 meg table cap. These two files contain similar information.
As usual, any help on this is greatly appreciated.
Thanks in advance,
Michael

An observer for page loads in a custom xul:browser

In my firefox extension I'm creating a xul:browser element. I want to have an observer that intercepts any url changes within the embedded browser and opens the url in a new browser tab (in the main browser). I'd also like new windows spawned by the xul:browser window to open in a tab instead of a new browser window.
I've created an observer which works, but I don't yet know how to apply that observer only to the xul:browser element.
function myFunction(){
var container = jQuery("#container")[0];
var new_browser_element = document.createElement('browser');
container.appendChild(new_browser_element);
var observerService = Components.classes["#mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
observerService.addObserver(myObserver, "http-on-modify-request", false);
}
var myObserver = {
observe: function(aSubject, aTopic, aData){
if (aTopic != 'http-on-modify-request'){
aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
// alert(aSubject.URI.spec);
// Now open url in new tab
}
},
QueryInterface: function(iid){
if (!iid.equals(Components.interfaces.nsISupports) &&
!iid.equals(Components.interfaces.nsIObserver))
throw Components.results.NS_ERROR_NO_INTERFACE;
return this;
}
};
You could try:
var myObserver = {
observe: function(aSubject, aTopic, aData){
if (aTopic == 'http-on-modify-request')
{
aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
var url = aSubject.URI.spec;
var postData ;
if (aSubject.requestMethod.toLowerCase() == "post")
{
var postText = this.readPostTextFromRequest(request);
if (postText)
{
var dataString = parseQuery(postText);
postData = postDataFromString(dataString);
}
}
var oHttp = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
var interfaceRequestor = oHttp.notificationCallbacks.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow);
//check if it is one of your mini browser windows
if (jQuery(DOMWindow).hasClass('mini_browser'))
{
openInTab(url, postData);
var request = aSubject.QueryInterface(Components.interfaces.nsIRequest);
request.cancel(Components.results.NS_BINDING_ABORTED);
}
}
},
QueryInterface: function(iid){
if (!iid.equals(Components.interfaces.nsISupports) &&
!iid.equals(Components.interfaces.nsIObserver))
throw Components.results.NS_ERROR_NO_INTERFACE;
return this;
},
readPostTextFromRequest : function(request) {
var is = request.QueryInterface(Components.interfaces.nsIUploadChannel).uploadStream;
if (is)
{
var ss = is.QueryInterface(Components.interfaces.nsISeekableStream);
var prevOffset;
if (ss)
{
prevOffset = ss.tell();
ss.seek(Components.interfaces.nsISeekableStream.NS_SEEK_SET, 0);
}
// Read data from the stream..
var charset = "UTF-8";
var text = this.readFromStream(is, charset, true);
// Seek locks the file so, seek to the beginning only if necko hasn't read it yet,
// since necko doesn't seek to 0 before reading (at lest not till 459384 is fixed).
if (ss && prevOffset == 0)
ss.seek(Components.interfaces.nsISeekableStream.NS_SEEK_SET, 0);
return text;
}
else {
dump("Failed to Query Interface for upload stream.\n");
}
}
return null;
},
readFromStream : function(stream, charset, noClose)
{
var sis = Components.classes["#mozilla.org/binaryinputstream;1"]
.getService(Components.interfaces.nsIBinaryInputStream);
sis.setInputStream(stream);
var segments = [];
for (var count = stream.available(); count; count = stream.available())
segments.push(sis.readBytes(count));
if (!noClose)
sis.close();
var text = segments.join("");
return text;
}
};
function openInTab(url, postData)
{
var wm = Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var recentWindow = wm.getMostRecentWindow("navigator:browser");
if (recentWindow)
{
// Use an existing browser window, open tab and "select" it
recentWindow.gBrowser.selectedTab = recentWindow.gBrowser.addTab(url, null, null, postData);
}
}
function parseQuery() {
var qry = this;
var rex = /[?&]?([^=]+)(?:=([^&#]*))?/g;
var qmatch, key;
var paramValues = {};
// parse querystring storing key/values in the ParamValues associative array
while (qmatch = rex.exec(qry)) {
key = decodeURIComponent(qmatch[1]);// get decoded key
val = decodeURIComponent(qmatch[2]);// get decoded value
paramValues[key] = val;
}
return paramValues;
}
function postDataFromString(dataString)
{
// POST method requests must wrap the encoded text in a MIME
// stream
var stringStream = Components.classes["#mozilla.org/io/string-input-stream;1"]
.createInstance(Components.interfaces.nsIStringInputStream);
if ("data" in stringStream) // Gecko 1.9 or newer
stringStream.data = dataString;
else // 1.8 or older
stringStream.setData(dataString, dataString.length);
var postData = Components.classes["#mozilla.org/network/mime-input-stream;1"].
createInstance(Components.interfaces.nsIMIMEInputStream);
postData.addHeader("Content-Type", "application/x-www-form-urlencoded");
postData.addContentLength = true;
postData.setData(stringStream);
return postData;
}
I'll update this to fill in the blanks in a bit.
edit: see http://forums.mozillazine.org/viewtopic.php?p=2772951#p2772951 for how to get the source window of a request.
Request cancellation code from http://zenit.senecac.on.ca/wiki/index.php/Support_For_OpenID.
see http://mxr.mozilla.org/mozilla-central/source/netwerk/base/public/nsIRequest.idl for details on nsIRequest.
See http://forums.mozillazine.org/viewtopic.php?p=2404533#p2404533 and https://developer.mozilla.org/en/XUL/Method/addTab for the definition of addTab.
parseQuery comes from http://blog.strictly-software.com/2008/10/using-javascript-to-parse-querystring.html.
See https://developer.mozilla.org/en/Code_snippets/Post_data_to_window#Preprocessing_POST_data for how to process post data in a form suitable for addTab.
ReadPostFromText and ReadTextFromStream both come from firebug (though slightly modified)

Resources