Play with Front-end JavaScript (Map)

This week, we are asked to implement dark mode for the bridge-troll project.

After reading through the feature request, there’re several interesting things involved. Leaflet, an open-source JavaScript library for mobile-friendly interactive maps, looks totally awesome. While SunCalc is an open source JavaScript library for calculating sun conditions for the given location and time. And the Material icons are used to represent the marker on the map.

Let’s get started with forking and cloning the repo. Follow the ReadMe to run the app. All looks good, successfully getting my current location and also shown a bridge nearby (bridges are shown as locks).

Screen Shot 2018-03-19 at 4.48.47 PM.png
initial display (day mode)

Steps to follow:

A) show a new tile
Click me to find a leaflet provider. After choosing your preferred tile, update your code to use the new tile URL in the current map:

const tileUrl = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png';

B) makes it automatically
In order to accomplish it, we use SunCalc library to do the job. By calculating the Sunlight times, these two properties look promising to work on our logic sunsetStart✓ & sunriseEnd✓. All we need is just to compare the current time with them.

npm install suncalc --save

C) isolate the logic
It’s always a good idea to keep things modularized, which will make our life easier for future and increase readability. So our logic will probably end up like this in a file:

// theme.js

const SunCalc = require('suncalc');
let setMode = (lat, lng) => {
  // do your calculation
  SunCalc ...
};
module.exports = { setMode };

After enabling the auto switching, we also would like to update our material icons to the new tile. Currently, all the icons are specified in svg-marker.js and exported as const variables.

Instead of putting the logic inside the svg-marker.js file, we will continue using our theme.js as a wrapper to return the proper markers. Don’t forget to update any code utilizing the svg-marker.js.

D) clean-up
Run the following commands to style your code:

npm run eslint
npm run prettier

 

Screen Shot 2018-03-19 at 6.02.13 PM

After fixing any ESLint error, you’re good to go!


Link to my fix & the final result:

Screen Shot 2018-03-19 at 6.09.15 PM
dark mode

Note: for now, it only supports mode change on start-up, need to fix using EventEmitter for switching on the fly.