PHP: Convert a Geolocation (Latitude / Longitude Coordinates) to a Timezone identifier

Part of a PHP project I’m working contains a list of sites/buildings. For each site/building we monitor some data, for example its energy usage.

We decided that we wanted to generate a daily/weekly/monthly reports of the data, by aggregating the datapoints. To not have to do this on the fly – using a typical GROUP BY query clause – we decided to pre-calculate and store the aggregated numbers on a daily basis.

As our sites/buildings are spread across the globe – and thus timezones – we have to use the location’s daily window to do our calculations. Unfortunately we don’t didn’t store the timezone for a location. But since we do keep track of its location – using a WGS84 latitude-longitude pair – it should be possible to derive its timezone, right?

Right! On StackOverflow I found this little snippet that does the job:

function get_nearest_timezone($cur_lat, $cur_long, $country_code = '') {
    $timezone_ids = ($country_code) ? DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $country_code)
                                    : DateTimeZone::listIdentifiers();

    if($timezone_ids && is_array($timezone_ids) && isset($timezone_ids[0])) {

        $time_zone = '';
        $tz_distance = 0;

        //only one identifier?
        if (count($timezone_ids) == 1) {
            $time_zone = $timezone_ids[0];
        } else {

            foreach($timezone_ids as $timezone_id) {
                $timezone = new DateTimeZone($timezone_id);
                $location = $timezone->getLocation();
                $tz_lat   = $location['latitude'];
                $tz_long  = $location['longitude'];

                $theta    = $cur_long - $tz_long;
                $distance = (sin(deg2rad($cur_lat)) * sin(deg2rad($tz_lat))) 
                + (cos(deg2rad($cur_lat)) * cos(deg2rad($tz_lat)) * cos(deg2rad($theta)));
                $distance = acos($distance);
                $distance = abs(rad2deg($distance));
                // echo '<br />'.$timezone_id.' '.$distance; 

                if (!$time_zone || $tz_distance > $distance) {
                    $time_zone   = $timezone_id;
                    $tz_distance = $distance;
                } 

            }
        }
        return  $time_zone;
    }
    return 'unknown';
}

Usage is as follows:

// timezone for one NY co-ordinate
echo get_nearest_timezone(40.772222,-74.164581);

// more faster and accurate if you can pass the country code 
echo get_nearest_timezone(40.772222, -74.164581, 'US');

🍻 Here’s to copying-and-pasting from StackOverflow!

On a related note: Falsehoods programmers believe about time and time zones is worth a read, especially if you’ve already dealt with time and timezones.

Song Exploder Episode 187: Apparat – Goodbye

This episode from Song Exploder gives us a good insight in how Goodbye by Apparat came to be.

The Netflix original series Dark debuted in December 2017. It’s a really mysterious, mind-bending German science fiction show with a unique tone. A big part of that tone is announced every episode with the music in the show’s opening title sequence. It’s the song “Goodbye,” by German electronic artist Apparat, the solo project of Sascha Ring. This song actually came out years ago, on the 2011 Apparat album The Devil’s Walk. Since then, before it was used as the theme song for Dark, it’s been featured in a bunch of films and commercials, and notably, in the Season 4 finale of Breaking Bad.

Back in the day I was really delighted when I heard it in the Season 4 finale of Breaking Bad as it complemented the camerawork, montage, and story.

It is a bit of a pity that the track is now known only as “The theme from Dark”, taking away the focus from Apparat’s other work which is also really good. How good? Let me put it this way: his album “The Devil’s Walk” (featuring Goodbye) didn’t make it into my top 10 of played albums over time for no reason 😉

The Sound of Silence

If you’re a regular reader of bram.us you might have noticed that I haven’t posted anything here during the past month. In short: I’ve been busy with many (personal) things that needed my attention. Here’s a few of the things that kept me from blogging …

Public Speaking

With COVID-19 many conferences have switched to an online format. With this came the opportunity to speak at rather distant conferences, which wouldn’t have been possible before. I’m honoured to have been able to speak at JS VidCon, JS RemoteConf, JSNation Live, and JSConf.be.

Some of those events worked with prerecorded talks, while others were done live. It was always a mix and match of sites and apps to use (Crowdcast, Zoom, Wirecast, Run the World, Slack, Discord, etc) all while I remained at home. Easy, although I’m kinda missing the personal connections one can make at IRL conferences.


Me, speaking at home #JSNationLive

Prepping for those conferences took some time, but thankfully I could reiterate on my ESNext: Proposals to look forward to talk. As the talk has grown over the past two years I’ve come rather fluent at it, and can easily adapt it to both short and long formats. There’s another rather big conference planned this mid-July, but I can’t talk about it just yet 😉

~

Life as a family of 3 + 2

Tomorrow it will be exactly five months ago that my youngest son Noah was born. If you’re a parent yourself I shouldn’t tell you how hard it is to have a baby in the house, especially if that baby only sleeps for short periods of time (bursts of 30 minutes during the day, 3 to 4 hours at night). He’s a very pleasant and happy baby to have around, yet the only thing we wish for is to get a few more hours of unbroken sleep. It’s really hard to focus and think when in Zombie mode 😵

We’ve also had some issues with getting his formula right, as he tends to be rather sensitive (but not allergic as the doctor said) to cow milk, but after four months of trial and error I think we finally got it right.


Noah, June 2020

My oldest son Finn (aged 11) and my daughter Tila (aged 9) live with us every other week, as they spend the other week at their mums place. When they’re at home with us, they really are “at home” as all the schools in Belgium had switched to a format called “pre-teaching” because of COVID-19: the kids don’t go to school physically, and are required to finish a set of daily tasks (both online and offline) at home. I’m blessed that I have quite smart and standalone children by now, yet my oldest son Finn is quite the slacker to be honest … always reminding him to get started, double checking his work, etc. is quite time consuming to be honest.


Ellie + Finn + Tila, May 2020

Thankfully schools have reopened their doors just last week, so that’s a small load off of my shoulders. And oh, I’m very grateful that my daughter Tila also helps us with the baby when she’s around.

~

We bought a new house

Ever since (before) the birth of our son Noah we’ve been on the lookout for a new house to live in, as we need an extra bedroom for him to sleep in (right now he sleeps with us in our bedroom, as we don’t have a room for him). About a month ago my colleague Roel stumbled upon a house while biking and sent it over. One thing led to the other and before we knew we were talking with the bank about a new loan and everything that goes along with that. And yes, our bid got accepted so mid-September we’ll be moving house 🤩


Our new house, soon to be home

~

We’re about to sell our current house

As we will no longer be needing our current home — and we kinda rely on the money that we’ll get from selling it — I’ve been busy finishing up the list of home improvements that needed to be done. The biggest job on that list was finishing the drywall in our living room. After sitting there unfinished for nearly 5 years (😬) I – with the help of a friend – finally got to smoothing it out, putting up a wallpaper and painting the whole thing white.


Before and after

In order for the realtor who will be selling our house to start, they need some photos. To do so, we got a set of instructions (it’s in Dutch but you get the idea with the photos). As a result we’ve been cleaning out our closets and have been making trips to the local thrift shop and/or recycling depot . It’s crazy what one can collect over a period of 10 years time 😅

Our house is expected to go up for sale early July.

~

Work

In between all that I also tried to do some actual work. I’m still working on a long-term Monitoring platform / IOT project which we at vBridge started almost two years ago, doing mainly PHP and cloud-based things nowadays. I try to sneak in some JS from time to time (both client- and serverside), but it’s quite limited to be honest.

As I’m currently the only web developer on the project (*), I’m a bit overbooked: refactoring a huge part of the app while also squashing bugs (if one were to be found) and catching deadlines of new promised features is quite a lot of juggling that needs to be done. This week I was finally able to finish up one of two planned refactors, so I can finally focus on new features again.

(*) Although we haven’t announced it officially yet, we’re on the lookout for good people to join our team. We’re basically looking for a web developer with preferably a PHP background and an interest in cloud development. Our policy is to hire for talent+attitude and train for skill, so don’t worry if you think you lack certain skills.

JavaScript Yellow

Back in November I was invited to speak at Full Stack Europe 2019. At the conference I was scheduled to do a pre-conference workshop on React and a lightning talk named “JavaScript Yellow”. Last week the video said talk got released:

References:

Thanks again to the organisers for having me 🙂

😅 In the end, I ended up doing a full talk on ESNext: Proposals to look forward to too, as one of the originally planned speakers unfortunately couldn’t make it after all.

How To Crash An Airplane

A talk by Nickolas Means, as recorded at Fronteers 2018 (which I attended).

On July 19, 1989, United Airlines Flight 232 was en route to Chicago when a mechanical failure caused the plane to become all but uncontrollable. In this unsurvivable situation, the flight crew saved more than half of those onboard. How did they do it?

Flight crews and software teams have a lot in common, and there’s much we can learn from how the best crews do their jobs. What can we learn from the story of United 232? While this talk won’t earn you your pilot’s license, you’ll definitely come away with some fresh ideas on how to make your team even more amazing.

If the audio is bothering you (there seems to be a bit of an audio loop in there?), there’s this rendition from 2016 that you might enjoy instead:

Recoil – An Experimental State Management Library for React

Recoil is the State Management Library for React they use at Facebook.

Recoil lets you create a data-flow graph that flows from atoms (shared state) through selectors (pure functions) and down into your React components. Atoms are units of state that components can subscribe to. Selectors transform this state either synchronously or asynchronously

Best to watch the talk from React Europe 2020 embedded above. It clearly explains why Recoil come to exist, and when & how to use it.

If you’ve ever used MobX it might all sound a bit familiar. This Twitter Thread by the MobX author is worth a quick read.

Recoil →

SPACEX – ISS Docking Simulator

This simulator will familiarize you with the controls of the actual interface used by NASA Astronauts to manually pilot the SpaceX Dragon 2 vehicle to the International Space Station. Successful docking is achieved when all green numbers in the center of the interface are below 0.2. Movement in space is slow and requires patience & precision.

My inner space-geek rejoices! 🤓

SPACEX – ISS Docking Simulator →

Don’t charge your MacBook Pro from the left side. Use the right side.

Ever since September 2019 I had this issue with my MacBook Pro where kernel_task would sometimes spike up to > 1000% (!) CPU load and drain my battery – even while connected to a charger.

Upon disconnecting the charger, the load would drop back to normal levels. But on reconnecting kernel_task would be at it again.

~

A few weeks ago I saw this tweet float by:

And yes, that totally explained my problem. As the linked StackExchange thread mentions:

High CPU usage by kernel_task is caused by high Thunderbolt Left Proximity temperature, which is caused by charging and having normal peripherals plugged in at the same time.

So the fix is simple: don’t charge your MacBook from the left side but use the right side.

Now this is not something I’d expect from a +$3000 costing machine but as the late Steve Jobs would say: “You’re holding charging it wrong” … ¯\_(ツ)_/¯

In Apple’s support article on it the function of kernel_task itself is explained in detail:

One of the functions of kernel_task is to help manage CPU temperature by making the CPU less available to processes that are using it intensely. In other words, kernel_task responds to conditions that cause your CPU to become too hot, even if your Mac doesn’t feel hot to you. It does not itself cause those conditions. When the CPU temperature decreases, kernel_task automatically reduces its activity.

So it’s basically kernel_task trying to steal CPU cycles from other processes, so that those processes don’t overheat the system.

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would always put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

Chrome DevTools Pong – A game to play inside the Chrome DevTools

Move over Chrome Dino Game! Now you can play Pong inside the Chrome DevTools.

Chrome DevTools Pong →

Spoiler: How it works

In case you were wondering: it’s a regular Pong game, but with the elements visually hidden (opacity: 0;) so that they only show up in the DevTools’ Layers Panel.

So simple, that becomes awesome!