The GeoJSON string of shapefile while using *.toGeoJSON() is incomplete in Mapbox - javascript

I'm using Mapbox with Leaflet for drawing, editing and removing polygons etc. I'm also using leaflet.shapefile to upload shapefiles and add them to the map.
For a certain application, I need to convert the layer to a GeoJSON object, which I then convert to a JSON string using this code:
var fcgeojson = layer.toGeoJSON();
var fcgeojsonstring = JSON.stringify(fcgeojson);
I have a working version of this in this jsfiddle. And for most of the shapefiles, it works just fine. However, in some cases, like when I use this shapefile, the JSON string of one of the polygons is actually incomplete. You can check out those strings by clicking on the "Test" button in the jsfiddle.
I haven't been able to figure out why this is happening (my guess is maybe the shapefile has too many vertices).

The method you are using to test the json string is where the problem arises. The incomplete json string comes from either stringify or alert. For this question, the problem likely lies with the latter.
Javascript alerts truncate messages at 10 000 characters, which coincidentally is exactly the number of characters that appear for me in the alert box when testing in your jsfiddle with your shapefile loaded.
When I used console.log() rather than alert() I could see the entire json (which is nearly 14 000 characters long). Though, there is a max size for console.log that varies with browsers, so you could always set the content of a div or other element to show the full content on screen.

Related

IntelliJ / WebStorm code style option to retain JSON arrays on a single line

Consider the following snippet of code that I have manually formatted into the preferred structure. In particular each attribute has one line for its value. Even arrays have only one (possibly v long) line.
This is precisely the output format generated by jsfiddle.net https://jsfiddle.net/javadba/toq7gby2/
Note that the following - each complete array entry on its own line - would also be a fine result:
I am looking into whether the following formatted javascript code were possible when using the Code | Reformat Code option in the Jetbrains family of IDE's. In particular the Settings | Editor | Code Style | Javascript option to keep line breaks or not:
This "on" selection results in one of many different results depending on how I entered/pasted the JSON originally. It does minimal reformatting. Here is one possible result
That is actually too much free style for me. I'm looking for that first result - which has all the entries aligned.
The other end of the spectrum happens when we turn off the line breaks:
Now the result is more compact - actually too compact. All entries in a given dict are on the same (possibly huge) line:
I'm wondering if there were any way to format the JOSN with Name/Value pairs each on their own line - as shown in the first screenshot?
The closest setup I can suggest is
but it's not exactly what you are looking for.
So using Prettier for code reformatting seems to be the best way to go:

JS: Text to Image

I'm currently making a toy project that converts a string of text into a series of GitHub commits. The end result should look something like this:
The solution I am currently working on is to take a string of text and convert each character to a 7x7 array of boolean values, where true is a green dot, and false is not. Then I'll iterate over that to come up with an array of commits to send to GitHub.
For the first part, I've been searching for an npm package that takes text, like ascii characters and returns a bmp or similar image representing the text, but I haven't had any luck.
Does anybody know of a library that will do something like that? My main requirement is that I can set the 'resolution' of the output, so I can get a 7x7 image from it. Alternatively, if there is an entirely different solution, I'd be happy to hear that too.
Thanks
Since you are using node.js, you could use opencv4node.js. It has features to write text to an image, that are normally used to annotate images, but should work well for your case.
The image could be whatever grid size you prefer. Then you could iterate over the pixels and use their coordinates to determine the commits.

Javascript retrieve linebreaks from dom [duplicate]

I need to add line breaks in the positions that the browser naturally adds a newline in a paragraph of text.
For example:
<p>This is some very long text \n that spans a number of lines in the paragraph.</p>
This is a paragraph that the browser chose to break at the position of the \n
I need to find this position and insert a <br />
Does anyone know of any JS libraries or functions that are able to do this?
The only solutuion that I have found so far is to remove tokens from the paragraph and observe the clientHeight property to detect a change in element height. I don't have time to finish this and would like to find something that's already tested.
Edit:
The reason I need to do this is that I need to accurately convert HTML to PDF. Acrobat renders text narrower than the browser does. This results in text that breaks in different positions. I need an identical ragged edge and the same number of lines in the converted PDF.
Edit:
#dtsazza: Thanks for your considered answer. It's not impossible to produce a layout editor that almost exactly replciates HTML I've written 99% of one ;)
The app I'm working on allows a user to create a product catalogue by dragging on 'tiles' The tiles are fixed width, absolutely positioned divs that contain images and text. All elemets are styled so font size is fixed. My solution for finding \n in paragraph is ok 80% of the time and when it works with a given paragrah the resulting PDF is so close to the on-screen version that the differences do not matter. Paragraphs are the same height (to the pixel), images are replaced with high res versions and all bitmap artwork is replaced with SVGs generated server side.
The only slight difference between my HTML and PDF is that Acrobat renderes text slightly more narrowly which results in line slightly shorter line length.
Diodeus's solution of adding span's and finding their coords is a very good one and should give me the location of the BRs. Please remember that the user will never see the HTML with the inserted BRs - these are added so that the PDF conversion produces a paragraph that is exactly the same size.
There are lots of people that seem to think this is impossible. I already have a working app that created extremely accurate HTML->PDF conversion of our docs - I just need a better solution of adding BRs because my solution sometimes misses a BR. BTW when it does work my paragraphs are the same height as the HTML equivalents which is the result we are after.
If anyone is interested in the type of doc i'm converting then you can check ou this screen cast:
http://www.localsa.com.au/brochure/brochure.html
Edit: Many thanks to Diodeus - your suggestion was spot on.
Solution:
for my situation it made more sense to wrap the words in spans instead of the spaces.
var text = paragraphElement.innerHTML.replace(/ /g, '</span> <span>');
text = "<span>"+text+"</span>"; //wrap first and last words.
This wraps each word in a span. I can now query the document to get all the words, iterate and compare y position. When y pos changes add a br.
This works flawlessly and gives me the results I need - Thank you!
I would suggest wrapping all spaces in a span tag and finding the coordinates of each tag. When the Y-value changes, you're on a new line.
I don't think there's going to be a very clean solution to this one, if any at all. The browser will flow a paragraph to fit the available space, linebreaking where needed. Consider that if a user resizes the browser window, all the paragraphs will be rerendered and almost certainly will change their break positions. If the user changes the size of the text on the page, the paragraphs will be rerendered with different line break points. If you (or some script on your page) changes the size of another element on the page, this will change the amount of space available to a floating paragraph and again - different line break points.
Besides, changing the actual markup of your page to mimic something that the browser does for you (and does very well) seems like the wrong approach to whatever you're doing. What's the actual problem you're trying to solve here? There's probably a better way to achieve it.
Edit: OK, so you want to render to PDF the same as "the screen version". Do you have a specific definitive screen version nominated - in terms of browser window dimensions, user stylesheets, font preferences and adjusted font size? The critical thing about HTML is that it deliberately does not specify a specific layout. It simply describes what is on the page, what they are and where they are in relation to one another.
I've seen several misguided attempts before to produce some HTML that will exactly replicate a printed creative, designed in something like a DTP application where a definitive absolute layout is essential. Those efforts were doomed to failure because of the nature of HTML, and doing it the other way round (as you're trying to) will be even worse because you don't even have a definitive starting point to work from.
On the assumption that this is all out of your hands and you'll have to do it anyway, my suggestion would be to give up on the idea of mangling the HTML. Look at the PDF conversion software - if it's any good it should give you some options for font kerning and similar settings. Playing around with the details here should get you something that approximates the font rendering in the browser and thus breaks lines at the same places.
Failing that, all I can suggest is taking screenshots of the browser and parsing these with OCR to work out where the lines break (it shouldn't require a very accurate OCR since you know what the raw text is anyway, it essentially just has to count spaces). Or perhaps just embed the screenshot in the PDF if text search/selection isn't a big deal.
Finally doing it by hand is likely the only way to make this work definitively and reliably.
But really, this is still just wrong and any attempts to revise the requirements would be better. Keep going up one step in the chain - why does the PDF have to have the exact same ragged edge as some arbitrary browser rendering? Can you achieve that purpose in another (better) way?
Sounds like a bad idea when you account for user set font sizes, MS Windows accessibility mode, and the hundreds of different mobile devices. Let the browser do it's thing - trying to have exact control over the rendering will only cause you hours of frustration.
I don't think you'll be able to do this with any kind of accuracy without embedding Gecko/WebKit/Trident or essentially recreating them.
Maybe an alternative: do all line-breaks yourself, instead of relying on the browser. Place all text in pre tags, and add your own linebreaks. Now at least you don't have to figure out where the browser put them.

multiple svg images in one file breaks text

I have a web app that uses SVG files to map various sorts of data onto our underlying experimental dataset. Each SVG file represents a mapping of one type of data to the experimental dataset and, in most of the pages on the site, they are displayed one at a time, with the various nodes carrying tooltips to make the maps more informative and links to associated data.
I would like to add a page where maps can be compared side-by-side, which means having multiple self-contained SVG's all on the same page. When I do this, however, the files seem to step on each others' toes in that only the first SVG on the page displays the correct text in the labels and axes. The rest appear to inherit the alphabet used in the first image, leaving the axes and labels garbled and nonsensical.
The snippet below shows how I am currently embedding the SVG's in the page. The object blocks are loaded up with SVG content via javascript/ajax when the user chooses a map on a dropdown menu. Everything functions correctly except for the noted problem with the SVG text.
<object id="map" name="map" class="compBuild" width=800 height=460></object>
Javascript:
$(document).on("change", ".db_field", function(e) {
var tmp = this.name.split("_");
var field = "map_" + tmp[1];
$(document.getElementById(field)).load(getSvgUrl($(this).val()));
// getSvgUrl just makes a Jquery AJAX call to obtain the location of
// the SVG file.
})
Maybe not obvious from the code given, but what actually happens on the page is that the menus and object blocks are dynamically generated, so the actual drop-downs and object blocks are addressed as mapSelect_X map_X, where X is a number appended when the block is created. (code not shown for the sake of brevity!)
I am wondering if there is a workaround for this as I would rather not convert the SVG files to images, since I would lose the functionality in the SVG's. Any help would be appreciated. Thanks!
Check that there are no duplicate id attributes in the two SVGs. ids must be unique on the page, otherwise any SVG features that use id references (like <use>, gradients etc) can't be trusted to point to the right thing.
Since Chrome and FF handle duplicate ids differently, a quick way to check this is the cause would be to see if the two browsers render the two-svg page differently.

googleVis datatype conversion in R does not seems to work

I have been working with 'googleVis' and R in order to produce a Line chart using Google charts APIs.
On Google API's tutorial I found that data conversion in Javascript is used to determine if the axes will be "continuous"(using Numeric Javascript type) and "discrete" (using String).
I believe with googleVis is the same, since datatypes are derived from R.
Problem is, in the following example (which I modified after taking it from the R demo function), the X axis values are equally spaced (hence, still discrete), despite they seem to be "Numeric"
library(googleVis)
df=data.frame(val1=c(10,13,100), val2=c(23,12,32))
Line <- gvisLineChart(df)
plot(Line)
Could someone please me help to understand this? Thank you very much!
Full disclosure: I love the googleVis package.
I see the same behavior you do, even after updating to the latest version of googleVis (not yet on CRAN). I don't know if this is a bug or not; the googleVis documentation for gvisLineChart mentions continuous data, but nothing I tried allows me to plot the X axis as numerical.
You can get clues as to what's happening when you change aspects of your code in generating googleVis charts and graphs if you right-click on the web page that gets displayed with the plot, and choose "View Page Source." This page is where the magic happens, and is the HTML output from the googleVis package.
The problematic line in this case is the one that reads "data.addColumn('string','val1');
In this line, the word 'string' should be 'number', and the val1 values should not be in quotes in the data section.
You can get the results you want, though, by using gvisScatterChart instead:
library(googleVis)
df=data.frame(val1=c(10,13,100), val2=c(23,12,32))
Line <- gvisScatterChart(df, options=list(lineWidth=2, pointSize=0))
plot(Line)

Categories

Resources