32 :: Using the Leaflet API to learn about Literals

I’m trying to break out of my bad habit of cutting and pasting code and then swapping out variables until I get the result I want.  So I’m slowing my work down. This makes me feel like I’m being less productive but I know that this work is an investment that hopefully should pay off in future endeavours. Hopefully.

Here’s an example of my new workflow.  Today I’m working through Leaflet’s API documentation to see if I can manipulate the basic example that I worked on some days ago.

I start reading the basic guide:

Every time something happens in Leaflet, e.g. user clicks on a marker or map zoom changes, the corresponding object sends an event which you can subscribe to with a function. It allows you to react to user interaction:

function onMapClick(e) {
    alert("You clicked the map at " + e.latlng);
}

map.on('click', onMapClick);

Each object has its own set of events — see documentation for details. The first argument of the listener function is an event object — it contains useful information about the event that happened. For example, map click event object (e in the example above) has latlng property which is a location at which the click occurred.

So I check out the (wonderful) documentation and start at the beginning with L.map : the central class of the API.  I know from previous reading that JavaScript is a class-less language and so this must be  some sort of pseudo-class that evidently I will one day have strong opinions about. But, for the time being, I decide to move on (after reading up on method chaining).

I look at the basic constructor section which reads:

Instantiates a map object given a div element (or its id) and optionally an object literal with map options described below.

I stop and wonder what an ‘object literal’ is and then do more reading. I find that Mozilla’s JavaScript Developer’s Guide is really useful and I try to absorb what I can.   Then I try to implement a simple literal: I try to make my basic map undraggable. But I don’t know where the code is supposed to go so I try a bunch of places and it refuses to work.

So I fall back to my old habit of searching for similar code online and in short order, I figure out where the literals are to be. I also learn that I made the mistake of using an ‘=’ instead of ‘:’ in setting the option.  But in the end, the code works!

var map = L.map('map', {dragging:false}).setView([42.306,-83.068], 16) ;

Bouncing back and forth from theory to application is definitely not the most efficient way of learning, but it’s the only way that is working for me at the moment.

It has inspired me to take a Computer Science course in the fall (my second!) that is dedicated to Algorithms. Hopefully, I’ll be able to hack my learning to something more efficient.

Leave a Reply

Your email address will not be published. Required fields are marked *