Request Dev Services ยป

theDevTip.com

Create a custom ‘Travel Map’ w/ Leaflet.js (Demo!)

In this demo I’ll illustrate ‘how’ to use and customize the Leaflet.js library to create cool interactive maps for the web. Here, I’ll build a “Travel Map” with custom pin icons, custom pin locations, and on click ‘overlays’ that illustrate places I have traveled and lived with a complete demo!


After loading your external leaflet.js dependencies; implement the HTML mark-up that acts as a placeholder for the invoked Map.

<div id="map"></div>

Next: Initialize the initial map and load position. (on window load)

  // center of the map
  var center = [38.9072, -77.0369];

  // Create the map
  var map = L.map('map').setView(center, 3);

Now: Call the OSM Layer, and set maxZoom

  // Set up the OSM layer
    L.tileLayer(
     'http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
       maxZoom: 18
  }).addTo(map);

Then: Set the custom icon specifications, and imagery.

    var RedIcon = L.Icon.extend({
      options: {
        shadowSize:   [50, 64],
        iconAnchor:   [5, 25],
        shadowAnchor: [4, 62],
        popupAnchor:  [0, 0]
      }
    });

    var redPin = new RedIcon({
        iconUrl: 'http://website.com/SweetIcon.png',
      className: 'redPin',
    });

And: Set your pins! Firstly, set the ‘home pin’. i.e.

    L.marker(center, {icon: redPin}).bindPopup("Home: Washington D.C.").addTo(map);

Now: Set your other pins via coordinates! i.e.

    // Carib
    L.marker([19.7509, -70.4144], {icon: redPin}).bindPopup("Traveled: Cabarate, D.R.").addTo(map);
    L.marker([18.3402, -67.2499], {icon: redPin}).bindPopup("Traveled: Rincon, P.R.").addTo(map);
    L.marker([19.3222, -81.2409], {icon: redPin}).bindPopup("Traveled: Grand Cayman, UK").addTo(map);


Click here to check out the ‘Full Demo’, and see it in action!


“Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 38 KB of JS, it has all the mapping features most developers ever need.”

About the Author
Cameron Cashwell Web Developer
I build websites, web apps, and software. Wanna work together? Let's chat about your project!

Leave a Reply

avatar
  Subscribe  
Notify of