What came to mind trying out a pretty simple but effective “iPad Case with Keyboard” product the other day was Tablet Run Web Server Blog PHP Tutorial, the scenario for which was that we had no laptop available and were constructing this blog’s content just with an iPad.
To us, at least, to even contemplate the publishing of content with even only a few paragraphs, assuming you can sort out the sftp needed to upload, we would want a Bluetooth Keyboard to come into the picture, along with the “tablet”, in our case an Apple iPad. We’ve talked about this before, and the other version was good too, but this product we’re talking about today, also tries, again, helping out the iPad, with a stand, for better viewing conditions and to better match that L shape a laptop can make for best work conditions.
On a day’s worth of use, we’d give it a big tick, as far as productivity improvements are concerned … minus that fifteen minutes working out that Fn-C got you to be able to pair the keyboard with the iPad up at …
Mulling continues unabated, after yesterday’s Tablet Run Web Server Blog Follow Up Tutorial as shown below, over how feasible it is to run this blog from a tablet … like an iPad … by today, putting the arrangement to the test of doing some PHP software development with the iPad. Spoiler alert … you can, but it’s a bit more painful than for HTML work, and needs some preparation in advance … but would you want to long term? For me, it’s still “not so much”.
You may recall from yesterday’s work …
The pleasant surprise I hadn’t anticipated out of our steps below, to do it …
Used “Save As” to give it the flickrfeedbigborder.html filename we ended up using (and Nitro HTML does not like non-alphanumeric characters by the way)
Used “Email as Attachment” to email as attachment … doh!
Open Mail app and tap/click into this email
Lo and behold a Share option of the attachment of this email is an FTPManager app (s)FTP file transfer … yayyyyyy!
… was that FTPManager attachment Share option, in that last step above … brilliant!
… well … the only difference today is that the content of our new webpage contents is PHP … our Apache/PHP/MySql web server serverside programming language of choice.
Today, a curiosity of mine going back “forevvvvver” was resolved for me … don’t expect PHP housed in a web server file with an extension .htm or .html work the PHP logic, unless you change something bizarre in Apache’s httpd.conf or .htaccess arrangements, perhaps. So how does that fit with the iPad’s “Nitro HTML” app not allowing file extensions of .php “out of the box”. Our way around this today involves that “preparation in advance” that the iPad’s functionality, as we have it at the moment, won’t help you with. That solution is to have an inhouse (something like) renamer.php PHP webpage with password protection, at the very least, and more protections, please, as you think fit … because this is a functionality you slow down and think about long and hard first … can come to the rescue renaming the .html out of “Nitro HTML” app to .php … bearing in mind the “FTPManager” app “out of the box” has no renaming functionality.
So, what are we doing today to need PHP? We use PHP flickrfeedseveral.php to read the HTML of yesterday to turn the “20” in “Random Flickr Feed – Latest 20” to be variable … 20 or less.
You can try out the predominantly iPad inspired live run link, to see for yourself.
We’ve continued our mulling, after yesterday’s Tablet Run Web Server Blog Primer Tutorial as shown below, over how feasible it is to run this blog from a tablet … like an iPad … by today, putting the arrangement to the test of doing some HTML software development with the iPad. Spoiler alert … you can … but would you want to long term? For me, not so much.
The pleasant surprise I hadn’t anticipated out of our steps below, to do it …
Used “Save As” to give it the flickrfeedbigborder.html filename we ended up using (and Nitro HTML does not like non-alphanumeric characters by the way)
Used “Email as Attachment” to email as attachment … doh!
Open Mail app and tap/click into this email
Lo and behold a Share option of the attachment of this email is an FTPManager app (s)FTP file transfer … yayyyyyy!
… was that FTPManager attachment Share option, in that last step above … brilliant!
So maybe you’d like to try the “fruits of the iPad’s labour” with this live run link, and hope to see you back soon.
We’ve been mulling over how feasible it is to run this blog from a tablet … like an iPad … please don’t ask why? Sorry seems to be the hardest word.
There are two major reasons it is difficult with an iPad “out of the box”, but who says you have to live in a box. That was rhetorical.
Anyway, the two reasons are …
the extreme pain of a native iPad keyboard “out of the box” … like to meet the person who doesn’t feel this when writing hand coded HTML, which is our wont hereabouts … oh, hello Mr Smith … oh, and you too Ms Smith … all right, that’s enough Cousin Smith … we don’t need your inferiority complex campaign thank you very much … no, I wasn’t thanking you … gheese … thinking on it, as painstaking as the really small keyboard buttons would be, to optionally have a mode of keyboard like QWERTY (sorry some people) would be nice as an option “out of the box” for hand coding HTML masochists
the (s)FTP question of getting media and HTML over to our web server … though, if you don’t need to show code in your WordPress blog, maybe you could do away with no (s)FTP thoughts … though know for a fact you would be causing grief to neglected software code components
Now today you may detect a little flippancy, a little triumphalism even … but it won’t last … however, the reason is twofold … one hardware and one software … and a warm and fuzzy conjoined Goldilocks feeling of the porridge in between (that must be networking) … but we digress …
hardware wise … and we’re sorry it cost something, but believe me, it could be worth it … we bought a Logitech K480 Multi-Device Bluetooth Keyboard … yayyyyyyyy! … no more scrambling around between keyboard modes looking for the < and >
software wise … and we’re back to it costing nothing … we looked on Apple Store for “HTML editor” and looked at the first screen’s worth of free apps … there were 4 and favoured out of the four, at a first brief look, in “most liked order first” order …
Nitro HTML … our blog posting today was written with it and the Bluetooth keyboard … so, thanks …
HTML editor
CodeMaster
Ca
Nitro HTML caught my eye for its …
email as attachment your HTML … and HTML editor for its …
(s)FTP functionality
… especially so, with the latter, because it augments the excellent iPad app FTPManager free version we already have, which can help us (s)FTP over to our web server our Photos app file(s), but not HTML, at least in this free version we have hereabouts. Pay a little for FTP on the Go Pro app and this will handle text file (s)ftp transfers.
We’ve been typing for quite a few minutes now, and the “glow” hasn’t subsided, and though we still prefer the good ol’ MacBook Pro methods … well … if push comes to shove … maybe you could do more than I initially gave credit to running a web server via just a tablet … we’ll see.
Did you know?
Just before we “see” let’s “sense”. Before all this “blurb” above a huge thing you should not be scared of on a tablet if you are going to take on this “tablet only” blog approach, is to not be scared of the iPad’s “long hover” over (HTML) text “Select” option, because it is a crucial start to Copy/Paste operations on a tablet. And if you do lots of “long hover” over (HTML) text work, don’t be shy to start the “long hover” in the middle of a block of HTML to get a good spread with those initial positioners … you’ll see what I mean if/when you do a lot of Copy/Paste tablet work.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
Have you been waiting for more “heads up” regarding issues we’ll have moving from a PHP (of a version starting with a 5) to a PHP (of a version starting with an 8)? Join the crowd?!
Warning
This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.
Alternatives to this function include:
preg_match() (with the i (PCRE_CASELESS) modifier)
… for you today, that worked on CentOS but not on AlmaLinux regarding our WordPress Blog search functionality inhouse Title RE checkbox option. Changed code goes …
<?php
function someof($sbits, $viapm) {
global $onclick;
$obits="";
$obits=str_replace('></option>','></OPTION>',$sbits);
$zobits=explode("</option>",$obits);
if (sizeof($zobits) > 1) {
$obits=str_replace("Tutorials (show blog, toggle sort order) ...","Tutorials about " . $viapm . " (or ask about another topic)",$zobits[0]) . "</option>";
if ($viapm != "") {
for ($j=1; $j<sizeof($zobits); $j++) {
$title=explode(">",$zobits[$j])[-1 + sizeof(explode(">",$zobits[$j]))];
//if (eregi($viapm, $title)) {
if (preg_match('/' . $viapm . '/i', $title)) {
$onclick=" onchange=";
$obits.="\n<option " . str_replace("_blank","myi",str_replace("windowopen","window.open",explode("<option ", $zobits[$j])[-1 + sizeof(explode("<option ", $zobits[$j]))])) . "</option>";
}
}
}
}
return $obits;
}
Have you been waiting for more “heads up” regarding issues we’ll have moving from a PHP (of a version starting with a 5) to a PHP (of a version starting with an 8)? Join the crowd?! But so far, it hasn’t been that bad. That is, until we started into looking at the PHP TimeZone functionalities. Going back to a previous time of referencing this, at the recent Google Charts Geo Chart Region Picker Conditional Positioning Tutorial, associative array based codelines like …
Google Charts Geo Chart Region Picker Alignment Tutorial
In our inhouse Region Picker we like the way the right hand webpage side involved some useful …
position: sticky;
… positioning, useful within the realms of what is going on on the right hand side.
But now we’re wanting some horizontal integration, linking commonalities of left and right regarding the country of interest, as a user’s eyes scan across the webpage, at pivotal times.
… all feature the great [element].scrollIntoView() way to programmatically scroll, rather than use (the sometimes ignored) window.scrollTo([left],[top]); or location.href=’#[elementID]’; approaches. It has the advantage of not altering location.hash (if you see that as a plus). We’d rather not add complexity, so, yes, we prefer the [aCountryElement].scrollIntoView(); call approach, at those pivotal times. This accounts for the left hand side of the webpage agreeing to the right hand side’s vertical scroll position. But what about the other way around? There, we started applying a CSS padding-top property to relevant right hand side elements (via DOM [element].style.paddingTop=[pixelsToExtendDown]px;), at pivotal points in the programming flow.
And on double clicking a right hand side button to start creating those background Geo Chart SVG based “images” we turn on a progress cursor, at least for non-mobile platforms, because the user needs patience here, in the changedregions_via_countries.htmlRegion Picker.
background-image:url(‘data:image/svg+xml;utf8, blahde blah ‘); nor background-image:url(‘data:image/svg+xml;base64, blahde blah ‘); ideas were not working for us … but today, we started to try …
overlay HTML div position:absolute; opacity:0.5; z-index:-4; …
We can’t remember a “foreground overlay” scenario so resembling a “background image feeling” end result, the transparent colour introduced into the Google ChartsGeo ChartSVG being crucial to help make this all work.
We want to be able to control the way a Google Charts Geo Chart can be nested within an HTML div element, for instance. We started the day wanting to be able to make …
a Google Charts Geo Chart be a background image to a div element … alas, on this first draft we couldn’t get there (but will continue with the research here) … whereas we succeeded …
adding the Google Charts Geo Chart interfacer’s resultant SVG data as the innerHTML (ie. content) …
<?php echo ”
function newbackin() {
if (dmyxhr.readyState == 4) {
if (dmyxhr.status == 200) {
if (dmyxhr.responseText) {
var m_t='image/jpeg';
var h_t='179';
var w_t='320';
var dbits = dmyxhr.responseText.split('\"height\": ');
if (dbits.length > 1) {
h_t=dbits[1].split(',')[0].split(String.fromCharCode(10))[0].split('}')[0].trim();
}
dbits = dmyxhr.responseText.split('\"mime_type\": \"');
if (dbits.length > 1) {
m_t=dbits[1].split('\"')[0];
}
dbits = dmyxhr.responseText.split('\"width\": ');
if (dbits.length > 1) {
w_t=dbits[1].split(',')[0].split(String.fromCharCode(10))[0].split('}')[0].trim();
}
dbits = dmyxhr.responseText.split('\"data\":');
dbits = dmyxhr.responseText.split('\"data\":');
if (dbits.length > 1) {
// replace all '_' with '/' and all '-' with '+' thanks to https://stackoverflow.com/questions/757675/website-screenshots
dgsbi='<img alt=\"Blog Posting Image\" style=\"width:' + w_t + 'px;height:' + h_t + 'px;\" width=' + w_t + ' height=' + h_t + ' src=\"data:' + m_t + ';base64,' + dbits[1].split('\"')[1].split('\"')[0].replace(/\_/g,'/').replace(/\-/g,'+') + '\"></img>';
//alert('dgsbi=' + dgsbi);
}
}
}
}
}
function ajaxit(urlin) {
if (urlin.length > 0) {
aurl=urlin;
if (window.XMLHttpRequest) {
dmyxhr = new window.XMLHttpRequest;
}
else {
try {
dmyxhr = new ActiveXObject('Msxml2.XMLHTTP');
} catch (othermicrosoft) {
try {
dmyxhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (failed) {
dmyxhr = false;
}
}
}
var xurl = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=' + encodeURIComponent(urlin) + '&screenshot=true';
if (dmyxhr) {
dmyxhr.onreadystatechange = newbackin;
dmyxhr.open('GET', xurl, true);
dmyxhr.send(null);
}
}
}
function wbtoa(instris) {
var outstris=instris;
while (outstris.indexOf(String.fromCharCode(10)) != -1) {
outstris=outstris.replace(String.fromCharCode(10),'');
}
var xzs=prompt(outstris, outstris);
return outstris.replace(/\\\"/g, \"'\");
}
In that Nearest Places form part of the TimeZone places webpage, we noticed that even when shaping to enter a TimeZone Placename in the first textbox we made no attempt to fill in …
latitude
longitude
… when we have the information to do so, and even if we’re misunderstanding a placename designation, that should not stop us from trying, because those two numerical fields above can be corrected, and the form resubmitted, in these scenarios.
Apart from making a PHP derived Javascript variable be made available to the code, we “wrap” …
GeoJson World Countries Drag and Drop Makeover Nuance Tutorial
Nuance alert! We’re not sure if you noticed, but if you tried out the Drag and Drop functionality in the World Countries web application of yesterday’s GeoJson World Countries Drag and Drop Makeover Tutorial you may have noticed …
for a country with lots of TimeZone places, like Brazil, you could get a decent Google Chart Geo Chart map up … but if you were to click the “Map?” link down the bottom of that iframe …
it would fail to show a Google Chart Map Chart for that country’s TimeZone places
This fix, believe it or not, is interesting, perhaps only in an “internal use only” sense, we grant you. But our solution got us delving even more into hashtagging data, so that the solution we came up with was a hybrid whereby …
stayed with PHP $_GET[] (ie. address bar ? and & argumented) data (versus using PHP $_POST[] methodologies) … but …
where it came to the &data=[most of the data] part, other than its first character, we hashtagged the rest
… so that the logic flows as per usual, but we intervene at places and flesh it out via location.hash (client side only) means. We won’t bore you too much with all the places of intervention except the receiving map.php’s “easiest to get” intervention …
In addition to the Wikipedia information, at the very least, presented following a successful drag and drop operation, from today, we also start presenting a new HTML iframe element containing …
Nearest TimeZone places along with Google Charts for each unique country involved
we wanted the first popup window content be aligned to the top and left … and then …
we thought it would be good to also, in “Drag and Drop land”, relevant countries nearby to the user’s drop point TimeZone Places be showing below that (and it panned out the best way to show this, for us, was via an iframe pointing at another incarnation of the tz_places.php webpage, because it could have GET arguments iso, iso2, iso3 etcetera to point at ISO 2 letter country codes, which we made more readily available (via a new data-ccglobal data attribute applied to the select option subelements presented) for the changed external Javascript countries.js we decided should get into the mix via a new Javascript function …
function tzagain(inhtml) {
var outhtml=inhtml, dccs=[], getarg='?', theone=1;
if (inhtml.indexOf('left:0px;') != -1 && inhtml.indexOf(' data-cc=') != -1) {
dccs=inhtml.split(' data-cc=');
for (var ii=1; ii<dccs.length; ii++) {
if (getarg == '?') {
getarg+='iso=' + dccs[ii].substring(0,4).replace(/\'/g,'').replace(/\"/g,'').substring(0,2);
theone++;
} else if (getarg.indexOf('=' + dccs[ii].substring(0,4).replace(/\'/g,'').replace(/\"/g,'').substring(0,2)) == -1) {
getarg+='&iso' + theone + '=' + dccs[ii].substring(0,4).replace(/\'/g,'').replace(/\"/g,'').substring(0,2);
theone++;
}
}
if (getarg != '?') {
if (inhtml.indexOf('</bo' + 'ody>') != -1) {
outhtml=inhtml.split('</bo' + 'dy>')[0] + '<iframe src="./tz_places.php' + getarg + '" style="position:absolute;left:0px;top:120px;width:100%;height:900px;"></iframe></body></html>';
} else {
outhtml=inhtml + '<iframe src="./tz_places.php' + getarg + '" style="position:absolute;left:0px;top:120px;width:100%;height:900px;"></iframe>';
}
}
}
return outhtml;
}
… that superfluous looking ?rand=blah measure being pretty useful really regarding getting around the cache keeping old external Javascript in its mind after changes.
Curiously, the grandparent regions.php starting off all this needed no changing! We hope you like these tweaks!
add similar drag and drop logic into our World Coastlines GeoJson web application … and along the way, also for the World Countries web application …
hold off involving the (pretty kludgy looking) vertical scrollbar of our drag and drop pin’s underlying HTML iframe …
<iframe scrolling=no frameborder=0 name=iftr id=iftr style=display:none; srcdoc="<body style=background-color:transparent;><p id=mg title='Wikipedia country page below via drag and drop to world map' draggable='true'>📍</p><br><br><div id=myh1></div><script type='text/javascript' src='./countries.js?rand=321156747657' defer></script></body>" data-src=></iframe>
… until the first drag operation starting, calls on …
parent.document.getElementById('iftr').scrolling='yes';
… proving a Javascript DOM control of the “scrolling” attribute works (as we weren’t sure, having never done this before)
It’s worth beavering away at a guinea pig web application until (just about complete) satisfaction (for now) before having a parallel set of code changes happening simultaneously, we’ve always found.
So, what happened in “external Javascript land”? No need for a “regions.js” here, as parent.document.URL can be scrutinised in that “external Javascript land” to discover which web application is the parent, and act accordingly. So changed were our changed external Javascript countries.js in …
our GeoJson World Countries web application Drag and Drop logic worked on an iPhone … but …
our GeoJson World Countries web application Drag and Drop logic did not work on an iPad
They’re both iOS! And usually the smaller iPhone has the problem and the larger iPad is okay when there is an odd scenario happening. So, what gives? Well, the odd thing is, it was just rearrangements of code and iframe srcdoc usage …
<iframe frameborder=0 name=iftr id=iftr style=display:none; srcdoc="<body style=background-color:transparent;><p id=mg title='Wikipedia country page below via drag and drop to world map' draggable='true'>📍</p><br><br><div id=myh1></div><script type='text/javascript' src='./countries.js?rand=321156747657' defer></script></body>" data-src=></iframe>
… that ended up helping us fix the issues. Figure this, on iPad our emoji pin could not be made visible down the bottom left of iPad screen but could be made to work in the title elements section?! Of course, we might have been having a bad day, but in our defence, even debugging in Safari via …
iPad Safari web browser invocation …
Apple white lead from iPad to MacBook Air …
MacBook Air Safari web browser Develop menu dropdown got us to debugging functionality
“long hover” (ie. on non-mobile, wait for a long while after the onmouseover event initiation to see whether the user is still hovering) … and today, a bit like that, is the new, for us …
“long drag” (the user waits a long time between the drag initialization and the drop event)
… and because we found “dawdling” on a drag and drop fairly unnatural, we think this “long drag” idea “has legs”, in that it works well as a deliberate act made by a user, knowing at the end they benefit from their actions. For us, with our GeoJSON Map web application, yesterday, with GeoJson World Drag and Drop Pin Tutorial, the drag and drop led to …
Wikipedia country information webpage … and today, we allow a “long drag” get you to …
Google Maps drop position information webpage … if the “long drag” is for 10 or more seconds …
Google Earth drop position information webpage … if the “very long drag” is for 20 or more seconds
onclick event logic … and today, we start to also include …
drag and drop event logic (like, but nuanced as explained below, the experimental drag and drop ideas included in the recent Planet Moon Game Tutorial) … the nuanced differences involving …
the drag part of the events occurs in an iframe (populated via small amount of srcdoc HTML and Javascript) able to reference its originator via window.parent …
drop part of the events occurs in that originator parent and so several Javascript function called by the child reside in the parent … and …
the child “drag” event controller uses the new external Javascript countries.js …
// countries.js
// July, 2023
// RJM Programming
// Help out countries.html and countries.php
var pos3=0, pos4=0, tdid='', poligono, punto, coone='', prectis;
// var poligono = [[2,9],[8,6],[12,10],[15,2],[10,4],[5,1]];
// var punto = [6, 5];
function pointInPolygon(polygon, point) { // thanks to https://community.appinventor.mit.edu/t/geofence-check-if-a-point-is-inside-a-polygon-javascript-map/57091
var odd = false;
for (var i = 0, j = polygon.length - 1; i < polygon.length; i++) {
if (((polygon[i][1] > point[1]) !== (polygon[j][1] > point[1]))
&& (point[0] < ((polygon[j][0] - polygon[i][0]) * (point[1] - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0]))) {
odd = !odd;
}
j = i;
}
return odd;
}
function andlaterstill() {
if (9 == 6) { // temporary
if (tdid != '') {
document.getElementById(tdid).innerHTML=document.getElementById(tdid).innerHTML.substring(0,1);
} else if (document.getElementById('mytable').innerHTML.indexOf(clonedatatwo) != '') {
document.getElementById('myh1').innerHTML=document.getElementById('myh1').innerHTML.split('</table>')[0] + '</table>';
}
if (document.getElementsByTagName('div')[0].innerHTML.indexOf(clonedatatwo) != -1) {
document.getElementsByTagName('div')[0].innerHTML=document.getElementsByTagName('div')[0].innerHTML.replace(clonedatatwo,'');
} else if (document.getElementsByTagName('div')[0].innerHTML.indexOf(clonedatatwo.replace('dragging','')) != -1) {
document.getElementsByTagName('div')[0].innerHTML=document.getElementsByTagName('div')[0].innerHTML.replace(clonedatatwo.replace('dragging',''),'');
} else if (document.body.innerHTML.split('<table')[0].indexOf(clonedatatwo.replace('dragging','')) != -1) {
document.body.innerHTML=document.body.innerHTML.replace(document.body.innerHTML.split('<table')[0], document.body.innerHTML.split('<table')[0].replace(clonedatatwo.replace('dragging',''),''));
} else if (document.body.innerHTML.split('<table')[0].indexOf(clonedatatwo) != -1) {
document.body.innerHTML=document.body.innerHTML.replace(document.body.innerHTML.split('<table')[0], document.body.innerHTML.split('<table')[0].replace(clonedatatwo,''));
}
}
tdid='';
}
function getprectis() {
if (window.opener) {
if (window.opener.document.getElementsByTagName('body')[0]) {
return window.opener.document.body.getBoundingClientRect();
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
return parent.document.body.getBoundingClientRect();
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
return parent.document.body.getBoundingClientRect();
}
}
return null;
}
function wod(ididea) {
if (window.opener) {
if (window.opener.document.getElementsByTagName(ididea)[0]) {
return window.opener.document.getElementsByTagName(ididea)[0];
} else if (window.parent) {
if (parent.document.getElementsByTagName(ididea)[0]) {
return parent.document.getElementsByTagName(ididea)[0];
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName(ididea)[0]) {
return parent.document.getElementsByTagName(ididea)[0];
}
}
return null;
}
function ccit() {
var divs, esot=[], bodyois=null;
if (window.opener) {
if (window.opener.document.getElementsByTagName('body')[0]) {
bodyois=window.opener.document.getElementsByTagName('body')[0];
divs=window.opener.document.getElementsByTagName('div');
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
bodyois=parent.document.getElementsByTagName('body')[0];
divs=parent.document.getElementsByTagName('div');
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
bodyois=parent.document.getElementsByTagName('body')[0];
divs=parent.document.getElementsByTagName('div');
}
}
function andqlater() {
//alert('HeRe');
tdid='';
var ppig='[]', coo='', coos=[], ip=0;
var squares; //=window.opener.document.getElementsByTagName('area');
if (window.opener) {
if (window.opener.document.getElementsByTagName('body')[0]) {
squares=window.opener.document.getElementsByTagName('area');
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
squares=parent.document.getElementsByTagName('area');
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
squares=parent.document.getElementsByTagName('area');
}
}
window.addEventListener("DOMContentLoaded", () => {
const source = document.querySelector("#mg");
console.log('source.id=' + source.id);
source.addEventListener("dragstart", (ev) => {
console.log("dragStart");
// Change the source element's background color
// to show that drag has started
ev.currentTarget.classList.add("dragging");
// Clear the drag data cache (for all formats/types)
ev.dataTransfer.clearData();
// Set the drag's format and data.
// Use the event target's id for the data
ev.dataTransfer.setData("text/plain", ev.target.id);
//ev.dataTransfer.setData("text/html", ev.target.outerHTML);
});
source.addEventListener("dragend", (ev) =>
ev.target.classList.remove("dragging")
);
const target = wod('body'); //window.opener.document.getElementsByTagName('body')[0];
target.id='usemap';
console.log('target.id=' + target.id);
target.addEventListener("dragover", (ev) => {
console.log("dragOver");
ev.preventDefault();
});
target.addEventListener("drop", (ev) => {
console.log("Drop");
ev.preventDefault();
// Get the data, which is the id of the source element
const data = ev.dataTransfer.getData("text");
const source = document.getElementById(data);
… where heap memory concerns related to the global variables memory used in our GeoJson World Coastlines webpage could cause mobile platform usage reloads of the web application, reminiscent of the external Javascript concerns we had back at GeoJson World Countries SVG Overlay Safari Error Tutorial.
There, as for here, mobile usage got better by swapping global variable usage for HTML content static PHP …
GeoJson World Coastline Function Noun Naming Tutorial
We’re working on an extension to yesterday’s GeoJson World Coastline Rivers Quiz Tutorial‘s Rivers Quiz functionality within our GeoJson World Coastlines web application, and have …
settled on an approach … but …
not yet finished on deployment issues
… but it is this approach we wanted to talk about today.
Our approach borrows from Object Oriented Programming (OOP) the idea that …
just as with OOP thinking class names are like nouns and the methods within that class are like verbs … we, with our approach …
help readability of our non-OOP functional code by including those nouns and verbs, as well as ideas like use of plurals to indicate array involvement, with our Javascript function naming
… we can best illustrate to you via showing you new functions and variables and modified code to show you this approach in code …
var rivers='', arivers=[], iguess=-1, isofar=' ', jscore=0, jgoes=0, elema=null, contexta=null, rectisleft=0, rectistop=0, isokto=true;
var populations='', apopulations=[], jguess=-1, jsofar=' ', both=false, jlastn='';
var idone=false;
function askapopulation() {
var another=false;
var origboth=both;
var midbit='';
var thing='population';
if (!both) { midbit='Append spaces to also answer a question regarding the Rivers Quiz, or R to just do Rivers Quiz.'; } else { thing='river'; }
var retthis=prompt('What is the name of this new red population area plotted on the world map? ' + midbit + ' Enter ? to get given more time looking at (longitude,latitude) = (' + apopulations[jguess].split(':')[1].split(',')[0] + ',' + apopulations[jguess].split(':')[1].split(',')[1] + ')', '');
if (retthis == null) {
both=false;
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (retthis.toLowerCase().trim() == 'r') {
both=false;
isokto=true;
getariver();
return '';
} else if (retthis.trim() == '?') {
if (retthis.trim() != retthis && !origboth) { both=true; }
setTimeout(askapopulation, 9000);
return '';
} else if (retthis.trim() == '') {
if (retthis != '' && !origboth) { thing='river'; }
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
if (retthis != '' && !origboth) { isokto=true; both=true; getariver(); }
} else if (jlastn.toLowerCase().indexOf(retthis.toLowerCase()) != -1 && jlastn.toLowerCase() == retthis.toLowerCase() && retthis.trim().length >= 1) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
jscore++;
another=confirm('Will pay that. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (jlastn.toLowerCase().indexOf(retthis.toLowerCase()) == -1) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (jlastn.toLowerCase() == retthis.toLowerCase()) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
jscore++;
another=confirm('Well done! Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (retthis.trim().length >= 1) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
jscore++;
another=confirm('Will pay that. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
}
if (both) { contexta.clearRect(0,0,360,180); }
if (both && !origboth) { isitok=true; getariver(); return ''; }
if (another) { if (both) { getariver(); getapopulation(); } else { getapopulation(); } } else { contexta.clearRect(0,0,360,180); }
return '';
}
function plotapopulation(which) {
if (isokto) { contexta.clearRect(0,0,360,180); }
//if (both) { isokto=true; }
jlastn=apopulations[which].split(':')[0];
var rest=apopulations[which].split(':')[1];
var restlonglat=[]; //rest.split(',');
restlonglat=rest.split(',');
if (eval('' + restlonglat.length) >= 2) {
contexta.fillStyle = 'red';
contexta.fillRect(eval(180.0 + eval('' + restlonglat[0])), eval(90.0 - eval('' + restlonglat[1])),1,1);
contexta.fill();
}
}
It’s time to turn our attention away from GeoJson World Countries, as talked about with yesterday’s GeoJson World Countries Plotted Ports Tutorial, and back to GeoJson World Coastline ideas. Why? We want to add a …
Rivers Quiz
… via the (generously provided) HTTP://geojson.xyz rivers lake centerlines GeoJSON data we download and then uploaded to become rivers.geojson data file. Now we were wondering out of …
use the URL to this GeoJSON file as the “src” attribute of an HTML iframe …
<iframe id=ifrivers onload=getthejson(this); style=display:none; src=./rivers.geojson></iframe>
… element (and then access the content via the onload event …
var rivers='', arivers=[], iguess=-1, isofar=' ', jscore=0, jgoes=0, elema=null, contexta=null, rectisleft=0, rectistop=0;
function getthejson(iois) {
var aconto = (iois.contentWindow || iois.contentDocument);
if (aconto != null) {
if (aconto.document) { aconto = aconto.document; }
if (aconto.body != null) {
rivers='' + aconto.body.innerHTML;
setTimeout(populaterivers, 500);
}
}
}
… function) would suffice, or if we would end up using …
Ajax call
… to access this data, and were a bit surprised the former method was all fine. Of course there are snazzy inbuilt Javascript hierarchical calls you can make to process the data, but we find, with GeoJSON data, in the client realm (where we’re keen to stay with today’s work (though PHP serverside can, of course, be purloined to do all this work, should you have that available)), of Javascript, we just need very basic string functions …
The progress with GeoJson World Countries helped too. We knew to add another HTML canvas layer as per …
document.body (now with the new onmousemove=airportplot(event); event logic) lowest level …
overlayed by HTML canvas element plotted with world country linework … now including …
overlayed by HTML canvas element dedicated to nearest airport plotting …
<canvas id=myacanvas height='180' width='360' style='background-color:transparent;z-index:55;display:inline-block;position:absolute;top:0px;left:0px;'></canvas>
overlayed by HTML img (transparent image) element and its associated image map area elements … and today we add into the mix …
HTML div hosting SVG elements overlaying initialized with “land” parts green infilled SVG at a mid range z-index (only as well as when called upon) individual GeoJson entities overlay
… and to, at document.body onload logic …
// ... and extended document.body onload event logic has added, up near its top ...
elema = document.getElementById('myacanvas');
contexta = elema.getContext('2d');
… and supplement with another HTML sub “emoji button” ❓ ( ❓ ) type element …
function askariver() {
var another=false;
var retthis=prompt('What is the name of this new blue river plotted on the world map? Enter ? to get given more time looking at (longitude,latitude) = (' + arivers[iguess].split(':')[1].split(',')[0] + ',' + arivers[iguess].split(':')[1].split(',')[1] + ')', '');
if (retthis == null) {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (retthis.trim() == '?') {
setTimeout(askariver, 8000);
return '';
} else if (retthis.trim() == '') {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (lastn.toLowerCase().indexOf(retthis.toLowerCase()) == -1) {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (lastn.toLowerCase() == retthis.toLowerCase()) {
jgoes++;
jscore++;
another=confirm('Well done! Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (retthis.trim().length >= 1) {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else {
jgoes++;
jscore++;
another=confirm('Will pay that. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
}
if (another) { getariver(); } else { contexta.clearRect(0,0,360,180); }
return '';
}
… to work the Rivers Quiz. Finally, though, for all good practicalities we also need those zoom logics out of GeoJson World Countries logic, via “emoji button” 🔎 ( 🔎 ) …
where to modularise … we think “data collection” commonality is a good reason, and so we make these changes to intair.php
making an (“animated emoji”) button dual purpose on top of originally being a single purpose button …
<sub title='Show Nearby Airports' onclick='doair=how(true,this); twothousand*=2; this.title=this.title.substring(0,4) + String.fromCharCode(105) + String.fromCharCode(110) + String.fromCharCode(103) + this.title.replace(this.title.split(String.fromCharCode(32))[0] + String.fromCharCode(32), String.fromCharCode(32));' data-type=9992 style=cursor:pointer; id=portsub>✈</sub>
… working with the intairsuffix global variable that could add a new GET argument where both the “port” label in &port=[value] and that [value] can affect behaviour from the intair.php PHP helper tool above …
var intairsuffix='', zhra=null, zhrb=null, kklat=0, kklong=0, doair=false, vsll=[-999.0], answered=true;
function how(atr, isub) {
var curgd=isub.getAttribute('data-type');
if (('' + curgd) == '9992') { // airport
if (intairsuffix != '') {
intairsuffix='&port=air';
isub.title='Showing Nearby Airports and Ports';
document.getElementById('title').value='Nearby Timezone Places and Airports and Ports';
}
} else if (('' + curgd) == '128674') { // port
if (intairsuffix == '') {
if (doair) {
intairsuffix='&port=air';
isub.title='Showing Nearby Airports and Ports';
document.getElementById('title').value='Nearby Timezone Places and Airports and Ports';
} else {
intairsuffix='&port=y';
isub.title='Showing Nearby Ports';
document.getElementById('title').value='Nearby Timezone Places and Ports';
}
}
}
return true;
}
function feedhow() {
var isub=document.getElementById('portsub');
var curgd=isub.getAttribute('data-type');
if (('' + curgd) == '9992') { // airport
isub.innerHTML='🚢';
isub.setAttribute('data-type', '128674');
} else if (('' + curgd) == '128674') { // port
isub.innerHTML='✈';
isub.setAttribute('data-type', '9992');
}
}
Ajax asynchronous usage for second half of a synchronous previous usage …
var intairsuffix='', zhra=null, zhrb=null, kklat=0, kklong=0, doair=false, vsll=[-999.0], answered=true;
function stateChangedb() {
if (zhrb.readyState == 4) {
if (zhrb.status == 200) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
var onepixelequals=izoom;
var bts=zhrb.response.split('.src + ' + String.fromCharCode(39));
if (eval('' + bts.length) > 1) {
for (var ijh=1; ijh<bts.length; ijh++) {
var vs=eval(eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))) +
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top))));
if (!inarray(vs,vsll)) {
vsll.push(vs);
drawaac(
eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))),
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top)))
);
}
}
}
}
}
}
function stateChangeda() {
if (zhra.readyState == 4) {
if (zhra.status == 200) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
var onepixelequals=izoom;
var bts=zhra.response.split('.src + ' + String.fromCharCode(39));
if (eval('' + bts.length) > 1) {
for (var ijh=1; ijh<bts.length; ijh++) {
var vs=eval(eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))) +
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top))));
if (!inarray(vs,vsll)) {
vsll.push(vs);
drawaac(
eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))),
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top)))
);
}
}
}
if (intairsuffix.indexOf('&port=air') != -1) {
zhrb = new XMLHttpRequest();
zhrb.onreadystatechange=stateChangedb;
zhrb.open('get', '/HTMLCSS/intair.php?num=6&lat=' + kklat + '&long=' + kklong + '&port=y', true);
zhrb.send(null);
}
answered=true;
}
}
}
… keeps a fastish synchronous call (that we enforce via that answered global variable) but truely invokes an asynchronous arrangement extracting Nearby Ports data to plot, as applicable
Introducing the Map Chart recognition of nearby Airports with yesterday’s GeoJson World Countries Nearest Airports Tutorial‘s progress on our latest GeoJson World Countries PHP web application, it set us to seeing …
the combination of Google Directions‘s talents allowing you to reposition on the fly … and …
the onmousemove event, at least for our non-mobile users
… could mean that if we pre-plot airports on the world map, given that the user has clicked the ✈ ( ✈ ) “Show an Interest in Airports” emoji button, as a non-mobile user hovers over the world map, this pre-plotting might help trip planners with their travel options, should air travel be part of their interest, in the same way it is an option up at Google Directions in our changedcountries.phpweb application you can also try below. The overlay scenario now reads …
document.body (now with the new onmousemove=airportplot(event); event logic) lowest level …
overlayed by HTML canvas element plotted with world country linework … now including …
overlayed by HTML canvas element dedicated to nearest airport plotting …
<canvas id=myacanvas height='180' width='360' style='background-color:transparent;z-index:55;display:inline-block;position:absolute;top:0px;left:0px;'></canvas>
overlayed by HTML img (transparent image) element and its associated image map area elements … and today we add into the mix …
HTML div hosting SVG elements overlaying initialized with “land” parts green infilled SVG at a mid range z-index (only as well as when called upon) individual GeoJson entities overlay
… worked by new (sometimes Ajax) Javascript code …
function inarray(needle, haystack) { // thanks to https://stackoverflow.com/questions/784012/javascript-equivalent-of-phps-in-array
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle) return true;
}
return false;
}
function stateChangeda() {
if (zhra.readyState == 4) {
if (zhra.status == 200) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
var onepixelequals=izoom;
var bts=zhra.response.split('.src + ' + String.fromCharCode(39));
if (eval('' + bts.length) > 1) {
for (var ijh=1; ijh<bts.length; ijh++) {
var vs=eval(eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))) +
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top))));
if (!inarray(vs,vsll)) {
vsll.push(vs);
drawaac(
eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))),
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top)))
);
}
}
}
answered=true;
}
}
}
function naira(klat, klong) {
if (answered && doair) {
answered=false;
zhra = new XMLHttpRequest();
zhra.onreadystatechange=stateChangeda;
zhra.open('get', '/HTMLCSS/intair.php?num=6&lat=' + klat + '&long=' + klong, true);
zhra.send(null);
}
}
function airportplot(e) {
if (answered) {
var rectis=null; //document.body.getBoundingClientRect();
var blat=0, blong=0;
var topllong=-180.0;
var topllat=90.0;
onepixelequals=eval(0.0 + eval(1.0 * izoom));
e = e || window.event;
e.preventDefault();
if (e.touches) {
if (e.touches[0].pageX) {
naira(eval(-rectisleft + e.touches[0].pageX), eval(-rectistop + e.touches[0].pageY)); //if (drawac(eval(-rectisleft + e.touches[0].pageX), eval(-rectistop + e.touches[0].pageY))) e = e; }
} else {
rectis=document.body.getBoundingClientRect();
naira(eval(-rectis.left + e.touches[0].clientX), eval(-rectis.top + e.touches[0].clientY)); //if (drawac(eval(-rectis.left + e.touches[0].clientX), eval(-rectis.top + e.touches[0].clientY))) { e = e; }
}
} else if (e.pageX || e.pageY) {
blat=eval(eval(eval(topllat * onepixelequals - eval(-rectistop + e.pageY) * 1)) / onepixelequals);
blong=eval(eval(eval(topllong * onepixelequals + eval(-rectisleft + e.pageX) * 1)) / onepixelequals);
if ((blat >= -90.0 && blat <= 90.0) && (blong >= -180.0 && blong <= 180.0)) {
naira(blat, blong); //if (drawac(eval(-rectisleft + e.pageX), eval(-rectistop + e.pageY))) { e = e; }
}
} else {
rectis=document.body.getBoundingClientRect();
naira(eval(-rectis.left + e.clientX), eval(-rectis.top + e.clientY)); //if (drawac(eval(-rectis.left + e.clientX), eval(-rectis.top + e.clientY))) { e = e; }
}
}
}
// ... and extended document.body onload event logic has added, up near its top ...
elema = document.getElementById('myacanvas');
contexta = elema.getContext('2d');
add interfacing functionality to the excellent Google Directions part of Google Maps, perhaps to help with Trip planning, or even just to associate a Placename with a latitude and longitude as clicked by the user, via the very simple URL arrangement … https://www.google.com/maps/dir/[decimalLatitudeDegrees]/[decimalLongitudeDegrees]
… helped out by new Javascript functions …
var lastlats=[], lastlongs=[], lastlat=-99.0, lastlong=-99.0, thislat=0.0, thislong=0.0;
function preface(inblurb) {
var extras='';
var outblurb=inblurb;
if (Math.abs(eval('' + lastlat)) > 0.0 || Math.abs(eval('' + lastlong)) > 0.0) {
if (Math.abs(eval('' + lastlat)) <= 90.0 && Math.abs(eval('' + lastlong)) <= 180.0) {
extras=' Add G for Google Directions between (' + lastlat + ',' + lastlong + ') to (' + thislat + ',' + thislong + ') and spaces (also more trip legs) to hashtag navigate to Google Charts later. ';
}
}
return extras + outblurb;
}
function alats(inlat) {
if (inlat == 0 && lastlats.length == 0) { inlat=inlat; } else { lastlats.push(inlat); }
return inlat;
}
Onto yesterday’s GeoJson World Countries TimeZone Times Tutorial GeoJson World Countries web application’s capabilities we want to add zooming, that doesn’t rely on web browser functionality (which continues to work). With that in mind we create a new emoji ( 🔎 ) 🔎 link, with this onclick event code …
var jzoom=1.0, izoom=location.search.split('zoom=')[1] ? eval(decodeURIComponent(location.search.split('zoom=')[1].split('&')[0])) : 1.0;
… to multiply the webpage zoom factor in a programmatical way. To acheive this, we have a two way approach (as you might have surmised from above) …
for mobile, the logic is easier by introducing a new meta name=viewport …
<meta id="myviewport" name="viewport" content="width=device-width, initial-scale=1, minimum-scale=0.1, maximum-scale=8, user-scalable=yes" >
… tag … while …
for non-mobile we needed to realize that event.pageX and event.pageY co-ordinates grow in proportion to the zoom factor, and that better latitude and longitude determining lines of code would go …
function canvasclick(e) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
onepixelequals=eval(0.0 + eval(1.0 * izoom));
//document.title='canvasclick';
e = e || window.event;
e.preventDefault();
if (e.touches) {
if (e.touches[0].pageX) {
//lastl='Longitude,Latitude coordinates are ' + eval(topllong + eval(-rectis.left + e.touches[0].pageX) * onepixelequals) + ',' + eval(topllat - eval(-rectis.top + e.touches[0].pageY) * onepixelequals);
if (drawc(eval(-rectisleft + e.touches[0].pageX), eval(-rectistop + e.touches[0].pageY))) {
thislat=eval(topllat - eval(-rectistop + e.touches[0].pageY) * onepixelequals);
thislong=eval(topllong + eval(-rectisleft + e.touches[0].pageX) * onepixelequals);
//console.log('rectistop=' + rectistop + ' and rectisleft=' + rectisleft + ' and rectisy=' + rectisy + ' and thislat=' + thislat);
document.getElementById('nearestif').src='/PHP/tz_places.php?place=&latitude=' + encodeURIComponent('' + eval(topllat - eval(-rectistop + e.touches[0].pageY) * onepixelequals)) + '&longitude=' + encodeURIComponent('' + eval(topllong + eval(-rectisleft + e.touches[0].pageX) * onepixelequals)) + '&ntztontz=y';
}
} else {
Some readers might be aware of our “theory regarding adverbs” and “web applications” on the net …
the most catered for adverb relates to the “where of life” … and the second banana is …
the “when of life”
… and, further to yesterday’s GeoJson World Countries SVG Overlay Safari Error Tutorial‘s emphasis on the “where of life”, today we add in a bit of the “when of life”, something right down the line of the remit of TimeZone talents.
Seriously though, a lot of us dream of the rest of the world on a world map, and wonder what time it is in other parts of the world. Phone call to relatives? A reminder SMS call? Email a game collaboration? It could all be part of life’s rich tapestry!
The expresion of this, for us, today, improving the communications with our current GeoJsom World Countries web application, take the form of emoji clocks from the 12 hour clock example forms such as …
1 o’clock is 🕐 🕐
2 o’clock is 🕑 🕑
12 o’clock is 🕛 🕛
2:30 is 🕝 🕝
11:30 is 🕦 🕦
12:30 is 🕧 🕧
… to show in “prompt” and “confirm” popup windows, as well as Map Chart maps … via new Javascript functions …
Also, in these same places we add in Time Place country ISO-2 character code based emoji flags, adding to information and colour pizazz in the informational parts to the workings of our changedcountries.phpweb application you can also try below.
On discovering our first solution theory of turning yesterday’s mapsvg.js external Javascript work into an async piece of work made no difference to this situation, we surmised that the huge amount of content held in the Javascript (ie. client side) global variable appendtoinnerHTML was causing memory issues. We couldn’t shift much to do with the overall amount of “data” needing to be handled, in order to implement country SVG colour infilling, but we could shift the data from being …
client side (external) Javascript held … to, instead, (have that data) be (determined on the) …
server side PHP filling in the contents of our (relevant) HTML div id=svgd ahead of the document.body onload event timing …
<?php
$icnt=0;
function apptohtmstuff($coordsare, $origc) {
global $icnt;
$minl=-1;
$mint=-1;
$maxl=-1;
$maxt=-1;
$zysare=explode(',', $coordsare);
$svgcis='';
for ($ij=0; $ij<sizeof($zysare); $ij+=2) {
if ($minl < 0) {
$minl=$zysare[$ij];
$maxl=$zysare[$ij];
$mint=$zysare[1 + $ij];
$maxt=$zysare[1 + $ij];
} else {
if ($zysare[$ij] < $minl) { $minl=$zysare[$ij]; }
if ($zysare[$ij] > $maxl) { $maxl=$zysare[$ij]; }
if ($zysare[1 + $ij] < $mint) { $mint=$zysare[1 + $ij]; }
if ($zysare[1 + $ij] > $maxt) { $maxt=$zysare[1 + $ij]; }
}
}
…everywhere … and an idea we’d ditched yesterday of …
idea to pre-colour “land” parts of the world GeoJson map green (ahead of the document.body onload event) also came good (after causing problems yesterday)
… meaning now, “overlay” wise, we could say …
document.body lowest level …
overlayed by HTML canvas element plotted with world country linework …
overlayed by HTML img (transparent image) element and its associated image map area elements … and today we add into the mix …
HTML div hosting SVG elements overlaying initialized with “land” parts green infilled SVG at a mid range z-index (only as well as when called upon) individual GeoJson entities overlay
… and we (reckon we’ve) improved the colour coding user experience at the same time.
We noticed that tweaks in the changed …
var lastflagged='', appendtoinnerHTML='', waitplease=false; // used to make sure "area" element onclick code precedes any document.body onmousedown or ontouchdown code
… also lessened the burden on the client side by only asking any Javascript DOM command operations act on single HTML element at a time, not a whole swathe of hosted ones, in any operation.
What deducible data item needs to be determined for these Geo Charts to work? We need a way to deduce ISO-2 character country codes from the ISO-3 character codes existing in the GeoJson “countries.geojson” data from yesterday’s work. We happened upon the extremely generous mapping data webpage to help with these ISO-2 character deductions …
… in our image map area elements PHP creation code above. As you can see, extra “intelligence”, moving forward, is contained in area element global data attributes.
Geo Chart can involve emoji (🏠 &127968;) or image (SVG) circle based symbology for the “User Clicked Place” and nearby TimeZone places respectively …
all these symbols can be clicked to open popup windows containing TimeZone Place Wikipedia webpages of relevance …
an emoji national flag (eg. Zambia “ZA” could be used to derive 🇿🇦 🇿🇦 flag emoji) derived from those ISO-2 character codes can supplement the GeoJson (more ISO-3 character based) names presented in the underlying data, in the Geo Chart title …
contextualizing the accompanying Map Chart … and …
vice versa regarding hovering over symbology (which works on Map Chart, but not Geo Chart) …
within the Map Chart iframe a “Geo” link can glean a “zoomed out” world Geo Chart view of your TimeZone places
Know your GeoJson! Yes, pretty obviously, any two GeoJson datasets might display the same in that “map plotting” sense, but one might have different and/or more “intelligence” than the other. Often, an XML has more “intelligence” than equivalent HTML (barring the use of global data attributes, that is), as today’s Corollacorollary.
Luckily for programmers all over, the organization of TimeZones has had an International flavour in its development and maintenance. As such, given the “purely coastline” GeoJson data involved in our fledgling PHP web application of yesterday’s GeoJson World Coastline Primer Tutorial a useful arrangement for improvement involves …
document.body onclick event co-ordinates … able to be converted to …
longitude, latitude (easily, only because of our simplistic map projection, of course) … onfed to …
… can have us helping out your curious web “clicking” user with the 3 nearest TimeZone places, as a reference as to where they are “clicking” in the world.
in a discrete click methodology of interest, you could adopt a non-mobile “onmousedown” logic set that does not get interfered with by a mobile “ontouchdown” logic set (perhaps leaving “onclick” event, which both non-mobile and mobile both recognise, for another event logic role) … and …
neither will interrupt the mobile gestures associated with swiping and pinching, which refer to the events “ontouchstart” and “ontouchend” at either end of their lifespan
And so, we arrive at a long planned for tilt at Image Map functionality that we often turn to Mobilefish.Com and its excellent Image Map Creation to help us out … but not today?! Why not? We have a funny set of needs, they being …
our Image Map’s image will have a variable set of width x height dimensions …
our Image Map’s image will be transparent
our Image Map needs to have a hole left aside inside it where the functionality that originally existed (and pointed to WordPress Blog content like you are reading), is still working
On this WordPress blog (now on AlmaLinux rather than CentOS) you are reading we have this permalink arrangement whereby URLs to blog postings have within them a representation of the blog posting title. We might be dreaming, but we think the arrangements for this “mapping of URLs” might have changed with the migration environment change. This would not be surprising. We think the way a “/” (forward slash) character that appears in a blog posting title might now “map” to a “-” (minus) character rather than to nothing that my CentOS dreams never forewarned me of, regarding … tut, tut!
To remedy this, we started fiddling around with good ol’ TwentyTen theme’s good ol’ headergood ol’.php code where we have many places where we simulate what must go on behind the scenes in WordPress.org based permalink code thinking. And then, we remembered twin good ol’ 404twin good ol’.php methodologies for URLs that are not found, and though many will see this as a klunky solution … god knows Luna and Nala find it pretty amusing … we kind of like …
And so, we arrive at performing the DNS changeover part to our CentOS to AlmaLinux migration journey, further to yesterday’s AlmaLinux DNS Changeover FileZilla sftp Tutorial progress towards this point.
We wanted to have in the blog posting title a changed word starting with “A” (and we chose “Activated”) because it is our rjmprogramming.com.au (Crazy Domains‘s) DNS Hosting‘s relevant A Record that is affected by our DNS Changeover today.
We, in this A Record updating, changed the CentOS IP Address 65.254.92.213 mentions to those of AlmaLinux 65.254.95.247 IP Address.
Not very onerous, but it takes a few hours to filter through to the world wide web! Even so, you may be reading this blog posting on AlmaLinux … yayyyyyy!!!!!
All this information will be blasé knowledge to many system operators out there, but a lot of us are not system operators, so we’ll outline what we see and find out here.
Regular readers will know we use and really like the great FileZilla product to use for the first of …
… group of access methodologies to our web server here at rjmprogramming.com.au domain. And, believe me, they are all used extensively around here, for many and various purposes.
We had ssh sorted pretty easily for the two scenarios, because it’s use only involved IP addresses, the two, for us, that are concerned, but with sftp, at least for us, we find three scenarios of concern show at the end of this posting part, the last of which we’ll show you the creation of a connection mechanism to in configuring FileZilla, with today’s animated GIF tutorial picture presentation, where no remembering of passwords was needed, and you’ll see us demonstrating …
FileZilla (top left icon) SiteManager -> Duplicate …
… and …
FileZilla SiteManager -> Rename …
… talents
! Huh?!
How so?!
Well, we’re glad you got that proxy to ask?! OpenSSH is used a lot, and for us …
… with web server access arrangements, and these passwords end up being the crux of access controlled by keychains and OpenSSH protected files which also get transferred, in all probability during a migration phase where web server contents is transferred from one IP address to the new web server IP addresses. For us, we relied on our web hoster, the great Crazy Domains to do this migration, and it all went so smoothly, thanks, but if you have those system operator skills you can do this yourself, if you decide to roll this way, or that way …
Anyway, we’re here today nearing the time for the actual DNS changeover, mulling over the question …
But what if we have forgotten something?!
We’re pretty sure there’ll be a bit of time where access back to the CentOS web server will be available to us, and we’d like an sftp access method for that purpose, corresponding to the last of the three FileZilla modes of connection below …
Ongoing sftp connection to whatever IP address web server corresponds to rjmprogramming.com.au
Before DNS changeover getting to proposed AlmaLinux web server
After DNS changeover getting back to CentOS web server (just in case)
amend wp-config.php to add in code statement … thanks to this great advice …
define('RELOCATE',true);
… meaning URLs such as https://[newIPaddressForRJMProgrammingIntoTheFuture]/ITblog just address data and software on [newIPaddressForRJMProgrammingIntoTheFuture] proposed new AlmaLinux9 web server (rather than ducking off to https://www.rjmprogramming.com.au/ITblog/ or https://[oldIPaddressForRJMProgrammingFromTheNearFuturePast]/ITblog/)
in WordPress admin section General Settings make sure both WordPress Address (URL) and Site Address (URL) get mapped to … https://[newIPaddressForRJMProgrammingIntoTheFuture]/ITblog
crontab and curl “MySql Watchdog” basis … we also, around here, use …
crontab and curl “Landing Page Daily Updates Regarding WordPress Blog Posting Content”
… so that going to the RJM Programming Landing Page can glean the latest WordPress Blog content.
During our “pre AlmaLinux” “pre DNS changeover” period, we’ve been doing two lots of WordPress Post “CMS style” textarea blog posting sessions for each daily new blog posting. We’ve got a WordPress Blog with permalinks set to a variant of the blog posting title, and between the two versions …
that part of a URL to get to this content remains the same (phew!) but the POST_ID becomes unreliable as a guaranteed thaing … the least worriesome aspect, against …
the Landing Page dropdowns for new, but soon to be the DNS IP address need to be populated via WordPress Blog MySql based data, via a tutorial_options.php piece of inhouse PHP which needs to change in a few ways …
references to what used to be “mysql_” style PHP calls now need to be transferred to equivalent “mysqli_” ones (and thanks to php – Replacement for deprecated function mysql_connect – Stack Overflow here, regarding great advice) where, as well as the i change, for all but …
$link = mysqli_connect($hostname, $username, $password);
mysqli_num_rows($res)
mysqli_fetch_row($res)
mysqli_close($link)
… references, for our PHP code, which used mysqli_select_db($link, $dbname) and mysqli_query($link,$qry) and mysqli_errno($link) … we needed that extra first argument of the mysqli connection value … changes that reminded us, a tad, of how to go from a CSS Selector to a Javascript DOM by getting rid of _ and just to the right of where that was, capitalize that character, thinking
rethink any $_GET[] or $_POST[] arrangements into $argc (and $argv[1] argument) based logic …
<?php
$index = "index";
if (isset($argc)) {
if ($argc >= 2) {
if ($argv[1] != "mobile") {
$index = $argv[1];
}
}
} else if (isset($_GET['index'])) {
$index = $_GET['index'];
} else if (isset($_POST['index'])) {
$index = $_POST['index'];
}
?>
… so that …
AlmaLinux
CentOS
cd ~rjmprogr/public_html/PHP; php tutorial_options.php
Yes, we’re migrating again (as we were talking about with Apache/PHP/MySql Web Hosting Website Migration ssh Tutorial), though as you read this blog posting, if hot off the press here on 19/7/2024, we’ll not have transferred the DNS over yet, which we’ll outline the reasons for into the future. But, today, we’re excited to outline some steps after …
… it was, mainly, regarding our MySql Watchdog ( korn shell scripting in the Linux Apache/PHP/MySql web server /etc/init.d scripts called via crontab ) that concerned us most. Why (Nala getting distracted, ever since MySql Down Thinking Followup Tutorial … or …)?
Well, understandably our Crazy Domains web hosts were kind enough to …
take on the migration … thanks … and not, just blithely …
make any “old scripting” assumptions ( ie. we came across the new web server’s /etc/init.d folder as empty (and /etc/rc.d/init.d folder, for your AlmaLinux Apache2 daemon process folder arrangements not empty, but missing our own tailored scripting (and that scripting and our crontabbing used /etc/init.d mentions) … so …) … especially any to do with anything even resembling …
crontab … nor, heaven forbid …
curl … (the use of which, up to now, we’ve only ever combined with argument URLs that mentioned rjmprogramming.com.au rather than any numerical IP address … hence, our concerns) … scripting being helped out by crontab … that had any personal tailoring ( ie. a crontab -l
# showed default AlamaLinux arrangements only
This can be very powerful stuff, and you could, during a period before the DNS changeover, if you had a matching crontab situation happening, having two watchdogs on two different IP addresses (only one of which is pointed to proper DNS rjmprogramming.com.au arrangements trying to pick up a MySql service, and though only one would get through picking up the true rjmprogramming.com.au MySql service, the other would, at the very least, be doing superfluous activity because of the way we scripted it. We scripted for …
one DNS arrangement for the one IP address related to rjmprogramming.com.au … rather than …
one DNS arrangement for the one IP address related to rjmprogramming.com.au and another IP address being readied for a future DNS rearrangement that it will map to … and after that …
one DNS arrangement where that new IP address can newly become the DNS for rjmprogramming.com.au and another obsolete (but still having a working crontab happening) IP address awaits a decommission
That is the power, and also the worry, regarding how curl and crontab can be such useful Linux web server tools!
For number 3 scenario, perhaps we can be quick decommissioning, but we imagine we’ll want to have another test period after the DNS changeover. We’ll see. Anyway, on the road towards solutions we’re pretty sure a first step is …
before thinking of starting up any “inhouse scripting componentry” crontab schedulings on the new IP address web server …
populate our empty /etc/init.d … with …
matching script content and permissions and ownership as is (and then, was) happening on the current (but soon to be decommissioned) IP address web server
This transfer of scripts is not suitable for our FileZilla sftp transferring arrangements, and we do not feel like tackling any big shake up of arrangements here.
But, we ended up with a zipping and unzipping methodology that went like …
pick a folder that is hidden to the public (for both IP addresses) but that your Linux administration user (in our case “root”) can get to and our FileZilla web server user (in our case “rjmprogr”) can plonk to and from, for us, that being (notice, regarding Apache, no “public_html” mention) … /home/rjmprogr
for current, but soon to be decommissioned IP address … ssh login … cd /etc/init.d … zip /home/rjmprogr/etcinitd.zip *
use relevant FileZilla on current, but soon to be decommissioned IP address setup to copy this back to your local operating system, ours being macOS …
use relevant FileZilla on new, but soon to be the DNS IP address setup to copy this local operating system etcinitd.zip over to /home/rjmprogr
for new, but soon to be the DNS IP address … ssh login … cd /etc/init.d … unzip /home/rjmprogr/etcinitd.zip *
if happy ( via … ls -l /etc/init.d/* … checking and comparing between IP addresses ), for current, but soon to be decommissioned IP address … ssh login … rm -f /home/rjmprogr/etcinitd.zip # or do this via appropriate FileZilla session
if happy ( via … ls -l /etc/init.d/* … checking and comparing between IP addresses ), for new, but soon to be the DNS IP address … ssh login … rm -f /home/rjmprogr/etcinitd.zip # or do this via appropriate FileZilla session
… that we were really happy with.
For a small number of script files, though, an animated GIF presentation we’ve provided (and don’t you just hate it when you only get the knack of it near the end of the job … sheeesh!) you might want to use …
open two macOS Terminal windows side by side (and not overlapping) …
left one has ssh login to current, but soon to be decommissioned IP address … cd /etc/init.d
right one has ssh login to new, but soon to be the DNS IP address … cd /etc/init.d
for each ( mainly *.*sh for us ) (korn shell usually for us) script of interest (we’ll call thesc.ksh below) …
# no return key press below …
left % cat thesc.ksh
# you might want to use Terminal app’s Edit -> Copy the highlighted “thesc.ksh” to help (via Terminal app’s Edit -> Paste) with …
right % vi thesc.ksh
at left, as necessary, press Return key
at left highlight from the bottom ( probably “exit” ) up to the top ( probably “#!/bin/ksh” ) and use Terminal app’s Edit -> Copy
at right, as necessary, press Return key
at right, if content already there, use appropriate <escape>999dd command to clear to nothing then …
at right, press “i” key (for Insert) …
at right, use Terminal app’s Edit -> Paste
at right, maybe press <escape>w (to have an interim look) ahead of …
at right, maybe press <escape>wq!
attend to any ownership (research chown and chgrp) or file permission (research chmod) mismatches you would tweak to via ls -l /etc/init.d/* … checking and comparing between IP addresses
and consider only leaving “inhouse scripting” in /etc/init.d on new, but soon to be the DNS IP address here, for now (and into the future rewrite scripting for /etc/rc.d/init.d reuse)
When we discussed Linux Watchdog Primer Tutorial in that very generic fashion below, we were being that … generic. Today we turn to specifics in that regard. On the rjmprogramming.com.au domain we use a …
(software) watchdog which checks for the health of the MySql Service, and if not healthy, restore it to health … which is all fine and good from the point of view of the domain rjmprogramming.com.au … but depending on what the user was doing we could …
code for intervention within the MySql using piece of software, and writing out the database error to the webpage, and present alternative navigation
… on the understanding with that latter thought, that we put into play today for a WordPress 4.1.1 blog, we realized we needed to intervene in …
… where the redirection to /slideshow.html effectively “Cuts to the Chase” for the gist of that blog posting you never got to, as MySql is currently down.
Notice how specific the actions can be when you write code “dependent” on another software component, as distinct from the “watchdog” approach we often want to be “independent” in its thinking.
Guess this begs the question? How did we work out where to intervene? We just got to folders on the rjmprogramming.com.au web server with the WordPress (Codex) software and went (showing you the one that yielded the nicest result for us) …
pwd // and we are at [DocumentRoot]/ITblog
cd wp-includes
fgrep 'Error establishing a database connection' *.php
Do you have a computer operational problem? What the … what is that humanoid on about? Well, is there a computer operation you have to do routinely, to fix an ongoing problem, that relies on your personal intervention that, one day, you’d like to not have to worry about, or better still … you usually intervene, but would like a backup approach should you get sick and can’t do it … here’s where you need Fido a watchdog
… am not recommending a Golden Retriever, unless you want your process licked rather than attended to? (had you forgotten this was a question, CedricLinux Nala)? …
oh, moi?)
“
Why is bellybutton fluff blue? But we digress, or at Buckingham Palace one digresses.
Right, back at watchdogs, there are schools of thought …
The process is down for too long and we need to do something about it, because customers are leaving
If you need a watchdog to save your bacon, then (clearly you’re not with it, because the dog’s eaten the bacon and) there is something else fundamentally wrong or something you do not understand, which is what you really should resolve, either way
My view is that, if the underlying process would take years to understand or if it is written in legacy code, I’d go more with the former idea, especially as there is delight in creating a really good watchdog (training one? not so easy) … it can be really hard to do … for this reason cannot give code here really, because there is no “out of the box” that is a responsible approach to advise … you have to study the issue and cut it into its components, unit test the solutions to the components of your watchdog solution, and retest with the interactions of those components. However, this is a coding enthusiast’s view, and is a bit short-sighted, perhaps. In any case, what will save the day is that this decision will probably be made for you by an operations expert, if you work in a large organization.
Some other watchdog considerations should be …
Is the attempt to automate the solution that the watchdog will provide technically possible … may not be?!
We can resolve it with personal intervention … can the watchdog simulate each step of the human intervention? If so, go for that approach if possible.
Be very careful of approaches that involve mouse clicks, as they are quite often relative to too many other environmental issues … try to restrict the watchdog solution to command line/scripting/keyboard ideas … on Windows, AutoHotKey is an excellent recording program of interest (would recommend just using it for keyboard recordings, if using it for a watchdog … by the way, tomorrow (tomorrow arrived today) we do a tutorial showing you how to create an AutoHotKey terminate-and-stay-resident program on Windows).
Have we identified the real intervention points? If not, you might succeed some of the time, but not all the time, and you may cause damage on those times when you have made some assumptions, with your incomplete understanding.
Here is an example. You have an overnight batch process run, and it falls over at a certain point, and you get paged at 3 or 4 (it’s bound to be AM). It has been tentatively decided you might want to create a watchdog … what are some considerations …
What do log files tell me? Find out.
Is it a single thing that is missing that would resolve the problem once and for all? If yes, well, you know not to deviate from this one thing … ignore ideas below.
Of the few problems, is it worth proceeding with the watchdog idea, because the number of separate issues can often cause a factor of ten more complication issue points, and maybe you should stick with human intervention.
Break the watchdog problem into these problem issues as a separate unit-testable piece of scripting code (or whatever your watchdog solution entails) … test each for success … retest for their interaction with each other (ie. that they don’t interfere with each other).
The title of this tutorial mentions Linux but generic thinking like above covers other operating system thought patterns, but there are some Linux (or Unix) tools that are great Linux commands that we should point out … thanks to Hscripts.com and CyberCiti.biz for this …
crontab ( eg. */5 * * * * Username /path/to/command # where /path/to/command gets run by Username every five minutes … arranged via crobtab -e ) … for Windows, equivalent would be Task Schedular in Windows Primer Tutorial
And here are some of the practicalities of a watchdog …
Where does it run? If at more than one place, consider each place separately. If it runs on more than one computer, then clearly this is important. Does the directory and file permissions allow the watchdog to run, but do not allow other users to misuse it? (Please say yes here.) A generic thing about crontab or nohup (or Windows start) scripting arrangements are that you should not assume the environments of these processes is the same as your current running command line process … you should write as if you have just logged on and have done nothing … so just about the first decision of the script is to “cd” itself to the proper place where it was designed to run.
Which user(s) (on whichever computer(s)) can run it?
When does it run? If the solution is uncomplicated enough, maybe you can use a pre-emptive approach. For example, you know the problem is to do with a file missing when a non-critical process fails but later on that file is looked for, then why not pre-emptively get the watchdog to create that file (with default data) ahead of the process run crash point time.
As part of the question above, does one subprocess need to end before another starts? If yes, you need to intervene in such a way that that process architecture remains, and you need to work out an independent way for your independent watchdog to step in, at the correct time, and take over the same task, as required. But if it gets to this, don’t you understand the underlying process well enough to have a crack at doing the “real” solution (for all time)? Have a think, now, and keep checking in on the issue?
You need to log the workings of the watchdog both for information and for further research which might help in achieving a “real” solution (without the watchdog) further down the track.
So why was this posting called a tutorial? Well, there’s some homework. You see there are these Daleks, and we sort of need to know when they’re going to invade Earth again, and Dr Who is not always available, so, was wondering, if it wouldn’t be too inconvenient … if you wouldn’t mind writing that watchdog to detect a Dalek invasion and shoo them off … 6 hours … okay?
“
Woofsky!
“
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
All this information will be blasé knowledge to many system operators out there, but a lot of us are not system operators, so we’ll outline what we see and find out here.
Regular readers will know we use and really like the great FileZilla product to use for the first of …
… group of access methodologies to our web server here at rjmprogramming.com.au domain. And, believe me, they are all used extensively around here, for many and various purposes.
We had ssh sorted pretty easily for the two scenarios, because it’s use only involved IP addresses, the two, for us, that are concerned, but with sftp, at least for us, we find three scenarios of concern show at the end of this posting part, the last of which we’ll show you the creation of a connection mechanism to in configuring FileZilla, with today’s animated GIF tutorial picture presentation, where no remembering of passwords was needed, and you’ll see us demonstrating …
FileZilla (top left icon) SiteManager -> Duplicate …
… and …
FileZilla SiteManager -> Rename …
… talents
! Huh?!
How so?!
Well, we’re glad you got that proxy to ask?! OpenSSH is used a lot, and for us …
… with web server access arrangements, and these passwords end up being the crux of access controlled by keychains and OpenSSH protected files which also get transferred, in all probability during a migration phase where web server contents is transferred from one IP address to the new web server IP addresses. For us, we relied on our web hoster, the great Crazy Domains to do this migration, and it all went so smoothly, thanks, but if you have those system operator skills you can do this yourself, if you decide to roll this way, or that way …
Anyway, we’re here today nearing the time for the actual DNS changeover, mulling over the question …
But what if we have forgotten something?!
We’re pretty sure there’ll be a bit of time where access back to the CentOS web server will be available to us, and we’d like an sftp access method for that purpose, corresponding to the last of the three FileZilla modes of connection below …
Ongoing sftp connection to whatever IP address web server corresponds to rjmprogramming.com.au
Before DNS changeover getting to proposed AlmaLinux web server
After DNS changeover getting back to CentOS web server (just in case)
amend wp-config.php to add in code statement … thanks to this great advice …
define('RELOCATE',true);
… meaning URLs such as https://[newIPaddressForRJMProgrammingIntoTheFuture]/ITblog just address data and software on [newIPaddressForRJMProgrammingIntoTheFuture] proposed new AlmaLinux9 web server (rather than ducking off to https://www.rjmprogramming.com.au/ITblog/ or https://[oldIPaddressForRJMProgrammingFromTheNearFuturePast]/ITblog/)
in WordPress admin section General Settings make sure both WordPress Address (URL) and Site Address (URL) get mapped to … https://[newIPaddressForRJMProgrammingIntoTheFuture]/ITblog
crontab and curl “MySql Watchdog” basis … we also, around here, use …
crontab and curl “Landing Page Daily Updates Regarding WordPress Blog Posting Content”
… so that going to the RJM Programming Landing Page can glean the latest WordPress Blog content.
During our “pre AlmaLinux” “pre DNS changeover” period, we’ve been doing two lots of WordPress Post “CMS style” textarea blog posting sessions for each daily new blog posting. We’ve got a WordPress Blog with permalinks set to a variant of the blog posting title, and between the two versions …
that part of a URL to get to this content remains the same (phew!) but the POST_ID becomes unreliable as a guaranteed thaing … the least worriesome aspect, against …
the Landing Page dropdowns for new, but soon to be the DNS IP address need to be populated via WordPress Blog MySql based data, via a tutorial_options.php piece of inhouse PHP which needs to change in a few ways …
references to what used to be “mysql_” style PHP calls now need to be transferred to equivalent “mysqli_” ones (and thanks to php – Replacement for deprecated function mysql_connect – Stack Overflow here, regarding great advice) where, as well as the i change, for all but …
$link = mysqli_connect($hostname, $username, $password);
mysqli_num_rows($res)
mysqli_fetch_row($res)
mysqli_close($link)
… references, for our PHP code, which used mysqli_select_db($link, $dbname) and mysqli_query($link,$qry) and mysqli_errno($link) … we needed that extra first argument of the mysqli connection value … changes that reminded us, a tad, of how to go from a CSS Selector to a Javascript DOM by getting rid of _ and just to the right of where that was, capitalize that character, thinking
rethink any $_GET[] or $_POST[] arrangements into $argc (and $argv[1] argument) based logic …
<?php
$index = "index";
if (isset($argc)) {
if ($argc >= 2) {
if ($argv[1] != "mobile") {
$index = $argv[1];
}
}
} else if (isset($_GET['index'])) {
$index = $_GET['index'];
} else if (isset($_POST['index'])) {
$index = $_POST['index'];
}
?>
… so that …
AlmaLinux
CentOS
cd ~rjmprogr/public_html/PHP; php tutorial_options.php
Yes, we’re migrating again (as we were talking about with Apache/PHP/MySql Web Hosting Website Migration ssh Tutorial), though as you read this blog posting, if hot off the press here on 19/7/2024, we’ll not have transferred the DNS over yet, which we’ll outline the reasons for into the future. But, today, we’re excited to outline some steps after …
… it was, mainly, regarding our MySql Watchdog ( korn shell scripting in the Linux Apache/PHP/MySql web server /etc/init.d scripts called via crontab ) that concerned us most. Why (Nala getting distracted, ever since MySql Down Thinking Followup Tutorial … or …)?
Well, understandably our Crazy Domains web hosts were kind enough to …
take on the migration … thanks … and not, just blithely …
make any “old scripting” assumptions ( ie. we came across the new web server’s /etc/init.d folder as empty (and /etc/rc.d/init.d folder, for your AlmaLinux Apache2 daemon process folder arrangements not empty, but missing our own tailored scripting (and that scripting and our crontabbing used /etc/init.d mentions) … so …) … especially any to do with anything even resembling …
crontab … nor, heaven forbid …
curl … (the use of which, up to now, we’ve only ever combined with argument URLs that mentioned rjmprogramming.com.au rather than any numerical IP address … hence, our concerns) … scripting being helped out by crontab … that had any personal tailoring ( ie. a crontab -l
# showed default AlamaLinux arrangements only
This can be very powerful stuff, and you could, during a period before the DNS changeover, if you had a matching crontab situation happening, having two watchdogs on two different IP addresses (only one of which is pointed to proper DNS rjmprogramming.com.au arrangements trying to pick up a MySql service, and though only one would get through picking up the true rjmprogramming.com.au MySql service, the other would, at the very least, be doing superfluous activity because of the way we scripted it. We scripted for …
one DNS arrangement for the one IP address related to rjmprogramming.com.au … rather than …
one DNS arrangement for the one IP address related to rjmprogramming.com.au and another IP address being readied for a future DNS rearrangement that it will map to … and after that …
one DNS arrangement where that new IP address can newly become the DNS for rjmprogramming.com.au and another obsolete (but still having a working crontab happening) IP address awaits a decommission
That is the power, and also the worry, regarding how curl and crontab can be such useful Linux web server tools!
For number 3 scenario, perhaps we can be quick decommissioning, but we imagine we’ll want to have another test period after the DNS changeover. We’ll see. Anyway, on the road towards solutions we’re pretty sure a first step is …
before thinking of starting up any “inhouse scripting componentry” crontab schedulings on the new IP address web server …
populate our empty /etc/init.d … with …
matching script content and permissions and ownership as is (and then, was) happening on the current (but soon to be decommissioned) IP address web server
This transfer of scripts is not suitable for our FileZilla sftp transferring arrangements, and we do not feel like tackling any big shake up of arrangements here.
But, we ended up with a zipping and unzipping methodology that went like …
pick a folder that is hidden to the public (for both IP addresses) but that your Linux administration user (in our case “root”) can get to and our FileZilla web server user (in our case “rjmprogr”) can plonk to and from, for us, that being (notice, regarding Apache, no “public_html” mention) … /home/rjmprogr
for current, but soon to be decommissioned IP address … ssh login … cd /etc/init.d … zip /home/rjmprogr/etcinitd.zip *
use relevant FileZilla on current, but soon to be decommissioned IP address setup to copy this back to your local operating system, ours being macOS …
use relevant FileZilla on new, but soon to be the DNS IP address setup to copy this local operating system etcinitd.zip over to /home/rjmprogr
for new, but soon to be the DNS IP address … ssh login … cd /etc/init.d … unzip /home/rjmprogr/etcinitd.zip *
if happy ( via … ls -l /etc/init.d/* … checking and comparing between IP addresses ), for current, but soon to be decommissioned IP address … ssh login … rm -f /home/rjmprogr/etcinitd.zip # or do this via appropriate FileZilla session
if happy ( via … ls -l /etc/init.d/* … checking and comparing between IP addresses ), for new, but soon to be the DNS IP address … ssh login … rm -f /home/rjmprogr/etcinitd.zip # or do this via appropriate FileZilla session
… that we were really happy with.
For a small number of script files, though, an animated GIF presentation we’ve provided (and don’t you just hate it when you only get the knack of it near the end of the job … sheeesh!) you might want to use …
open two macOS Terminal windows side by side (and not overlapping) …
left one has ssh login to current, but soon to be decommissioned IP address … cd /etc/init.d
right one has ssh login to new, but soon to be the DNS IP address … cd /etc/init.d
for each ( mainly *.*sh for us ) (korn shell usually for us) script of interest (we’ll call thesc.ksh below) …
# no return key press below …
left % cat thesc.ksh
# you might want to use Terminal app’s Edit -> Copy the highlighted “thesc.ksh” to help (via Terminal app’s Edit -> Paste) with …
right % vi thesc.ksh
at left, as necessary, press Return key
at left highlight from the bottom ( probably “exit” ) up to the top ( probably “#!/bin/ksh” ) and use Terminal app’s Edit -> Copy
at right, as necessary, press Return key
at right, if content already there, use appropriate <escape>999dd command to clear to nothing then …
at right, press “i” key (for Insert) …
at right, use Terminal app’s Edit -> Paste
at right, maybe press <escape>w (to have an interim look) ahead of …
at right, maybe press <escape>wq!
attend to any ownership (research chown and chgrp) or file permission (research chmod) mismatches you would tweak to via ls -l /etc/init.d/* … checking and comparing between IP addresses
and consider only leaving “inhouse scripting” in /etc/init.d on new, but soon to be the DNS IP address here, for now (and into the future rewrite scripting for /etc/rc.d/init.d reuse)
When we discussed Linux Watchdog Primer Tutorial in that very generic fashion below, we were being that … generic. Today we turn to specifics in that regard. On the rjmprogramming.com.au domain we use a …
(software) watchdog which checks for the health of the MySql Service, and if not healthy, restore it to health … which is all fine and good from the point of view of the domain rjmprogramming.com.au … but depending on what the user was doing we could …
code for intervention within the MySql using piece of software, and writing out the database error to the webpage, and present alternative navigation
… on the understanding with that latter thought, that we put into play today for a WordPress 4.1.1 blog, we realized we needed to intervene in …
… where the redirection to /slideshow.html effectively “Cuts to the Chase” for the gist of that blog posting you never got to, as MySql is currently down.
Notice how specific the actions can be when you write code “dependent” on another software component, as distinct from the “watchdog” approach we often want to be “independent” in its thinking.
Guess this begs the question? How did we work out where to intervene? We just got to folders on the rjmprogramming.com.au web server with the WordPress (Codex) software and went (showing you the one that yielded the nicest result for us) …
pwd // and we are at [DocumentRoot]/ITblog
cd wp-includes
fgrep 'Error establishing a database connection' *.php
Do you have a computer operational problem? What the … what is that humanoid on about? Well, is there a computer operation you have to do routinely, to fix an ongoing problem, that relies on your personal intervention that, one day, you’d like to not have to worry about, or better still … you usually intervene, but would like a backup approach should you get sick and can’t do it … here’s where you need Fido a watchdog
… am not recommending a Golden Retriever, unless you want your process licked rather than attended to? (had you forgotten this was a question, CedricLinux Nala)? …
oh, moi?)
“
Why is bellybutton fluff blue? But we digress, or at Buckingham Palace one digresses.
Right, back at watchdogs, there are schools of thought …
The process is down for too long and we need to do something about it, because customers are leaving
If you need a watchdog to save your bacon, then (clearly you’re not with it, because the dog’s eaten the bacon and) there is something else fundamentally wrong or something you do not understand, which is what you really should resolve, either way
My view is that, if the underlying process would take years to understand or if it is written in legacy code, I’d go more with the former idea, especially as there is delight in creating a really good watchdog (training one? not so easy) … it can be really hard to do … for this reason cannot give code here really, because there is no “out of the box” that is a responsible approach to advise … you have to study the issue and cut it into its components, unit test the solutions to the components of your watchdog solution, and retest with the interactions of those components. However, this is a coding enthusiast’s view, and is a bit short-sighted, perhaps. In any case, what will save the day is that this decision will probably be made for you by an operations expert, if you work in a large organization.
Some other watchdog considerations should be …
Is the attempt to automate the solution that the watchdog will provide technically possible … may not be?!
We can resolve it with personal intervention … can the watchdog simulate each step of the human intervention? If so, go for that approach if possible.
Be very careful of approaches that involve mouse clicks, as they are quite often relative to too many other environmental issues … try to restrict the watchdog solution to command line/scripting/keyboard ideas … on Windows, AutoHotKey is an excellent recording program of interest (would recommend just using it for keyboard recordings, if using it for a watchdog … by the way, tomorrow (tomorrow arrived today) we do a tutorial showing you how to create an AutoHotKey terminate-and-stay-resident program on Windows).
Have we identified the real intervention points? If not, you might succeed some of the time, but not all the time, and you may cause damage on those times when you have made some assumptions, with your incomplete understanding.
Here is an example. You have an overnight batch process run, and it falls over at a certain point, and you get paged at 3 or 4 (it’s bound to be AM). It has been tentatively decided you might want to create a watchdog … what are some considerations …
What do log files tell me? Find out.
Is it a single thing that is missing that would resolve the problem once and for all? If yes, well, you know not to deviate from this one thing … ignore ideas below.
Of the few problems, is it worth proceeding with the watchdog idea, because the number of separate issues can often cause a factor of ten more complication issue points, and maybe you should stick with human intervention.
Break the watchdog problem into these problem issues as a separate unit-testable piece of scripting code (or whatever your watchdog solution entails) … test each for success … retest for their interaction with each other (ie. that they don’t interfere with each other).
The title of this tutorial mentions Linux but generic thinking like above covers other operating system thought patterns, but there are some Linux (or Unix) tools that are great Linux commands that we should point out … thanks to Hscripts.com and CyberCiti.biz for this …
crontab ( eg. */5 * * * * Username /path/to/command # where /path/to/command gets run by Username every five minutes … arranged via crobtab -e ) … for Windows, equivalent would be Task Schedular in Windows Primer Tutorial
And here are some of the practicalities of a watchdog …
Where does it run? If at more than one place, consider each place separately. If it runs on more than one computer, then clearly this is important. Does the directory and file permissions allow the watchdog to run, but do not allow other users to misuse it? (Please say yes here.) A generic thing about crontab or nohup (or Windows start) scripting arrangements are that you should not assume the environments of these processes is the same as your current running command line process … you should write as if you have just logged on and have done nothing … so just about the first decision of the script is to “cd” itself to the proper place where it was designed to run.
Which user(s) (on whichever computer(s)) can run it?
When does it run? If the solution is uncomplicated enough, maybe you can use a pre-emptive approach. For example, you know the problem is to do with a file missing when a non-critical process fails but later on that file is looked for, then why not pre-emptively get the watchdog to create that file (with default data) ahead of the process run crash point time.
As part of the question above, does one subprocess need to end before another starts? If yes, you need to intervene in such a way that that process architecture remains, and you need to work out an independent way for your independent watchdog to step in, at the correct time, and take over the same task, as required. But if it gets to this, don’t you understand the underlying process well enough to have a crack at doing the “real” solution (for all time)? Have a think, now, and keep checking in on the issue?
You need to log the workings of the watchdog both for information and for further research which might help in achieving a “real” solution (without the watchdog) further down the track.
So why was this posting called a tutorial? Well, there’s some homework. You see there are these Daleks, and we sort of need to know when they’re going to invade Earth again, and Dr Who is not always available, so, was wondering, if it wouldn’t be too inconvenient … if you wouldn’t mind writing that watchdog to detect a Dalek invasion and shoo them off … 6 hours … okay?
“
Woofsky!
“
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
We want to be able to control the way a Google Charts Geo Chart can be nested within an HTML div element, for instance. We started the day wanting to be able to make …
a Google Charts Geo Chart be a background image to a div element … alas, on this first draft we couldn’t get there (but will continue with the research here) … whereas we succeeded …
adding the Google Charts Geo Chart interfacer’s resultant SVG data as the innerHTML (ie. content) …
<?php echo ”
function newbackin() {
if (dmyxhr.readyState == 4) {
if (dmyxhr.status == 200) {
if (dmyxhr.responseText) {
var m_t='image/jpeg';
var h_t='179';
var w_t='320';
var dbits = dmyxhr.responseText.split('\"height\": ');
if (dbits.length > 1) {
h_t=dbits[1].split(',')[0].split(String.fromCharCode(10))[0].split('}')[0].trim();
}
dbits = dmyxhr.responseText.split('\"mime_type\": \"');
if (dbits.length > 1) {
m_t=dbits[1].split('\"')[0];
}
dbits = dmyxhr.responseText.split('\"width\": ');
if (dbits.length > 1) {
w_t=dbits[1].split(',')[0].split(String.fromCharCode(10))[0].split('}')[0].trim();
}
dbits = dmyxhr.responseText.split('\"data\":');
dbits = dmyxhr.responseText.split('\"data\":');
if (dbits.length > 1) {
// replace all '_' with '/' and all '-' with '+' thanks to https://stackoverflow.com/questions/757675/website-screenshots
dgsbi='<img alt=\"Blog Posting Image\" style=\"width:' + w_t + 'px;height:' + h_t + 'px;\" width=' + w_t + ' height=' + h_t + ' src=\"data:' + m_t + ';base64,' + dbits[1].split('\"')[1].split('\"')[0].replace(/\_/g,'/').replace(/\-/g,'+') + '\"></img>';
//alert('dgsbi=' + dgsbi);
}
}
}
}
}
function ajaxit(urlin) {
if (urlin.length > 0) {
aurl=urlin;
if (window.XMLHttpRequest) {
dmyxhr = new window.XMLHttpRequest;
}
else {
try {
dmyxhr = new ActiveXObject('Msxml2.XMLHTTP');
} catch (othermicrosoft) {
try {
dmyxhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (failed) {
dmyxhr = false;
}
}
}
var xurl = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=' + encodeURIComponent(urlin) + '&screenshot=true';
if (dmyxhr) {
dmyxhr.onreadystatechange = newbackin;
dmyxhr.open('GET', xurl, true);
dmyxhr.send(null);
}
}
}
function wbtoa(instris) {
var outstris=instris;
while (outstris.indexOf(String.fromCharCode(10)) != -1) {
outstris=outstris.replace(String.fromCharCode(10),'');
}
var xzs=prompt(outstris, outstris);
return outstris.replace(/\\\"/g, \"'\");
}
In that Nearest Places form part of the TimeZone places webpage, we noticed that even when shaping to enter a TimeZone Placename in the first textbox we made no attempt to fill in …
latitude
longitude
… when we have the information to do so, and even if we’re misunderstanding a placename designation, that should not stop us from trying, because those two numerical fields above can be corrected, and the form resubmitted, in these scenarios.
Apart from making a PHP derived Javascript variable be made available to the code, we “wrap” …
GeoJson World Countries Drag and Drop Makeover Nuance Tutorial
Nuance alert! We’re not sure if you noticed, but if you tried out the Drag and Drop functionality in the World Countries web application of yesterday’s GeoJson World Countries Drag and Drop Makeover Tutorial you may have noticed …
for a country with lots of TimeZone places, like Brazil, you could get a decent Google Chart Geo Chart map up … but if you were to click the “Map?” link down the bottom of that iframe …
it would fail to show a Google Chart Map Chart for that country’s TimeZone places
This fix, believe it or not, is interesting, perhaps only in an “internal use only” sense, we grant you. But our solution got us delving even more into hashtagging data, so that the solution we came up with was a hybrid whereby …
stayed with PHP $_GET[] (ie. address bar ? and & argumented) data (versus using PHP $_POST[] methodologies) … but …
where it came to the &data=[most of the data] part, other than its first character, we hashtagged the rest
… so that the logic flows as per usual, but we intervene at places and flesh it out via location.hash (client side only) means. We won’t bore you too much with all the places of intervention except the receiving map.php’s “easiest to get” intervention …
In addition to the Wikipedia information, at the very least, presented following a successful drag and drop operation, from today, we also start presenting a new HTML iframe element containing …
Nearest TimeZone places along with Google Charts for each unique country involved
we wanted the first popup window content be aligned to the top and left … and then …
we thought it would be good to also, in “Drag and Drop land”, relevant countries nearby to the user’s drop point TimeZone Places be showing below that (and it panned out the best way to show this, for us, was via an iframe pointing at another incarnation of the tz_places.php webpage, because it could have GET arguments iso, iso2, iso3 etcetera to point at ISO 2 letter country codes, which we made more readily available (via a new data-ccglobal data attribute applied to the select option subelements presented) for the changed external Javascript countries.js we decided should get into the mix via a new Javascript function …
function tzagain(inhtml) {
var outhtml=inhtml, dccs=[], getarg='?', theone=1;
if (inhtml.indexOf('left:0px;') != -1 && inhtml.indexOf(' data-cc=') != -1) {
dccs=inhtml.split(' data-cc=');
for (var ii=1; ii<dccs.length; ii++) {
if (getarg == '?') {
getarg+='iso=' + dccs[ii].substring(0,4).replace(/\'/g,'').replace(/\"/g,'').substring(0,2);
theone++;
} else if (getarg.indexOf('=' + dccs[ii].substring(0,4).replace(/\'/g,'').replace(/\"/g,'').substring(0,2)) == -1) {
getarg+='&iso' + theone + '=' + dccs[ii].substring(0,4).replace(/\'/g,'').replace(/\"/g,'').substring(0,2);
theone++;
}
}
if (getarg != '?') {
if (inhtml.indexOf('</bo' + 'ody>') != -1) {
outhtml=inhtml.split('</bo' + 'dy>')[0] + '<iframe src="./tz_places.php' + getarg + '" style="position:absolute;left:0px;top:120px;width:100%;height:900px;"></iframe></body></html>';
} else {
outhtml=inhtml + '<iframe src="./tz_places.php' + getarg + '" style="position:absolute;left:0px;top:120px;width:100%;height:900px;"></iframe>';
}
}
}
return outhtml;
}
… that superfluous looking ?rand=blah measure being pretty useful really regarding getting around the cache keeping old external Javascript in its mind after changes.
Curiously, the grandparent regions.php starting off all this needed no changing! We hope you like these tweaks!
add similar drag and drop logic into our World Coastlines GeoJson web application … and along the way, also for the World Countries web application …
hold off involving the (pretty kludgy looking) vertical scrollbar of our drag and drop pin’s underlying HTML iframe …
<iframe scrolling=no frameborder=0 name=iftr id=iftr style=display:none; srcdoc="<body style=background-color:transparent;><p id=mg title='Wikipedia country page below via drag and drop to world map' draggable='true'>📍</p><br><br><div id=myh1></div><script type='text/javascript' src='./countries.js?rand=321156747657' defer></script></body>" data-src=></iframe>
… until the first drag operation starting, calls on …
parent.document.getElementById('iftr').scrolling='yes';
… proving a Javascript DOM control of the “scrolling” attribute works (as we weren’t sure, having never done this before)
It’s worth beavering away at a guinea pig web application until (just about complete) satisfaction (for now) before having a parallel set of code changes happening simultaneously, we’ve always found.
So, what happened in “external Javascript land”? No need for a “regions.js” here, as parent.document.URL can be scrutinised in that “external Javascript land” to discover which web application is the parent, and act accordingly. So changed were our changed external Javascript countries.js in …
our GeoJson World Countries web application Drag and Drop logic worked on an iPhone … but …
our GeoJson World Countries web application Drag and Drop logic did not work on an iPad
They’re both iOS! And usually the smaller iPhone has the problem and the larger iPad is okay when there is an odd scenario happening. So, what gives? Well, the odd thing is, it was just rearrangements of code and iframe srcdoc usage …
<iframe frameborder=0 name=iftr id=iftr style=display:none; srcdoc="<body style=background-color:transparent;><p id=mg title='Wikipedia country page below via drag and drop to world map' draggable='true'>📍</p><br><br><div id=myh1></div><script type='text/javascript' src='./countries.js?rand=321156747657' defer></script></body>" data-src=></iframe>
… that ended up helping us fix the issues. Figure this, on iPad our emoji pin could not be made visible down the bottom left of iPad screen but could be made to work in the title elements section?! Of course, we might have been having a bad day, but in our defence, even debugging in Safari via …
iPad Safari web browser invocation …
Apple white lead from iPad to MacBook Air …
MacBook Air Safari web browser Develop menu dropdown got us to debugging functionality
“long hover” (ie. on non-mobile, wait for a long while after the onmouseover event initiation to see whether the user is still hovering) … and today, a bit like that, is the new, for us …
“long drag” (the user waits a long time between the drag initialization and the drop event)
… and because we found “dawdling” on a drag and drop fairly unnatural, we think this “long drag” idea “has legs”, in that it works well as a deliberate act made by a user, knowing at the end they benefit from their actions. For us, with our GeoJSON Map web application, yesterday, with GeoJson World Drag and Drop Pin Tutorial, the drag and drop led to …
Wikipedia country information webpage … and today, we allow a “long drag” get you to …
Google Maps drop position information webpage … if the “long drag” is for 10 or more seconds …
Google Earth drop position information webpage … if the “very long drag” is for 20 or more seconds
onclick event logic … and today, we start to also include …
drag and drop event logic (like, but nuanced as explained below, the experimental drag and drop ideas included in the recent Planet Moon Game Tutorial) … the nuanced differences involving …
the drag part of the events occurs in an iframe (populated via small amount of srcdoc HTML and Javascript) able to reference its originator via window.parent …
drop part of the events occurs in that originator parent and so several Javascript function called by the child reside in the parent … and …
the child “drag” event controller uses the new external Javascript countries.js …
// countries.js
// July, 2023
// RJM Programming
// Help out countries.html and countries.php
var pos3=0, pos4=0, tdid='', poligono, punto, coone='', prectis;
// var poligono = [[2,9],[8,6],[12,10],[15,2],[10,4],[5,1]];
// var punto = [6, 5];
function pointInPolygon(polygon, point) { // thanks to https://community.appinventor.mit.edu/t/geofence-check-if-a-point-is-inside-a-polygon-javascript-map/57091
var odd = false;
for (var i = 0, j = polygon.length - 1; i < polygon.length; i++) {
if (((polygon[i][1] > point[1]) !== (polygon[j][1] > point[1]))
&& (point[0] < ((polygon[j][0] - polygon[i][0]) * (point[1] - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0]))) {
odd = !odd;
}
j = i;
}
return odd;
}
function andlaterstill() {
if (9 == 6) { // temporary
if (tdid != '') {
document.getElementById(tdid).innerHTML=document.getElementById(tdid).innerHTML.substring(0,1);
} else if (document.getElementById('mytable').innerHTML.indexOf(clonedatatwo) != '') {
document.getElementById('myh1').innerHTML=document.getElementById('myh1').innerHTML.split('</table>')[0] + '</table>';
}
if (document.getElementsByTagName('div')[0].innerHTML.indexOf(clonedatatwo) != -1) {
document.getElementsByTagName('div')[0].innerHTML=document.getElementsByTagName('div')[0].innerHTML.replace(clonedatatwo,'');
} else if (document.getElementsByTagName('div')[0].innerHTML.indexOf(clonedatatwo.replace('dragging','')) != -1) {
document.getElementsByTagName('div')[0].innerHTML=document.getElementsByTagName('div')[0].innerHTML.replace(clonedatatwo.replace('dragging',''),'');
} else if (document.body.innerHTML.split('<table')[0].indexOf(clonedatatwo.replace('dragging','')) != -1) {
document.body.innerHTML=document.body.innerHTML.replace(document.body.innerHTML.split('<table')[0], document.body.innerHTML.split('<table')[0].replace(clonedatatwo.replace('dragging',''),''));
} else if (document.body.innerHTML.split('<table')[0].indexOf(clonedatatwo) != -1) {
document.body.innerHTML=document.body.innerHTML.replace(document.body.innerHTML.split('<table')[0], document.body.innerHTML.split('<table')[0].replace(clonedatatwo,''));
}
}
tdid='';
}
function getprectis() {
if (window.opener) {
if (window.opener.document.getElementsByTagName('body')[0]) {
return window.opener.document.body.getBoundingClientRect();
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
return parent.document.body.getBoundingClientRect();
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
return parent.document.body.getBoundingClientRect();
}
}
return null;
}
function wod(ididea) {
if (window.opener) {
if (window.opener.document.getElementsByTagName(ididea)[0]) {
return window.opener.document.getElementsByTagName(ididea)[0];
} else if (window.parent) {
if (parent.document.getElementsByTagName(ididea)[0]) {
return parent.document.getElementsByTagName(ididea)[0];
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName(ididea)[0]) {
return parent.document.getElementsByTagName(ididea)[0];
}
}
return null;
}
function ccit() {
var divs, esot=[], bodyois=null;
if (window.opener) {
if (window.opener.document.getElementsByTagName('body')[0]) {
bodyois=window.opener.document.getElementsByTagName('body')[0];
divs=window.opener.document.getElementsByTagName('div');
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
bodyois=parent.document.getElementsByTagName('body')[0];
divs=parent.document.getElementsByTagName('div');
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
bodyois=parent.document.getElementsByTagName('body')[0];
divs=parent.document.getElementsByTagName('div');
}
}
function andqlater() {
//alert('HeRe');
tdid='';
var ppig='[]', coo='', coos=[], ip=0;
var squares; //=window.opener.document.getElementsByTagName('area');
if (window.opener) {
if (window.opener.document.getElementsByTagName('body')[0]) {
squares=window.opener.document.getElementsByTagName('area');
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
squares=parent.document.getElementsByTagName('area');
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
squares=parent.document.getElementsByTagName('area');
}
}
window.addEventListener("DOMContentLoaded", () => {
const source = document.querySelector("#mg");
console.log('source.id=' + source.id);
source.addEventListener("dragstart", (ev) => {
console.log("dragStart");
// Change the source element's background color
// to show that drag has started
ev.currentTarget.classList.add("dragging");
// Clear the drag data cache (for all formats/types)
ev.dataTransfer.clearData();
// Set the drag's format and data.
// Use the event target's id for the data
ev.dataTransfer.setData("text/plain", ev.target.id);
//ev.dataTransfer.setData("text/html", ev.target.outerHTML);
});
source.addEventListener("dragend", (ev) =>
ev.target.classList.remove("dragging")
);
const target = wod('body'); //window.opener.document.getElementsByTagName('body')[0];
target.id='usemap';
console.log('target.id=' + target.id);
target.addEventListener("dragover", (ev) => {
console.log("dragOver");
ev.preventDefault();
});
target.addEventListener("drop", (ev) => {
console.log("Drop");
ev.preventDefault();
// Get the data, which is the id of the source element
const data = ev.dataTransfer.getData("text");
const source = document.getElementById(data);
… where heap memory concerns related to the global variables memory used in our GeoJson World Coastlines webpage could cause mobile platform usage reloads of the web application, reminiscent of the external Javascript concerns we had back at GeoJson World Countries SVG Overlay Safari Error Tutorial.
There, as for here, mobile usage got better by swapping global variable usage for HTML content static PHP …
GeoJson World Coastline Function Noun Naming Tutorial
We’re working on an extension to yesterday’s GeoJson World Coastline Rivers Quiz Tutorial‘s Rivers Quiz functionality within our GeoJson World Coastlines web application, and have …
settled on an approach … but …
not yet finished on deployment issues
… but it is this approach we wanted to talk about today.
Our approach borrows from Object Oriented Programming (OOP) the idea that …
just as with OOP thinking class names are like nouns and the methods within that class are like verbs … we, with our approach …
help readability of our non-OOP functional code by including those nouns and verbs, as well as ideas like use of plurals to indicate array involvement, with our Javascript function naming
… we can best illustrate to you via showing you new functions and variables and modified code to show you this approach in code …
var rivers='', arivers=[], iguess=-1, isofar=' ', jscore=0, jgoes=0, elema=null, contexta=null, rectisleft=0, rectistop=0, isokto=true;
var populations='', apopulations=[], jguess=-1, jsofar=' ', both=false, jlastn='';
var idone=false;
function askapopulation() {
var another=false;
var origboth=both;
var midbit='';
var thing='population';
if (!both) { midbit='Append spaces to also answer a question regarding the Rivers Quiz, or R to just do Rivers Quiz.'; } else { thing='river'; }
var retthis=prompt('What is the name of this new red population area plotted on the world map? ' + midbit + ' Enter ? to get given more time looking at (longitude,latitude) = (' + apopulations[jguess].split(':')[1].split(',')[0] + ',' + apopulations[jguess].split(':')[1].split(',')[1] + ')', '');
if (retthis == null) {
both=false;
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (retthis.toLowerCase().trim() == 'r') {
both=false;
isokto=true;
getariver();
return '';
} else if (retthis.trim() == '?') {
if (retthis.trim() != retthis && !origboth) { both=true; }
setTimeout(askapopulation, 9000);
return '';
} else if (retthis.trim() == '') {
if (retthis != '' && !origboth) { thing='river'; }
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
if (retthis != '' && !origboth) { isokto=true; both=true; getariver(); }
} else if (jlastn.toLowerCase().indexOf(retthis.toLowerCase()) != -1 && jlastn.toLowerCase() == retthis.toLowerCase() && retthis.trim().length >= 1) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
jscore++;
another=confirm('Will pay that. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (jlastn.toLowerCase().indexOf(retthis.toLowerCase()) == -1) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (jlastn.toLowerCase() == retthis.toLowerCase()) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
jscore++;
another=confirm('Well done! Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (retthis.trim().length >= 1) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
jscore++;
another=confirm('Will pay that. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
}
if (both) { contexta.clearRect(0,0,360,180); }
if (both && !origboth) { isitok=true; getariver(); return ''; }
if (another) { if (both) { getariver(); getapopulation(); } else { getapopulation(); } } else { contexta.clearRect(0,0,360,180); }
return '';
}
function plotapopulation(which) {
if (isokto) { contexta.clearRect(0,0,360,180); }
//if (both) { isokto=true; }
jlastn=apopulations[which].split(':')[0];
var rest=apopulations[which].split(':')[1];
var restlonglat=[]; //rest.split(',');
restlonglat=rest.split(',');
if (eval('' + restlonglat.length) >= 2) {
contexta.fillStyle = 'red';
contexta.fillRect(eval(180.0 + eval('' + restlonglat[0])), eval(90.0 - eval('' + restlonglat[1])),1,1);
contexta.fill();
}
}
It’s time to turn our attention away from GeoJson World Countries, as talked about with yesterday’s GeoJson World Countries Plotted Ports Tutorial, and back to GeoJson World Coastline ideas. Why? We want to add a …
Rivers Quiz
… via the (generously provided) HTTP://geojson.xyz rivers lake centerlines GeoJSON data we download and then uploaded to become rivers.geojson data file. Now we were wondering out of …
use the URL to this GeoJSON file as the “src” attribute of an HTML iframe …
<iframe id=ifrivers onload=getthejson(this); style=display:none; src=./rivers.geojson></iframe>
… element (and then access the content via the onload event …
var rivers='', arivers=[], iguess=-1, isofar=' ', jscore=0, jgoes=0, elema=null, contexta=null, rectisleft=0, rectistop=0;
function getthejson(iois) {
var aconto = (iois.contentWindow || iois.contentDocument);
if (aconto != null) {
if (aconto.document) { aconto = aconto.document; }
if (aconto.body != null) {
rivers='' + aconto.body.innerHTML;
setTimeout(populaterivers, 500);
}
}
}
… function) would suffice, or if we would end up using …
Ajax call
… to access this data, and were a bit surprised the former method was all fine. Of course there are snazzy inbuilt Javascript hierarchical calls you can make to process the data, but we find, with GeoJSON data, in the client realm (where we’re keen to stay with today’s work (though PHP serverside can, of course, be purloined to do all this work, should you have that available)), of Javascript, we just need very basic string functions …
The progress with GeoJson World Countries helped too. We knew to add another HTML canvas layer as per …
document.body (now with the new onmousemove=airportplot(event); event logic) lowest level …
overlayed by HTML canvas element plotted with world country linework … now including …
overlayed by HTML canvas element dedicated to nearest airport plotting …
<canvas id=myacanvas height='180' width='360' style='background-color:transparent;z-index:55;display:inline-block;position:absolute;top:0px;left:0px;'></canvas>
overlayed by HTML img (transparent image) element and its associated image map area elements … and today we add into the mix …
HTML div hosting SVG elements overlaying initialized with “land” parts green infilled SVG at a mid range z-index (only as well as when called upon) individual GeoJson entities overlay
… and to, at document.body onload logic …
// ... and extended document.body onload event logic has added, up near its top ...
elema = document.getElementById('myacanvas');
contexta = elema.getContext('2d');
… and supplement with another HTML sub “emoji button” ❓ ( ❓ ) type element …
function askariver() {
var another=false;
var retthis=prompt('What is the name of this new blue river plotted on the world map? Enter ? to get given more time looking at (longitude,latitude) = (' + arivers[iguess].split(':')[1].split(',')[0] + ',' + arivers[iguess].split(':')[1].split(',')[1] + ')', '');
if (retthis == null) {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (retthis.trim() == '?') {
setTimeout(askariver, 8000);
return '';
} else if (retthis.trim() == '') {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (lastn.toLowerCase().indexOf(retthis.toLowerCase()) == -1) {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (lastn.toLowerCase() == retthis.toLowerCase()) {
jgoes++;
jscore++;
another=confirm('Well done! Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (retthis.trim().length >= 1) {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else {
jgoes++;
jscore++;
another=confirm('Will pay that. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
}
if (another) { getariver(); } else { contexta.clearRect(0,0,360,180); }
return '';
}
… to work the Rivers Quiz. Finally, though, for all good practicalities we also need those zoom logics out of GeoJson World Countries logic, via “emoji button” 🔎 ( 🔎 ) …
where to modularise … we think “data collection” commonality is a good reason, and so we make these changes to intair.php
making an (“animated emoji”) button dual purpose on top of originally being a single purpose button …
<sub title='Show Nearby Airports' onclick='doair=how(true,this); twothousand*=2; this.title=this.title.substring(0,4) + String.fromCharCode(105) + String.fromCharCode(110) + String.fromCharCode(103) + this.title.replace(this.title.split(String.fromCharCode(32))[0] + String.fromCharCode(32), String.fromCharCode(32));' data-type=9992 style=cursor:pointer; id=portsub>✈</sub>
… working with the intairsuffix global variable that could add a new GET argument where both the “port” label in &port=[value] and that [value] can affect behaviour from the intair.php PHP helper tool above …
var intairsuffix='', zhra=null, zhrb=null, kklat=0, kklong=0, doair=false, vsll=[-999.0], answered=true;
function how(atr, isub) {
var curgd=isub.getAttribute('data-type');
if (('' + curgd) == '9992') { // airport
if (intairsuffix != '') {
intairsuffix='&port=air';
isub.title='Showing Nearby Airports and Ports';
document.getElementById('title').value='Nearby Timezone Places and Airports and Ports';
}
} else if (('' + curgd) == '128674') { // port
if (intairsuffix == '') {
if (doair) {
intairsuffix='&port=air';
isub.title='Showing Nearby Airports and Ports';
document.getElementById('title').value='Nearby Timezone Places and Airports and Ports';
} else {
intairsuffix='&port=y';
isub.title='Showing Nearby Ports';
document.getElementById('title').value='Nearby Timezone Places and Ports';
}
}
}
return true;
}
function feedhow() {
var isub=document.getElementById('portsub');
var curgd=isub.getAttribute('data-type');
if (('' + curgd) == '9992') { // airport
isub.innerHTML='🚢';
isub.setAttribute('data-type', '128674');
} else if (('' + curgd) == '128674') { // port
isub.innerHTML='✈';
isub.setAttribute('data-type', '9992');
}
}
Ajax asynchronous usage for second half of a synchronous previous usage …
var intairsuffix='', zhra=null, zhrb=null, kklat=0, kklong=0, doair=false, vsll=[-999.0], answered=true;
function stateChangedb() {
if (zhrb.readyState == 4) {
if (zhrb.status == 200) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
var onepixelequals=izoom;
var bts=zhrb.response.split('.src + ' + String.fromCharCode(39));
if (eval('' + bts.length) > 1) {
for (var ijh=1; ijh<bts.length; ijh++) {
var vs=eval(eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))) +
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top))));
if (!inarray(vs,vsll)) {
vsll.push(vs);
drawaac(
eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))),
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top)))
);
}
}
}
}
}
}
function stateChangeda() {
if (zhra.readyState == 4) {
if (zhra.status == 200) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
var onepixelequals=izoom;
var bts=zhra.response.split('.src + ' + String.fromCharCode(39));
if (eval('' + bts.length) > 1) {
for (var ijh=1; ijh<bts.length; ijh++) {
var vs=eval(eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))) +
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top))));
if (!inarray(vs,vsll)) {
vsll.push(vs);
drawaac(
eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))),
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top)))
);
}
}
}
if (intairsuffix.indexOf('&port=air') != -1) {
zhrb = new XMLHttpRequest();
zhrb.onreadystatechange=stateChangedb;
zhrb.open('get', '/HTMLCSS/intair.php?num=6&lat=' + kklat + '&long=' + kklong + '&port=y', true);
zhrb.send(null);
}
answered=true;
}
}
}
… keeps a fastish synchronous call (that we enforce via that answered global variable) but truely invokes an asynchronous arrangement extracting Nearby Ports data to plot, as applicable
Introducing the Map Chart recognition of nearby Airports with yesterday’s GeoJson World Countries Nearest Airports Tutorial‘s progress on our latest GeoJson World Countries PHP web application, it set us to seeing …
the combination of Google Directions‘s talents allowing you to reposition on the fly … and …
the onmousemove event, at least for our non-mobile users
… could mean that if we pre-plot airports on the world map, given that the user has clicked the ✈ ( ✈ ) “Show an Interest in Airports” emoji button, as a non-mobile user hovers over the world map, this pre-plotting might help trip planners with their travel options, should air travel be part of their interest, in the same way it is an option up at Google Directions in our changedcountries.phpweb application you can also try below. The overlay scenario now reads …
document.body (now with the new onmousemove=airportplot(event); event logic) lowest level …
overlayed by HTML canvas element plotted with world country linework … now including …
overlayed by HTML canvas element dedicated to nearest airport plotting …
<canvas id=myacanvas height='180' width='360' style='background-color:transparent;z-index:55;display:inline-block;position:absolute;top:0px;left:0px;'></canvas>
overlayed by HTML img (transparent image) element and its associated image map area elements … and today we add into the mix …
HTML div hosting SVG elements overlaying initialized with “land” parts green infilled SVG at a mid range z-index (only as well as when called upon) individual GeoJson entities overlay
… worked by new (sometimes Ajax) Javascript code …
function inarray(needle, haystack) { // thanks to https://stackoverflow.com/questions/784012/javascript-equivalent-of-phps-in-array
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle) return true;
}
return false;
}
function stateChangeda() {
if (zhra.readyState == 4) {
if (zhra.status == 200) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
var onepixelequals=izoom;
var bts=zhra.response.split('.src + ' + String.fromCharCode(39));
if (eval('' + bts.length) > 1) {
for (var ijh=1; ijh<bts.length; ijh++) {
var vs=eval(eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))) +
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top))));
if (!inarray(vs,vsll)) {
vsll.push(vs);
drawaac(
eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))),
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top)))
);
}
}
}
answered=true;
}
}
}
function naira(klat, klong) {
if (answered && doair) {
answered=false;
zhra = new XMLHttpRequest();
zhra.onreadystatechange=stateChangeda;
zhra.open('get', '/HTMLCSS/intair.php?num=6&lat=' + klat + '&long=' + klong, true);
zhra.send(null);
}
}
function airportplot(e) {
if (answered) {
var rectis=null; //document.body.getBoundingClientRect();
var blat=0, blong=0;
var topllong=-180.0;
var topllat=90.0;
onepixelequals=eval(0.0 + eval(1.0 * izoom));
e = e || window.event;
e.preventDefault();
if (e.touches) {
if (e.touches[0].pageX) {
naira(eval(-rectisleft + e.touches[0].pageX), eval(-rectistop + e.touches[0].pageY)); //if (drawac(eval(-rectisleft + e.touches[0].pageX), eval(-rectistop + e.touches[0].pageY))) e = e; }
} else {
rectis=document.body.getBoundingClientRect();
naira(eval(-rectis.left + e.touches[0].clientX), eval(-rectis.top + e.touches[0].clientY)); //if (drawac(eval(-rectis.left + e.touches[0].clientX), eval(-rectis.top + e.touches[0].clientY))) { e = e; }
}
} else if (e.pageX || e.pageY) {
blat=eval(eval(eval(topllat * onepixelequals - eval(-rectistop + e.pageY) * 1)) / onepixelequals);
blong=eval(eval(eval(topllong * onepixelequals + eval(-rectisleft + e.pageX) * 1)) / onepixelequals);
if ((blat >= -90.0 && blat <= 90.0) && (blong >= -180.0 && blong <= 180.0)) {
naira(blat, blong); //if (drawac(eval(-rectisleft + e.pageX), eval(-rectistop + e.pageY))) { e = e; }
}
} else {
rectis=document.body.getBoundingClientRect();
naira(eval(-rectis.left + e.clientX), eval(-rectis.top + e.clientY)); //if (drawac(eval(-rectis.left + e.clientX), eval(-rectis.top + e.clientY))) { e = e; }
}
}
}
// ... and extended document.body onload event logic has added, up near its top ...
elema = document.getElementById('myacanvas');
contexta = elema.getContext('2d');
add interfacing functionality to the excellent Google Directions part of Google Maps, perhaps to help with Trip planning, or even just to associate a Placename with a latitude and longitude as clicked by the user, via the very simple URL arrangement … https://www.google.com/maps/dir/[decimalLatitudeDegrees]/[decimalLongitudeDegrees]
… helped out by new Javascript functions …
var lastlats=[], lastlongs=[], lastlat=-99.0, lastlong=-99.0, thislat=0.0, thislong=0.0;
function preface(inblurb) {
var extras='';
var outblurb=inblurb;
if (Math.abs(eval('' + lastlat)) > 0.0 || Math.abs(eval('' + lastlong)) > 0.0) {
if (Math.abs(eval('' + lastlat)) <= 90.0 && Math.abs(eval('' + lastlong)) <= 180.0) {
extras=' Add G for Google Directions between (' + lastlat + ',' + lastlong + ') to (' + thislat + ',' + thislong + ') and spaces (also more trip legs) to hashtag navigate to Google Charts later. ';
}
}
return extras + outblurb;
}
function alats(inlat) {
if (inlat == 0 && lastlats.length == 0) { inlat=inlat; } else { lastlats.push(inlat); }
return inlat;
}
Onto yesterday’s GeoJson World Countries TimeZone Times Tutorial GeoJson World Countries web application’s capabilities we want to add zooming, that doesn’t rely on web browser functionality (which continues to work). With that in mind we create a new emoji ( 🔎 ) 🔎 link, with this onclick event code …
var jzoom=1.0, izoom=location.search.split('zoom=')[1] ? eval(decodeURIComponent(location.search.split('zoom=')[1].split('&')[0])) : 1.0;
… to multiply the webpage zoom factor in a programmatical way. To acheive this, we have a two way approach (as you might have surmised from above) …
for mobile, the logic is easier by introducing a new meta name=viewport …
<meta id="myviewport" name="viewport" content="width=device-width, initial-scale=1, minimum-scale=0.1, maximum-scale=8, user-scalable=yes" >
… tag … while …
for non-mobile we needed to realize that event.pageX and event.pageY co-ordinates grow in proportion to the zoom factor, and that better latitude and longitude determining lines of code would go …
function canvasclick(e) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
onepixelequals=eval(0.0 + eval(1.0 * izoom));
//document.title='canvasclick';
e = e || window.event;
e.preventDefault();
if (e.touches) {
if (e.touches[0].pageX) {
//lastl='Longitude,Latitude coordinates are ' + eval(topllong + eval(-rectis.left + e.touches[0].pageX) * onepixelequals) + ',' + eval(topllat - eval(-rectis.top + e.touches[0].pageY) * onepixelequals);
if (drawc(eval(-rectisleft + e.touches[0].pageX), eval(-rectistop + e.touches[0].pageY))) {
thislat=eval(topllat - eval(-rectistop + e.touches[0].pageY) * onepixelequals);
thislong=eval(topllong + eval(-rectisleft + e.touches[0].pageX) * onepixelequals);
//console.log('rectistop=' + rectistop + ' and rectisleft=' + rectisleft + ' and rectisy=' + rectisy + ' and thislat=' + thislat);
document.getElementById('nearestif').src='/PHP/tz_places.php?place=&latitude=' + encodeURIComponent('' + eval(topllat - eval(-rectistop + e.touches[0].pageY) * onepixelequals)) + '&longitude=' + encodeURIComponent('' + eval(topllong + eval(-rectisleft + e.touches[0].pageX) * onepixelequals)) + '&ntztontz=y';
}
} else {
Some readers might be aware of our “theory regarding adverbs” and “web applications” on the net …
the most catered for adverb relates to the “where of life” … and the second banana is …
the “when of life”
… and, further to yesterday’s GeoJson World Countries SVG Overlay Safari Error Tutorial‘s emphasis on the “where of life”, today we add in a bit of the “when of life”, something right down the line of the remit of TimeZone talents.
Seriously though, a lot of us dream of the rest of the world on a world map, and wonder what time it is in other parts of the world. Phone call to relatives? A reminder SMS call? Email a game collaboration? It could all be part of life’s rich tapestry!
The expresion of this, for us, today, improving the communications with our current GeoJsom World Countries web application, take the form of emoji clocks from the 12 hour clock example forms such as …
1 o’clock is 🕐 🕐
2 o’clock is 🕑 🕑
12 o’clock is 🕛 🕛
2:30 is 🕝 🕝
11:30 is 🕦 🕦
12:30 is 🕧 🕧
… to show in “prompt” and “confirm” popup windows, as well as Map Chart maps … via new Javascript functions …
Also, in these same places we add in Time Place country ISO-2 character code based emoji flags, adding to information and colour pizazz in the informational parts to the workings of our changedcountries.phpweb application you can also try below.
On discovering our first solution theory of turning yesterday’s mapsvg.js external Javascript work into an async piece of work made no difference to this situation, we surmised that the huge amount of content held in the Javascript (ie. client side) global variable appendtoinnerHTML was causing memory issues. We couldn’t shift much to do with the overall amount of “data” needing to be handled, in order to implement country SVG colour infilling, but we could shift the data from being …
client side (external) Javascript held … to, instead, (have that data) be (determined on the) …
server side PHP filling in the contents of our (relevant) HTML div id=svgd ahead of the document.body onload event timing …
<?php
$icnt=0;
function apptohtmstuff($coordsare, $origc) {
global $icnt;
$minl=-1;
$mint=-1;
$maxl=-1;
$maxt=-1;
$zysare=explode(',', $coordsare);
$svgcis='';
for ($ij=0; $ij<sizeof($zysare); $ij+=2) {
if ($minl < 0) {
$minl=$zysare[$ij];
$maxl=$zysare[$ij];
$mint=$zysare[1 + $ij];
$maxt=$zysare[1 + $ij];
} else {
if ($zysare[$ij] < $minl) { $minl=$zysare[$ij]; }
if ($zysare[$ij] > $maxl) { $maxl=$zysare[$ij]; }
if ($zysare[1 + $ij] < $mint) { $mint=$zysare[1 + $ij]; }
if ($zysare[1 + $ij] > $maxt) { $maxt=$zysare[1 + $ij]; }
}
}
…everywhere … and an idea we’d ditched yesterday of …
idea to pre-colour “land” parts of the world GeoJson map green (ahead of the document.body onload event) also came good (after causing problems yesterday)
… meaning now, “overlay” wise, we could say …
document.body lowest level …
overlayed by HTML canvas element plotted with world country linework …
overlayed by HTML img (transparent image) element and its associated image map area elements … and today we add into the mix …
HTML div hosting SVG elements overlaying initialized with “land” parts green infilled SVG at a mid range z-index (only as well as when called upon) individual GeoJson entities overlay
… and we (reckon we’ve) improved the colour coding user experience at the same time.
We noticed that tweaks in the changed …
var lastflagged='', appendtoinnerHTML='', waitplease=false; // used to make sure "area" element onclick code precedes any document.body onmousedown or ontouchdown code
… also lessened the burden on the client side by only asking any Javascript DOM command operations act on single HTML element at a time, not a whole swathe of hosted ones, in any operation.
What deducible data item needs to be determined for these Geo Charts to work? We need a way to deduce ISO-2 character country codes from the ISO-3 character codes existing in the GeoJson “countries.geojson” data from yesterday’s work. We happened upon the extremely generous mapping data webpage to help with these ISO-2 character deductions …
… in our image map area elements PHP creation code above. As you can see, extra “intelligence”, moving forward, is contained in area element global data attributes.
Geo Chart can involve emoji (🏠 &127968;) or image (SVG) circle based symbology for the “User Clicked Place” and nearby TimeZone places respectively …
all these symbols can be clicked to open popup windows containing TimeZone Place Wikipedia webpages of relevance …
an emoji national flag (eg. Zambia “ZA” could be used to derive 🇿🇦 🇿🇦 flag emoji) derived from those ISO-2 character codes can supplement the GeoJson (more ISO-3 character based) names presented in the underlying data, in the Geo Chart title …
contextualizing the accompanying Map Chart … and …
vice versa regarding hovering over symbology (which works on Map Chart, but not Geo Chart) …
within the Map Chart iframe a “Geo” link can glean a “zoomed out” world Geo Chart view of your TimeZone places
Know your GeoJson! Yes, pretty obviously, any two GeoJson datasets might display the same in that “map plotting” sense, but one might have different and/or more “intelligence” than the other. Often, an XML has more “intelligence” than equivalent HTML (barring the use of global data attributes, that is), as today’s Corollacorollary.
Luckily for programmers all over, the organization of TimeZones has had an International flavour in its development and maintenance. As such, given the “purely coastline” GeoJson data involved in our fledgling PHP web application of yesterday’s GeoJson World Coastline Primer Tutorial a useful arrangement for improvement involves …
document.body onclick event co-ordinates … able to be converted to …
longitude, latitude (easily, only because of our simplistic map projection, of course) … onfed to …
… can have us helping out your curious web “clicking” user with the 3 nearest TimeZone places, as a reference as to where they are “clicking” in the world.
in a discrete click methodology of interest, you could adopt a non-mobile “onmousedown” logic set that does not get interfered with by a mobile “ontouchdown” logic set (perhaps leaving “onclick” event, which both non-mobile and mobile both recognise, for another event logic role) … and …
neither will interrupt the mobile gestures associated with swiping and pinching, which refer to the events “ontouchstart” and “ontouchend” at either end of their lifespan
And so, we arrive at a long planned for tilt at Image Map functionality that we often turn to Mobilefish.Com and its excellent Image Map Creation to help us out … but not today?! Why not? We have a funny set of needs, they being …
our Image Map’s image will have a variable set of width x height dimensions …
our Image Map’s image will be transparent
our Image Map needs to have a hole left aside inside it where the functionality that originally existed (and pointed to WordPress Blog content like you are reading), is still working
We want to be able to control the way a Google Charts Geo Chart can be nested within an HTML div element, for instance. We started the day wanting to be able to make …
a Google Charts Geo Chart be a background image to a div element … alas, on this first draft we couldn’t get there (but will continue with the research here) … whereas we succeeded …
adding the Google Charts Geo Chart interfacer’s resultant SVG data as the innerHTML (ie. content) …
<?php echo ”
function newbackin() {
if (dmyxhr.readyState == 4) {
if (dmyxhr.status == 200) {
if (dmyxhr.responseText) {
var m_t='image/jpeg';
var h_t='179';
var w_t='320';
var dbits = dmyxhr.responseText.split('\"height\": ');
if (dbits.length > 1) {
h_t=dbits[1].split(',')[0].split(String.fromCharCode(10))[0].split('}')[0].trim();
}
dbits = dmyxhr.responseText.split('\"mime_type\": \"');
if (dbits.length > 1) {
m_t=dbits[1].split('\"')[0];
}
dbits = dmyxhr.responseText.split('\"width\": ');
if (dbits.length > 1) {
w_t=dbits[1].split(',')[0].split(String.fromCharCode(10))[0].split('}')[0].trim();
}
dbits = dmyxhr.responseText.split('\"data\":');
dbits = dmyxhr.responseText.split('\"data\":');
if (dbits.length > 1) {
// replace all '_' with '/' and all '-' with '+' thanks to https://stackoverflow.com/questions/757675/website-screenshots
dgsbi='<img alt=\"Blog Posting Image\" style=\"width:' + w_t + 'px;height:' + h_t + 'px;\" width=' + w_t + ' height=' + h_t + ' src=\"data:' + m_t + ';base64,' + dbits[1].split('\"')[1].split('\"')[0].replace(/\_/g,'/').replace(/\-/g,'+') + '\"></img>';
//alert('dgsbi=' + dgsbi);
}
}
}
}
}
function ajaxit(urlin) {
if (urlin.length > 0) {
aurl=urlin;
if (window.XMLHttpRequest) {
dmyxhr = new window.XMLHttpRequest;
}
else {
try {
dmyxhr = new ActiveXObject('Msxml2.XMLHTTP');
} catch (othermicrosoft) {
try {
dmyxhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (failed) {
dmyxhr = false;
}
}
}
var xurl = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=' + encodeURIComponent(urlin) + '&screenshot=true';
if (dmyxhr) {
dmyxhr.onreadystatechange = newbackin;
dmyxhr.open('GET', xurl, true);
dmyxhr.send(null);
}
}
}
function wbtoa(instris) {
var outstris=instris;
while (outstris.indexOf(String.fromCharCode(10)) != -1) {
outstris=outstris.replace(String.fromCharCode(10),'');
}
var xzs=prompt(outstris, outstris);
return outstris.replace(/\\\"/g, \"'\");
}
In that Nearest Places form part of the TimeZone places webpage, we noticed that even when shaping to enter a TimeZone Placename in the first textbox we made no attempt to fill in …
latitude
longitude
… when we have the information to do so, and even if we’re misunderstanding a placename designation, that should not stop us from trying, because those two numerical fields above can be corrected, and the form resubmitted, in these scenarios.
Apart from making a PHP derived Javascript variable be made available to the code, we “wrap” …
GeoJson World Countries Drag and Drop Makeover Nuance Tutorial
Nuance alert! We’re not sure if you noticed, but if you tried out the Drag and Drop functionality in the World Countries web application of yesterday’s GeoJson World Countries Drag and Drop Makeover Tutorial you may have noticed …
for a country with lots of TimeZone places, like Brazil, you could get a decent Google Chart Geo Chart map up … but if you were to click the “Map?” link down the bottom of that iframe …
it would fail to show a Google Chart Map Chart for that country’s TimeZone places
This fix, believe it or not, is interesting, perhaps only in an “internal use only” sense, we grant you. But our solution got us delving even more into hashtagging data, so that the solution we came up with was a hybrid whereby …
stayed with PHP $_GET[] (ie. address bar ? and & argumented) data (versus using PHP $_POST[] methodologies) … but …
where it came to the &data=[most of the data] part, other than its first character, we hashtagged the rest
… so that the logic flows as per usual, but we intervene at places and flesh it out via location.hash (client side only) means. We won’t bore you too much with all the places of intervention except the receiving map.php’s “easiest to get” intervention …
In addition to the Wikipedia information, at the very least, presented following a successful drag and drop operation, from today, we also start presenting a new HTML iframe element containing …
Nearest TimeZone places along with Google Charts for each unique country involved
we wanted the first popup window content be aligned to the top and left … and then …
we thought it would be good to also, in “Drag and Drop land”, relevant countries nearby to the user’s drop point TimeZone Places be showing below that (and it panned out the best way to show this, for us, was via an iframe pointing at another incarnation of the tz_places.php webpage, because it could have GET arguments iso, iso2, iso3 etcetera to point at ISO 2 letter country codes, which we made more readily available (via a new data-ccglobal data attribute applied to the select option subelements presented) for the changed external Javascript countries.js we decided should get into the mix via a new Javascript function …
function tzagain(inhtml) {
var outhtml=inhtml, dccs=[], getarg='?', theone=1;
if (inhtml.indexOf('left:0px;') != -1 && inhtml.indexOf(' data-cc=') != -1) {
dccs=inhtml.split(' data-cc=');
for (var ii=1; ii<dccs.length; ii++) {
if (getarg == '?') {
getarg+='iso=' + dccs[ii].substring(0,4).replace(/\'/g,'').replace(/\"/g,'').substring(0,2);
theone++;
} else if (getarg.indexOf('=' + dccs[ii].substring(0,4).replace(/\'/g,'').replace(/\"/g,'').substring(0,2)) == -1) {
getarg+='&iso' + theone + '=' + dccs[ii].substring(0,4).replace(/\'/g,'').replace(/\"/g,'').substring(0,2);
theone++;
}
}
if (getarg != '?') {
if (inhtml.indexOf('</bo' + 'ody>') != -1) {
outhtml=inhtml.split('</bo' + 'dy>')[0] + '<iframe src="./tz_places.php' + getarg + '" style="position:absolute;left:0px;top:120px;width:100%;height:900px;"></iframe></body></html>';
} else {
outhtml=inhtml + '<iframe src="./tz_places.php' + getarg + '" style="position:absolute;left:0px;top:120px;width:100%;height:900px;"></iframe>';
}
}
}
return outhtml;
}
… that superfluous looking ?rand=blah measure being pretty useful really regarding getting around the cache keeping old external Javascript in its mind after changes.
Curiously, the grandparent regions.php starting off all this needed no changing! We hope you like these tweaks!
add similar drag and drop logic into our World Coastlines GeoJson web application … and along the way, also for the World Countries web application …
hold off involving the (pretty kludgy looking) vertical scrollbar of our drag and drop pin’s underlying HTML iframe …
<iframe scrolling=no frameborder=0 name=iftr id=iftr style=display:none; srcdoc="<body style=background-color:transparent;><p id=mg title='Wikipedia country page below via drag and drop to world map' draggable='true'>📍</p><br><br><div id=myh1></div><script type='text/javascript' src='./countries.js?rand=321156747657' defer></script></body>" data-src=></iframe>
… until the first drag operation starting, calls on …
parent.document.getElementById('iftr').scrolling='yes';
… proving a Javascript DOM control of the “scrolling” attribute works (as we weren’t sure, having never done this before)
It’s worth beavering away at a guinea pig web application until (just about complete) satisfaction (for now) before having a parallel set of code changes happening simultaneously, we’ve always found.
So, what happened in “external Javascript land”? No need for a “regions.js” here, as parent.document.URL can be scrutinised in that “external Javascript land” to discover which web application is the parent, and act accordingly. So changed were our changed external Javascript countries.js in …
our GeoJson World Countries web application Drag and Drop logic worked on an iPhone … but …
our GeoJson World Countries web application Drag and Drop logic did not work on an iPad
They’re both iOS! And usually the smaller iPhone has the problem and the larger iPad is okay when there is an odd scenario happening. So, what gives? Well, the odd thing is, it was just rearrangements of code and iframe srcdoc usage …
<iframe frameborder=0 name=iftr id=iftr style=display:none; srcdoc="<body style=background-color:transparent;><p id=mg title='Wikipedia country page below via drag and drop to world map' draggable='true'>📍</p><br><br><div id=myh1></div><script type='text/javascript' src='./countries.js?rand=321156747657' defer></script></body>" data-src=></iframe>
… that ended up helping us fix the issues. Figure this, on iPad our emoji pin could not be made visible down the bottom left of iPad screen but could be made to work in the title elements section?! Of course, we might have been having a bad day, but in our defence, even debugging in Safari via …
iPad Safari web browser invocation …
Apple white lead from iPad to MacBook Air …
MacBook Air Safari web browser Develop menu dropdown got us to debugging functionality
“long hover” (ie. on non-mobile, wait for a long while after the onmouseover event initiation to see whether the user is still hovering) … and today, a bit like that, is the new, for us …
“long drag” (the user waits a long time between the drag initialization and the drop event)
… and because we found “dawdling” on a drag and drop fairly unnatural, we think this “long drag” idea “has legs”, in that it works well as a deliberate act made by a user, knowing at the end they benefit from their actions. For us, with our GeoJSON Map web application, yesterday, with GeoJson World Drag and Drop Pin Tutorial, the drag and drop led to …
Wikipedia country information webpage … and today, we allow a “long drag” get you to …
Google Maps drop position information webpage … if the “long drag” is for 10 or more seconds …
Google Earth drop position information webpage … if the “very long drag” is for 20 or more seconds
onclick event logic … and today, we start to also include …
drag and drop event logic (like, but nuanced as explained below, the experimental drag and drop ideas included in the recent Planet Moon Game Tutorial) … the nuanced differences involving …
the drag part of the events occurs in an iframe (populated via small amount of srcdoc HTML and Javascript) able to reference its originator via window.parent …
drop part of the events occurs in that originator parent and so several Javascript function called by the child reside in the parent … and …
the child “drag” event controller uses the new external Javascript countries.js …
// countries.js
// July, 2023
// RJM Programming
// Help out countries.html and countries.php
var pos3=0, pos4=0, tdid='', poligono, punto, coone='', prectis;
// var poligono = [[2,9],[8,6],[12,10],[15,2],[10,4],[5,1]];
// var punto = [6, 5];
function pointInPolygon(polygon, point) { // thanks to https://community.appinventor.mit.edu/t/geofence-check-if-a-point-is-inside-a-polygon-javascript-map/57091
var odd = false;
for (var i = 0, j = polygon.length - 1; i < polygon.length; i++) {
if (((polygon[i][1] > point[1]) !== (polygon[j][1] > point[1]))
&& (point[0] < ((polygon[j][0] - polygon[i][0]) * (point[1] - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0]))) {
odd = !odd;
}
j = i;
}
return odd;
}
function andlaterstill() {
if (9 == 6) { // temporary
if (tdid != '') {
document.getElementById(tdid).innerHTML=document.getElementById(tdid).innerHTML.substring(0,1);
} else if (document.getElementById('mytable').innerHTML.indexOf(clonedatatwo) != '') {
document.getElementById('myh1').innerHTML=document.getElementById('myh1').innerHTML.split('</table>')[0] + '</table>';
}
if (document.getElementsByTagName('div')[0].innerHTML.indexOf(clonedatatwo) != -1) {
document.getElementsByTagName('div')[0].innerHTML=document.getElementsByTagName('div')[0].innerHTML.replace(clonedatatwo,'');
} else if (document.getElementsByTagName('div')[0].innerHTML.indexOf(clonedatatwo.replace('dragging','')) != -1) {
document.getElementsByTagName('div')[0].innerHTML=document.getElementsByTagName('div')[0].innerHTML.replace(clonedatatwo.replace('dragging',''),'');
} else if (document.body.innerHTML.split('<table')[0].indexOf(clonedatatwo.replace('dragging','')) != -1) {
document.body.innerHTML=document.body.innerHTML.replace(document.body.innerHTML.split('<table')[0], document.body.innerHTML.split('<table')[0].replace(clonedatatwo.replace('dragging',''),''));
} else if (document.body.innerHTML.split('<table')[0].indexOf(clonedatatwo) != -1) {
document.body.innerHTML=document.body.innerHTML.replace(document.body.innerHTML.split('<table')[0], document.body.innerHTML.split('<table')[0].replace(clonedatatwo,''));
}
}
tdid='';
}
function getprectis() {
if (window.opener) {
if (window.opener.document.getElementsByTagName('body')[0]) {
return window.opener.document.body.getBoundingClientRect();
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
return parent.document.body.getBoundingClientRect();
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
return parent.document.body.getBoundingClientRect();
}
}
return null;
}
function wod(ididea) {
if (window.opener) {
if (window.opener.document.getElementsByTagName(ididea)[0]) {
return window.opener.document.getElementsByTagName(ididea)[0];
} else if (window.parent) {
if (parent.document.getElementsByTagName(ididea)[0]) {
return parent.document.getElementsByTagName(ididea)[0];
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName(ididea)[0]) {
return parent.document.getElementsByTagName(ididea)[0];
}
}
return null;
}
function ccit() {
var divs, esot=[], bodyois=null;
if (window.opener) {
if (window.opener.document.getElementsByTagName('body')[0]) {
bodyois=window.opener.document.getElementsByTagName('body')[0];
divs=window.opener.document.getElementsByTagName('div');
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
bodyois=parent.document.getElementsByTagName('body')[0];
divs=parent.document.getElementsByTagName('div');
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
bodyois=parent.document.getElementsByTagName('body')[0];
divs=parent.document.getElementsByTagName('div');
}
}
function andqlater() {
//alert('HeRe');
tdid='';
var ppig='[]', coo='', coos=[], ip=0;
var squares; //=window.opener.document.getElementsByTagName('area');
if (window.opener) {
if (window.opener.document.getElementsByTagName('body')[0]) {
squares=window.opener.document.getElementsByTagName('area');
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
squares=parent.document.getElementsByTagName('area');
}
}
} else if (window.parent) {
if (parent.document.getElementsByTagName('body')[0]) {
squares=parent.document.getElementsByTagName('area');
}
}
window.addEventListener("DOMContentLoaded", () => {
const source = document.querySelector("#mg");
console.log('source.id=' + source.id);
source.addEventListener("dragstart", (ev) => {
console.log("dragStart");
// Change the source element's background color
// to show that drag has started
ev.currentTarget.classList.add("dragging");
// Clear the drag data cache (for all formats/types)
ev.dataTransfer.clearData();
// Set the drag's format and data.
// Use the event target's id for the data
ev.dataTransfer.setData("text/plain", ev.target.id);
//ev.dataTransfer.setData("text/html", ev.target.outerHTML);
});
source.addEventListener("dragend", (ev) =>
ev.target.classList.remove("dragging")
);
const target = wod('body'); //window.opener.document.getElementsByTagName('body')[0];
target.id='usemap';
console.log('target.id=' + target.id);
target.addEventListener("dragover", (ev) => {
console.log("dragOver");
ev.preventDefault();
});
target.addEventListener("drop", (ev) => {
console.log("Drop");
ev.preventDefault();
// Get the data, which is the id of the source element
const data = ev.dataTransfer.getData("text");
const source = document.getElementById(data);
… where heap memory concerns related to the global variables memory used in our GeoJson World Coastlines webpage could cause mobile platform usage reloads of the web application, reminiscent of the external Javascript concerns we had back at GeoJson World Countries SVG Overlay Safari Error Tutorial.
There, as for here, mobile usage got better by swapping global variable usage for HTML content static PHP …
GeoJson World Coastline Function Noun Naming Tutorial
We’re working on an extension to yesterday’s GeoJson World Coastline Rivers Quiz Tutorial‘s Rivers Quiz functionality within our GeoJson World Coastlines web application, and have …
settled on an approach … but …
not yet finished on deployment issues
… but it is this approach we wanted to talk about today.
Our approach borrows from Object Oriented Programming (OOP) the idea that …
just as with OOP thinking class names are like nouns and the methods within that class are like verbs … we, with our approach …
help readability of our non-OOP functional code by including those nouns and verbs, as well as ideas like use of plurals to indicate array involvement, with our Javascript function naming
… we can best illustrate to you via showing you new functions and variables and modified code to show you this approach in code …
var rivers='', arivers=[], iguess=-1, isofar=' ', jscore=0, jgoes=0, elema=null, contexta=null, rectisleft=0, rectistop=0, isokto=true;
var populations='', apopulations=[], jguess=-1, jsofar=' ', both=false, jlastn='';
var idone=false;
function askapopulation() {
var another=false;
var origboth=both;
var midbit='';
var thing='population';
if (!both) { midbit='Append spaces to also answer a question regarding the Rivers Quiz, or R to just do Rivers Quiz.'; } else { thing='river'; }
var retthis=prompt('What is the name of this new red population area plotted on the world map? ' + midbit + ' Enter ? to get given more time looking at (longitude,latitude) = (' + apopulations[jguess].split(':')[1].split(',')[0] + ',' + apopulations[jguess].split(':')[1].split(',')[1] + ')', '');
if (retthis == null) {
both=false;
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (retthis.toLowerCase().trim() == 'r') {
both=false;
isokto=true;
getariver();
return '';
} else if (retthis.trim() == '?') {
if (retthis.trim() != retthis && !origboth) { both=true; }
setTimeout(askapopulation, 9000);
return '';
} else if (retthis.trim() == '') {
if (retthis != '' && !origboth) { thing='river'; }
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
if (retthis != '' && !origboth) { isokto=true; both=true; getariver(); }
} else if (jlastn.toLowerCase().indexOf(retthis.toLowerCase()) != -1 && jlastn.toLowerCase() == retthis.toLowerCase() && retthis.trim().length >= 1) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
jscore++;
another=confirm('Will pay that. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (jlastn.toLowerCase().indexOf(retthis.toLowerCase()) == -1) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (jlastn.toLowerCase() == retthis.toLowerCase()) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
jscore++;
another=confirm('Well done! Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else if (retthis.trim().length >= 1) {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
another=confirm('Bad luck. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
} else {
if (retthis.trim() != retthis && !origboth) { both=true; thing='river'; }
jgoes++;
jscore++;
another=confirm('Will pay that. Answer was ' + jlastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new ' + thing + '?');
}
if (both) { contexta.clearRect(0,0,360,180); }
if (both && !origboth) { isitok=true; getariver(); return ''; }
if (another) { if (both) { getariver(); getapopulation(); } else { getapopulation(); } } else { contexta.clearRect(0,0,360,180); }
return '';
}
function plotapopulation(which) {
if (isokto) { contexta.clearRect(0,0,360,180); }
//if (both) { isokto=true; }
jlastn=apopulations[which].split(':')[0];
var rest=apopulations[which].split(':')[1];
var restlonglat=[]; //rest.split(',');
restlonglat=rest.split(',');
if (eval('' + restlonglat.length) >= 2) {
contexta.fillStyle = 'red';
contexta.fillRect(eval(180.0 + eval('' + restlonglat[0])), eval(90.0 - eval('' + restlonglat[1])),1,1);
contexta.fill();
}
}
It’s time to turn our attention away from GeoJson World Countries, as talked about with yesterday’s GeoJson World Countries Plotted Ports Tutorial, and back to GeoJson World Coastline ideas. Why? We want to add a …
Rivers Quiz
… via the (generously provided) HTTP://geojson.xyz rivers lake centerlines GeoJSON data we download and then uploaded to become rivers.geojson data file. Now we were wondering out of …
use the URL to this GeoJSON file as the “src” attribute of an HTML iframe …
<iframe id=ifrivers onload=getthejson(this); style=display:none; src=./rivers.geojson></iframe>
… element (and then access the content via the onload event …
var rivers='', arivers=[], iguess=-1, isofar=' ', jscore=0, jgoes=0, elema=null, contexta=null, rectisleft=0, rectistop=0;
function getthejson(iois) {
var aconto = (iois.contentWindow || iois.contentDocument);
if (aconto != null) {
if (aconto.document) { aconto = aconto.document; }
if (aconto.body != null) {
rivers='' + aconto.body.innerHTML;
setTimeout(populaterivers, 500);
}
}
}
… function) would suffice, or if we would end up using …
Ajax call
… to access this data, and were a bit surprised the former method was all fine. Of course there are snazzy inbuilt Javascript hierarchical calls you can make to process the data, but we find, with GeoJSON data, in the client realm (where we’re keen to stay with today’s work (though PHP serverside can, of course, be purloined to do all this work, should you have that available)), of Javascript, we just need very basic string functions …
The progress with GeoJson World Countries helped too. We knew to add another HTML canvas layer as per …
document.body (now with the new onmousemove=airportplot(event); event logic) lowest level …
overlayed by HTML canvas element plotted with world country linework … now including …
overlayed by HTML canvas element dedicated to nearest airport plotting …
<canvas id=myacanvas height='180' width='360' style='background-color:transparent;z-index:55;display:inline-block;position:absolute;top:0px;left:0px;'></canvas>
overlayed by HTML img (transparent image) element and its associated image map area elements … and today we add into the mix …
HTML div hosting SVG elements overlaying initialized with “land” parts green infilled SVG at a mid range z-index (only as well as when called upon) individual GeoJson entities overlay
… and to, at document.body onload logic …
// ... and extended document.body onload event logic has added, up near its top ...
elema = document.getElementById('myacanvas');
contexta = elema.getContext('2d');
… and supplement with another HTML sub “emoji button” ❓ ( ❓ ) type element …
function askariver() {
var another=false;
var retthis=prompt('What is the name of this new blue river plotted on the world map? Enter ? to get given more time looking at (longitude,latitude) = (' + arivers[iguess].split(':')[1].split(',')[0] + ',' + arivers[iguess].split(':')[1].split(',')[1] + ')', '');
if (retthis == null) {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (retthis.trim() == '?') {
setTimeout(askariver, 8000);
return '';
} else if (retthis.trim() == '') {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (lastn.toLowerCase().indexOf(retthis.toLowerCase()) == -1) {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (lastn.toLowerCase() == retthis.toLowerCase()) {
jgoes++;
jscore++;
another=confirm('Well done! Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else if (retthis.trim().length >= 1) {
jgoes++;
another=confirm('Bad luck. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
} else {
jgoes++;
jscore++;
another=confirm('Will pay that. Answer was ' + lastn + '. Score ' + jscore + '/' + jgoes + '. Another go with a new river?');
}
if (another) { getariver(); } else { contexta.clearRect(0,0,360,180); }
return '';
}
… to work the Rivers Quiz. Finally, though, for all good practicalities we also need those zoom logics out of GeoJson World Countries logic, via “emoji button” 🔎 ( 🔎 ) …
where to modularise … we think “data collection” commonality is a good reason, and so we make these changes to intair.php
making an (“animated emoji”) button dual purpose on top of originally being a single purpose button …
<sub title='Show Nearby Airports' onclick='doair=how(true,this); twothousand*=2; this.title=this.title.substring(0,4) + String.fromCharCode(105) + String.fromCharCode(110) + String.fromCharCode(103) + this.title.replace(this.title.split(String.fromCharCode(32))[0] + String.fromCharCode(32), String.fromCharCode(32));' data-type=9992 style=cursor:pointer; id=portsub>✈</sub>
… working with the intairsuffix global variable that could add a new GET argument where both the “port” label in &port=[value] and that [value] can affect behaviour from the intair.php PHP helper tool above …
var intairsuffix='', zhra=null, zhrb=null, kklat=0, kklong=0, doair=false, vsll=[-999.0], answered=true;
function how(atr, isub) {
var curgd=isub.getAttribute('data-type');
if (('' + curgd) == '9992') { // airport
if (intairsuffix != '') {
intairsuffix='&port=air';
isub.title='Showing Nearby Airports and Ports';
document.getElementById('title').value='Nearby Timezone Places and Airports and Ports';
}
} else if (('' + curgd) == '128674') { // port
if (intairsuffix == '') {
if (doair) {
intairsuffix='&port=air';
isub.title='Showing Nearby Airports and Ports';
document.getElementById('title').value='Nearby Timezone Places and Airports and Ports';
} else {
intairsuffix='&port=y';
isub.title='Showing Nearby Ports';
document.getElementById('title').value='Nearby Timezone Places and Ports';
}
}
}
return true;
}
function feedhow() {
var isub=document.getElementById('portsub');
var curgd=isub.getAttribute('data-type');
if (('' + curgd) == '9992') { // airport
isub.innerHTML='🚢';
isub.setAttribute('data-type', '128674');
} else if (('' + curgd) == '128674') { // port
isub.innerHTML='✈';
isub.setAttribute('data-type', '9992');
}
}
Ajax asynchronous usage for second half of a synchronous previous usage …
var intairsuffix='', zhra=null, zhrb=null, kklat=0, kklong=0, doair=false, vsll=[-999.0], answered=true;
function stateChangedb() {
if (zhrb.readyState == 4) {
if (zhrb.status == 200) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
var onepixelequals=izoom;
var bts=zhrb.response.split('.src + ' + String.fromCharCode(39));
if (eval('' + bts.length) > 1) {
for (var ijh=1; ijh<bts.length; ijh++) {
var vs=eval(eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))) +
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top))));
if (!inarray(vs,vsll)) {
vsll.push(vs);
drawaac(
eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))),
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top)))
);
}
}
}
}
}
}
function stateChangeda() {
if (zhra.readyState == 4) {
if (zhra.status == 200) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
var onepixelequals=izoom;
var bts=zhra.response.split('.src + ' + String.fromCharCode(39));
if (eval('' + bts.length) > 1) {
for (var ijh=1; ijh<bts.length; ijh++) {
var vs=eval(eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))) +
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top))));
if (!inarray(vs,vsll)) {
vsll.push(vs);
drawaac(
eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))),
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top)))
);
}
}
}
if (intairsuffix.indexOf('&port=air') != -1) {
zhrb = new XMLHttpRequest();
zhrb.onreadystatechange=stateChangedb;
zhrb.open('get', '/HTMLCSS/intair.php?num=6&lat=' + kklat + '&long=' + kklong + '&port=y', true);
zhrb.send(null);
}
answered=true;
}
}
}
… keeps a fastish synchronous call (that we enforce via that answered global variable) but truely invokes an asynchronous arrangement extracting Nearby Ports data to plot, as applicable
Introducing the Map Chart recognition of nearby Airports with yesterday’s GeoJson World Countries Nearest Airports Tutorial‘s progress on our latest GeoJson World Countries PHP web application, it set us to seeing …
the combination of Google Directions‘s talents allowing you to reposition on the fly … and …
the onmousemove event, at least for our non-mobile users
… could mean that if we pre-plot airports on the world map, given that the user has clicked the ✈ ( ✈ ) “Show an Interest in Airports” emoji button, as a non-mobile user hovers over the world map, this pre-plotting might help trip planners with their travel options, should air travel be part of their interest, in the same way it is an option up at Google Directions in our changedcountries.phpweb application you can also try below. The overlay scenario now reads …
document.body (now with the new onmousemove=airportplot(event); event logic) lowest level …
overlayed by HTML canvas element plotted with world country linework … now including …
overlayed by HTML canvas element dedicated to nearest airport plotting …
<canvas id=myacanvas height='180' width='360' style='background-color:transparent;z-index:55;display:inline-block;position:absolute;top:0px;left:0px;'></canvas>
overlayed by HTML img (transparent image) element and its associated image map area elements … and today we add into the mix …
HTML div hosting SVG elements overlaying initialized with “land” parts green infilled SVG at a mid range z-index (only as well as when called upon) individual GeoJson entities overlay
… worked by new (sometimes Ajax) Javascript code …
function inarray(needle, haystack) { // thanks to https://stackoverflow.com/questions/784012/javascript-equivalent-of-phps-in-array
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle) return true;
}
return false;
}
function stateChangeda() {
if (zhra.readyState == 4) {
if (zhra.status == 200) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
var onepixelequals=izoom;
var bts=zhra.response.split('.src + ' + String.fromCharCode(39));
if (eval('' + bts.length) > 1) {
for (var ijh=1; ijh<bts.length; ijh++) {
var vs=eval(eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))) +
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top))));
if (!inarray(vs,vsll)) {
vsll.push(vs);
drawaac(
eval(eval(eval(-topllong + eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[1])) * onepixelequals) + eval(0 * eval(rectis.left))),
eval(eval(eval(topllat - eval(bts[ijh].split(String.fromCharCode(39))[0].split('[')[1].split(',')[0])) * onepixelequals) + eval(0 * eval(rectis.top)))
);
}
}
}
answered=true;
}
}
}
function naira(klat, klong) {
if (answered && doair) {
answered=false;
zhra = new XMLHttpRequest();
zhra.onreadystatechange=stateChangeda;
zhra.open('get', '/HTMLCSS/intair.php?num=6&lat=' + klat + '&long=' + klong, true);
zhra.send(null);
}
}
function airportplot(e) {
if (answered) {
var rectis=null; //document.body.getBoundingClientRect();
var blat=0, blong=0;
var topllong=-180.0;
var topllat=90.0;
onepixelequals=eval(0.0 + eval(1.0 * izoom));
e = e || window.event;
e.preventDefault();
if (e.touches) {
if (e.touches[0].pageX) {
naira(eval(-rectisleft + e.touches[0].pageX), eval(-rectistop + e.touches[0].pageY)); //if (drawac(eval(-rectisleft + e.touches[0].pageX), eval(-rectistop + e.touches[0].pageY))) e = e; }
} else {
rectis=document.body.getBoundingClientRect();
naira(eval(-rectis.left + e.touches[0].clientX), eval(-rectis.top + e.touches[0].clientY)); //if (drawac(eval(-rectis.left + e.touches[0].clientX), eval(-rectis.top + e.touches[0].clientY))) { e = e; }
}
} else if (e.pageX || e.pageY) {
blat=eval(eval(eval(topllat * onepixelequals - eval(-rectistop + e.pageY) * 1)) / onepixelequals);
blong=eval(eval(eval(topllong * onepixelequals + eval(-rectisleft + e.pageX) * 1)) / onepixelequals);
if ((blat >= -90.0 && blat <= 90.0) && (blong >= -180.0 && blong <= 180.0)) {
naira(blat, blong); //if (drawac(eval(-rectisleft + e.pageX), eval(-rectistop + e.pageY))) { e = e; }
}
} else {
rectis=document.body.getBoundingClientRect();
naira(eval(-rectis.left + e.clientX), eval(-rectis.top + e.clientY)); //if (drawac(eval(-rectis.left + e.clientX), eval(-rectis.top + e.clientY))) { e = e; }
}
}
}
// ... and extended document.body onload event logic has added, up near its top ...
elema = document.getElementById('myacanvas');
contexta = elema.getContext('2d');
add interfacing functionality to the excellent Google Directions part of Google Maps, perhaps to help with Trip planning, or even just to associate a Placename with a latitude and longitude as clicked by the user, via the very simple URL arrangement … https://www.google.com/maps/dir/[decimalLatitudeDegrees]/[decimalLongitudeDegrees]
… helped out by new Javascript functions …
var lastlats=[], lastlongs=[], lastlat=-99.0, lastlong=-99.0, thislat=0.0, thislong=0.0;
function preface(inblurb) {
var extras='';
var outblurb=inblurb;
if (Math.abs(eval('' + lastlat)) > 0.0 || Math.abs(eval('' + lastlong)) > 0.0) {
if (Math.abs(eval('' + lastlat)) <= 90.0 && Math.abs(eval('' + lastlong)) <= 180.0) {
extras=' Add G for Google Directions between (' + lastlat + ',' + lastlong + ') to (' + thislat + ',' + thislong + ') and spaces (also more trip legs) to hashtag navigate to Google Charts later. ';
}
}
return extras + outblurb;
}
function alats(inlat) {
if (inlat == 0 && lastlats.length == 0) { inlat=inlat; } else { lastlats.push(inlat); }
return inlat;
}
Onto yesterday’s GeoJson World Countries TimeZone Times Tutorial GeoJson World Countries web application’s capabilities we want to add zooming, that doesn’t rely on web browser functionality (which continues to work). With that in mind we create a new emoji ( 🔎 ) 🔎 link, with this onclick event code …
var jzoom=1.0, izoom=location.search.split('zoom=')[1] ? eval(decodeURIComponent(location.search.split('zoom=')[1].split('&')[0])) : 1.0;
… to multiply the webpage zoom factor in a programmatical way. To acheive this, we have a two way approach (as you might have surmised from above) …
for mobile, the logic is easier by introducing a new meta name=viewport …
<meta id="myviewport" name="viewport" content="width=device-width, initial-scale=1, minimum-scale=0.1, maximum-scale=8, user-scalable=yes" >
… tag … while …
for non-mobile we needed to realize that event.pageX and event.pageY co-ordinates grow in proportion to the zoom factor, and that better latitude and longitude determining lines of code would go …
function canvasclick(e) {
var rectis=document.body.getBoundingClientRect();
var topllong=-180.0;
var topllat=90.0;
onepixelequals=eval(0.0 + eval(1.0 * izoom));
//document.title='canvasclick';
e = e || window.event;
e.preventDefault();
if (e.touches) {
if (e.touches[0].pageX) {
//lastl='Longitude,Latitude coordinates are ' + eval(topllong + eval(-rectis.left + e.touches[0].pageX) * onepixelequals) + ',' + eval(topllat - eval(-rectis.top + e.touches[0].pageY) * onepixelequals);
if (drawc(eval(-rectisleft + e.touches[0].pageX), eval(-rectistop + e.touches[0].pageY))) {
thislat=eval(topllat - eval(-rectistop + e.touches[0].pageY) * onepixelequals);
thislong=eval(topllong + eval(-rectisleft + e.touches[0].pageX) * onepixelequals);
//console.log('rectistop=' + rectistop + ' and rectisleft=' + rectisleft + ' and rectisy=' + rectisy + ' and thislat=' + thislat);
document.getElementById('nearestif').src='/PHP/tz_places.php?place=&latitude=' + encodeURIComponent('' + eval(topllat - eval(-rectistop + e.touches[0].pageY) * onepixelequals)) + '&longitude=' + encodeURIComponent('' + eval(topllong + eval(-rectisleft + e.touches[0].pageX) * onepixelequals)) + '&ntztontz=y';
}
} else {
Some readers might be aware of our “theory regarding adverbs” and “web applications” on the net …
the most catered for adverb relates to the “where of life” … and the second banana is …
the “when of life”
… and, further to yesterday’s GeoJson World Countries SVG Overlay Safari Error Tutorial‘s emphasis on the “where of life”, today we add in a bit of the “when of life”, something right down the line of the remit of TimeZone talents.
Seriously though, a lot of us dream of the rest of the world on a world map, and wonder what time it is in other parts of the world. Phone call to relatives? A reminder SMS call? Email a game collaboration? It could all be part of life’s rich tapestry!
The expresion of this, for us, today, improving the communications with our current GeoJsom World Countries web application, take the form of emoji clocks from the 12 hour clock example forms such as …
1 o’clock is 🕐 🕐
2 o’clock is 🕑 🕑
12 o’clock is 🕛 🕛
2:30 is 🕝 🕝
11:30 is 🕦 🕦
12:30 is 🕧 🕧
… to show in “prompt” and “confirm” popup windows, as well as Map Chart maps … via new Javascript functions …
Also, in these same places we add in Time Place country ISO-2 character code based emoji flags, adding to information and colour pizazz in the informational parts to the workings of our changedcountries.phpweb application you can also try below.
On discovering our first solution theory of turning yesterday’s mapsvg.js external Javascript work into an async piece of work made no difference to this situation, we surmised that the huge amount of content held in the Javascript (ie. client side) global variable appendtoinnerHTML was causing memory issues. We couldn’t shift much to do with the overall amount of “data” needing to be handled, in order to implement country SVG colour infilling, but we could shift the data from being …
client side (external) Javascript held … to, instead, (have that data) be (determined on the) …
server side PHP filling in the contents of our (relevant) HTML div id=svgd ahead of the document.body onload event timing …
<?php
$icnt=0;
function apptohtmstuff($coordsare, $origc) {
global $icnt;
$minl=-1;
$mint=-1;
$maxl=-1;
$maxt=-1;
$zysare=explode(',', $coordsare);
$svgcis='';
for ($ij=0; $ij<sizeof($zysare); $ij+=2) {
if ($minl < 0) {
$minl=$zysare[$ij];
$maxl=$zysare[$ij];
$mint=$zysare[1 + $ij];
$maxt=$zysare[1 + $ij];
} else {
if ($zysare[$ij] < $minl) { $minl=$zysare[$ij]; }
if ($zysare[$ij] > $maxl) { $maxl=$zysare[$ij]; }
if ($zysare[1 + $ij] < $mint) { $mint=$zysare[1 + $ij]; }
if ($zysare[1 + $ij] > $maxt) { $maxt=$zysare[1 + $ij]; }
}
}
…everywhere … and an idea we’d ditched yesterday of …
idea to pre-colour “land” parts of the world GeoJson map green (ahead of the document.body onload event) also came good (after causing problems yesterday)
… meaning now, “overlay” wise, we could say …
document.body lowest level …
overlayed by HTML canvas element plotted with world country linework …
overlayed by HTML img (transparent image) element and its associated image map area elements … and today we add into the mix …
HTML div hosting SVG elements overlaying initialized with “land” parts green infilled SVG at a mid range z-index (only as well as when called upon) individual GeoJson entities overlay
… and we (reckon we’ve) improved the colour coding user experience at the same time.
We noticed that tweaks in the changed …
var lastflagged='', appendtoinnerHTML='', waitplease=false; // used to make sure "area" element onclick code precedes any document.body onmousedown or ontouchdown code
… also lessened the burden on the client side by only asking any Javascript DOM command operations act on single HTML element at a time, not a whole swathe of hosted ones, in any operation.
What deducible data item needs to be determined for these Geo Charts to work? We need a way to deduce ISO-2 character country codes from the ISO-3 character codes existing in the GeoJson “countries.geojson” data from yesterday’s work. We happened upon the extremely generous mapping data webpage to help with these ISO-2 character deductions …
… in our image map area elements PHP creation code above. As you can see, extra “intelligence”, moving forward, is contained in area element global data attributes.
Geo Chart can involve emoji (🏠 &127968;) or image (SVG) circle based symbology for the “User Clicked Place” and nearby TimeZone places respectively …
all these symbols can be clicked to open popup windows containing TimeZone Place Wikipedia webpages of relevance …
an emoji national flag (eg. Zambia “ZA” could be used to derive 🇿🇦 🇿🇦 flag emoji) derived from those ISO-2 character codes can supplement the GeoJson (more ISO-3 character based) names presented in the underlying data, in the Geo Chart title …
contextualizing the accompanying Map Chart … and …
vice versa regarding hovering over symbology (which works on Map Chart, but not Geo Chart) …
within the Map Chart iframe a “Geo” link can glean a “zoomed out” world Geo Chart view of your TimeZone places
Know your GeoJson! Yes, pretty obviously, any two GeoJson datasets might display the same in that “map plotting” sense, but one might have different and/or more “intelligence” than the other. Often, an XML has more “intelligence” than equivalent HTML (barring the use of global data attributes, that is), as today’s Corollacorollary.
Luckily for programmers all over, the organization of TimeZones has had an International flavour in its development and maintenance. As such, given the “purely coastline” GeoJson data involved in our fledgling PHP web application of yesterday’s GeoJson World Coastline Primer Tutorial a useful arrangement for improvement involves …
document.body onclick event co-ordinates … able to be converted to …
longitude, latitude (easily, only because of our simplistic map projection, of course) … onfed to …
… can have us helping out your curious web “clicking” user with the 3 nearest TimeZone places, as a reference as to where they are “clicking” in the world.
in a discrete click methodology of interest, you could adopt a non-mobile “onmousedown” logic set that does not get interfered with by a mobile “ontouchdown” logic set (perhaps leaving “onclick” event, which both non-mobile and mobile both recognise, for another event logic role) … and …
neither will interrupt the mobile gestures associated with swiping and pinching, which refer to the events “ontouchstart” and “ontouchend” at either end of their lifespan
And so, we arrive at a long planned for tilt at Image Map functionality that we often turn to Mobilefish.Com and its excellent Image Map Creation to help us out … but not today?! Why not? We have a funny set of needs, they being …
our Image Map’s image will have a variable set of width x height dimensions …
our Image Map’s image will be transparent
our Image Map needs to have a hole left aside inside it where the functionality that originally existed (and pointed to WordPress Blog content like you are reading), is still working
… so from that … let’s see … we get The Four TopsPipsP’s (in relation to lemon trees … tee hee).
Well, to make Moon Angles and Astronomy Helper web applications work on AlmaLinux we needed to attend to a couple of install matters …
install the Python package manager Pip via (the AlmaLinux PHP dnf package manager) …
dnf install python3-pip.noarch
install the Python module, helping out with Astronomy matters, called PyEphem via …
sudo pip install pyephem
… to be in a position to progress, and then add a check for existence of /usr/bin/python (for AlmaLinux) in preference to /usr/local/bin/python3.3 (for CentOS) as the final measure needed to start getting results back to any PHP overseers …
PHP/Javascript/HTML and Python PyEphem Moon Angle Tutorial
A long time ago now we presented PHP/Javascript/HTML Moon Angle Tutorial but now we feel is a good time for it to get a makeover. Why is that? Well, we have the relatively new discovery of the very useful Python PyEphem module to thank for that.
As far as the new version goes we now offer a Moon Angle “time of transit (and relative to now)” calculation, which we think will be of more use to users.
The Moon Angle at Transit calculations again involve the Sublunary Point as the position on Earth directly above which is Moon is located. Add in the Python PyEphem work and some more terminology that may interest you could involve …
The Moon Angle web application live run, which we welcome you to try, has the underlying PHP moon_angle_now_at.php that supervises the Python exemplied above, and which featured these changes to make this happen.
Here is a tutorial that calculates Noon Moon Angles from Earth via the entry of Latitude and Longitude. The calculation of noon moon angles uses the concept of Sublunary Point, which is explained in the quote from Wikipedia below.
The sublunary point (Latin sub-lunar, under the moon ‘, from Latin) is the one place on earth where the moon in exactly the zenith is. He is the point where the line connecting the centers of the Earth and Moon intersects the Earth’s surface. The point is a common auxiliary point to observe the Moon in the celestial mechanics and astronomical phenomenology , and in particular the theory of the tides , as well as the theory of eclipses .
The calculation of the point corresponding to the determination of the geocentric coordinates of the Moon, it has the same longitude and latitude , as the moon astronomical length and width has – both are denoted by φ and β.
The Javascript embellishments in this tutorial mainly revolve around:
Here is a link to a live run. (The way it changed on 1/12/2013 to have a dropdown of placenames as extra functionality will be explained in a tutorial called PHP/Javascript/HTML Geographical Placename Integration Tutorial on 3/12/2013.)
Here is a link to some downloadable PHP programming source code which you may want to rename to moon_angle_now_at.php
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.
If this was interesting you may be interested in this too.