Read .txt file into HTML image map - javascript

I am a beginner in HTML and am writing a webpage where a canvas is segmented into a grid. Users can mouse over rectangles within the grid and see them highlighted.
I have many coordinates of the rectangles stored in a .txt file (each row has 4 coordinates separated by spaces) and am hoping to read in the file line by line and input them into my code as variables as I might with Python.
<area shape="rect" coords="xmin,xmax,ymin,ymax" href="#"...>
Any advice/where to point me is much appreciated, as there are too many coordinates for me to input manually!

What you're looking for is AJAX. You can use something like the following.
var xhr = new XMLHttpRequest();
xhr.open("GET", "coords.txt", true);
xhr.onload = function(e) {
if(this.status == 200) {
// get text contents
var coords = this.responseText.split("\n");
coords.forEach(function(coord) {
// create new area element
var area = document.createElement("area");
area.shape = "rect";
area.coords = coord.replace(/ /g,","); // replace spaces with commas
area.href = "#";
// get your map element somehow
document.getElementById("myMap").appendChild(area);
});
}
};
xhr.send();

Related

Uploading Images to WYSIWYG editor and having default styling applied

I have created a wysiwyg text editor for my site and am trying to work with images.
So far I've got my image being uploaded and being added to my text editor where I want it using something like this:
$("#upload_wysiwyg_image").unbind("click").bind("click", function() {
var formData = new FormData();
var image_to_upload = document.getElementById("wysiwyg_image").files[0];
formData.append("wysiwyg_image", image_to_upload);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText.includes('uploaded')){
var upload_string = this.responseText;
var image_name = upload_string.replace("uploaded ","")
var image_path = '../media/wysiwyg_images/'+image_name;
execCmdWithArg('insertImage', image_path);
}
}
};
xmlhttp.open("POST", "upload_wysiwyg_image.php", true);
xmlhttp.send(formData);
});
function execCmdWithArg (command, arg){
richTextField.document.execCommand(command, false, arg);
}
I want to be able to format the image at this point when it is being inserted. So for instance set a max-width/max-height or be able to select a float value for positioning.
Can this be done at this point while it is being inserted or will I need to insert it, and then call another function to set values for styling?
If anyone can point me in the right direction for this it would be greatly appreciated.

Calling a JavaScript function from a link set at canvas opens a new tab with an error

I'm trying to set a hyperlink on a specific part of an HTML5 Canvas. I want that clicking of that hyperlink calls a Javascript function that changes some contents onthe canvas itself but does ont open any new browser tab or page. However, what I'm getting is (i) the canvas contents re actually changed by the function I'm calling BUT (ii) I get a new broser tab displaying an error ERR_EMPTY_RESPONSE. How can I fix that? Thanks in advance!
My piece of code is (I'm using a variation of the the "link on canvas" solution posted here by 'dogbane' some years ago:
// this function is called from WITHIN another function (print_meteosarriaYearMonthData) which contains the variable declarations
function draw_link(ctx)
{
//add mouse listeners
canvas.addEventListener("mousemove", on_mousemove, false);
canvas.addEventListener("click", on_click, false);
}
//check if the mouse is over the link and change cursor style
function on_mousemove (ev) {
var x, y;
// Get the mouse position relative to the canvas element.
if (ev.layerX || ev.layerX == 0) { //for firefox
x = ev.layerX;
y = ev.layerY;
}
x-=canvas.offsetLeft;
y-=canvas.offsetTop;
//is the mouse over the link?
if(x>=linkX && x <= (linkX + linkWidth) && y<=linkY && y>= (linkY-linkHeight)){
document.body.style.cursor = "pointer";
inLink=true;
}
else{
document.body.style.cursor = "";
inLink=false;
}
}
//if the link has been clicked, go to link
function on_click(e) {
if (inLink) {
// this function is where the link-related functions are embedded and does the job of changing the canvas contents (depending on the parameter METEODATA_MONTH or METEODATA_YEAR
print_meteosarriaYearMonthData(METEODATA_MONTH);
return false; // is this necessary?
}
}
The code of print_meteosarriaYearMonthData is
function print_meteosarriaYearMonthData(yearOrMonth)
{
var canvas = document.getElementById("meteoinfo");
var ctx = canvas.getContext("2d");
var linkWidth;
var linkHeight;
var linkX;
var linkY;
if (yearOrMonth == METEODATA_YEAR)
{
// PRINT YEAR
<...code to pint year>
// Print tab & dimmed month with link
<further code to print data on canvas>
linkWidth = ctx.measureText(month+"/"+year).width;
linkHeight = 30;
linkX = meteoYearDataYearAnchorX+50;
linkY = meteoYearDataYearAnchorY-20;;
draw_link(ctx); // CALL TO DRAW LINK FUNCTION
// Get yearly data
<code to get & print yearly data >
}
else
{
// PRINT MONTH
<code to print current month>
}
// start of draw_link, on_mousemove & on_click functions code
function draw_link(ctx)
{
...
}
function on_mousemove(ctx)
{
...
}
function on_click(ctx)
{
...
}
}
Forget the question. The code was OK. Apparently I was working with a previous wrong version of the Javascript file stored in the cache. Now it is working fine.
Excuse the inconveniences and thank you everybody (in particular to 'somethinghere') who may have looked at the post and try to find a cause for the behaviour I described.
Regards

Set background color for excel range using javascript

I want to open an existing .xls file, set the background color for the header and also merge few columns of the 1st row using javascript.
Thanks for any help.
Here is my code as of now.. I could, set the background color index of the cell and merge the cells.
var xls = new ActiveXObject("Excel.Application");
xls.visible = true;
xls.DisplayAlerts=false;
var wb=xls.Workbooks.Open("C:\\ECN REPORT.xls");
xls.Range("A1","B1").Interior.ColorIndex=37;
xls.Range("C1","D1").Interior.ColorIndex=37;
xls.Range("A1:D1").Merge();
wb.SaveAs("C:\\ECN REPORT.xls");
xls.Quit();
I have set the DisplayAlerts=False and want to save the excel again with wb.SaveAs(); It saves the file without prompt, but the merge changes are not reflected in the excel file.
Could somebody let me know where im wrong? Thanks in advance.
Font Color:
oSheet.Range("A1","X1").Font.ColorIndex = 49;
Interior Color:
oSheet.Range("A1","X1").Interior.ColorIndex = 15;
Merging Cells:
oSheet.Range("A1","X1").Merge();
or
oSheet.Range("A1","X1").MergeCells = true;
Here's the working example for my question.
It checks if the file exists, if so deletes and then creates an excel, merges columns, sets background colors,borders,fon.
var Excel = new ActiveXObject("Excel.Application");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var checkFile= fso.FileExists("C:\\Report.xlsx");
if(checkFile)
{
fso.DeleteFile("C:\\Report.xlsx",true);
}
var ExcelSheet=new ActiveXObject("Excel.Sheet");
ExcelSheet.ActiveSheet.Range("A1","G1").Merge();
ExcelSheet.ActiveSheet.Range("A1").value="ECN REPORT";
ExcelSheet.ActiveSheet.Range("A1").Font.Bold = true;
ExcelSheet.ActiveSheet.Range("A1").Font.Size = 24;
ExcelSheet.ActiveSheet.Range("A1").HorizontalAlignment = -4108;
ExcelSheet.ActiveSheet.Range("A1","F1").Interior.ColorIndex=2;
// xlEdgeLeft,xlEdgeTop,xlEdgeBottom,xlEdgeRight all set to continuous borders
ExcelSheet.ActiveSheet.Range("A1","F1").Borders(7).LineStyle=1;
ExcelSheet.ActiveSheet.Range("A1","F1").Borders(8).LineStyle=1;
ExcelSheet.ActiveSheet.Range("A1","F1").Borders(9).LineStyle=1;
ExcelSheet.ActiveSheet.Range("A1","F1").Borders(10).LineStyle=1;

How to display image from another page in my page

I want to start a greasemonkey plugin to an existing page. The plugin should fetch and display some images automatically, each image from different pages.
I thought of using jQuery.get("link", function(data)) and hide the page and display the images only but on an average to display 4 images I should load 6 webpages into present webpage it is creating a delay in loading.
Is there any other work around to create a function that loads the page html of all image pages in background or in another tab and get the href of <a> tag's in that page, into my page and load only images into my page?
You can try this solution below.
Just put the URLs you want in the "pages" array. When the script runs, it makes Ajax calls in the background. When they are ready, it searches the source returned for images and picks one randomly. If found, it wraps the image in a link to the page where it found it (or if available, the image's url) and inserts the linked image to the top of the body of your own current page.
You can try the code by pasting it into your browser's JavaScript console and it will add the images to the current page.
You also see a demo here: http://jsfiddle.net/3Lcj3918/3/
//pages you want
var pages =
[
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random'
]
//a simple function used to make an ajax call and run a callback with the target page source as an argument when successful
function getSubPageSource(url, successCallback)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
//when source returned, run callback with the response text
successCallback(xhr.responseText);
}
};
//requires a proxy url for CORS
var proxyURL = 'https://cors-anywhere.herokuapp.com/';
xhr.open('GET', proxyURL+url, true);
//set headers required by proxy
xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");
xhr.setRequestHeader("Access-Control-Allow-Origin","https://cors-anywhere.herokuapp.com/");
xhr.send();
}
//a function that extract images from given url and inserts into current page
function injectImagesFrom(url)
{
getSubPageSource(url, function(data)
{
//trim source code to body only
var bodySource = data.substr(data.indexOf('<body ')); //find body tag
bodySource = bodySource.substr(bodySource.indexOf('>') + 1); //finish removing body open tag
bodySource = bodySource.substring(0, bodySource.indexOf('</body')); //remove body close tag
//create an element to insert external source
var workingNode = document.createElement("span");
//insert source
workingNode.innerHTML = bodySource;
//find all images
var allImages = workingNode.getElementsByTagName('img');
//any images?
if (allImages.length > 0)
{
//grab random image
var randomIndex = Math.floor(Math.random() * allImages.length);
var randomImage = allImages.item(randomIndex);
//add border
randomImage.setAttribute('style', 'border: 1px solid red;');
//restrain size
randomImage.setAttribute('width', 200);
randomImage.setAttribute('height', 200);
//check if parent node is a link
var parentNode = randomImage.parentNode;
if (parentNode.tagName == 'A')
{
//yes, use it
var imageURL = parentNode.getAttribute('href');
}
else
{
//no, use image's page's url
var imageURL = url;
}
//add a link pointing to where image was taken from
var aLink = document.createElement("a");
aLink.setAttribute('href', imageURL);
aLink.setAttribute('target', '_blank');
//insert image into link
aLink.appendChild(randomImage);
/* INSERT INTO PAGE */
//insert image in beginning of body
document.body.insertBefore(aLink,document.body.childNodes[0]);
//remove working node children
while (workingNode.firstChild) {
workingNode.removeChild(workingNode.firstChild);
}
//unreference
workingNode = null;
}
});
}
for (var ii = 0, nn = pages.length; ii < nn; ii++)
{
injectImagesFrom(pages[ii]);
}

OpenLayers Markers with custom Text / Label

I have "N" markers on an Openlayers map and I need to "label" these markers (Meaning: Put a text in/on them)
I have tried several ways but still couldn't achieve what I need.
My JS code snippet (Removed some irrevelant stuff from the code):
function getWeatherInfo(){
if(wheatherOfCitiesMarkerLayer == null){
wheatherOfCitiesMarkerLayer = new OpenLayers.Layer.Markers("WeatherMarkerLayer");
map.addLayer(wheatherOfCitiesMarkerLayer);
}
$.getJSON(qryPointResultListForAllCities(), function(data) {
if(data!= null){
var size = new OpenLayers.Size(60,45);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
for(var i = 0; i < data.pr.length; i ++){
// Create markers by using the returned data from the server
//...
//... Removed some irrevelant stuff
var lat = data.pr[i].la;
var lon = data.pr[i].lo;
var infos = data.pr[i].info.infos;
var infop = data.pr[i].info.infop;
var infocc = data.pr[i].info.infocc;
var icon = new OpenLayers.Icon('my_marker_img.png',size,offset);
location = new OpenLayers.LonLat(lon, lat);
location = transformFromWGS1984ToSphericalMercator(location.clone());
marker = new OpenLayers.Marker(location,icon.clone());
wheatherOfCitiesMarkerLayer.addMarker(marker);
}
}
}
}
What I need to do is put a label or text in/on each marker on the map.
Since you are taking marker data from server anyway, what you can do is, create a layer in a map file with just the label class defined and add it on your marker layer as a overlay.
Hope this helps.
Instead of adding text (or label) to a marker, you can add a marker to a label.
This is done by creating a new text file with the location, title, description and path to your icon (not required, it will use the default if none is set). For example,
if you want to place two markers on the map, the text file may look like this
point title description icon
10,99 An labeled marker with default image
12,34 Another marker This is my label text http://example.com/marker.png
Please note that there should be tabs between the names and parameters, not spaces. There is also a tab at the end of the second line where no icon is given.
Save this file somewhere on your site and put this code where your layers are being initialized.
var textl = new OpenLayers.Layer.Text("text", {location : "data_dile.txt"});
map.addLayer(textl);
The text file may be created dynamically though server-side languages, such as PHP.
There is an online example here.

Categories

Resources