Replacing Google Maps with Leaflet, Part 1

Google’s massive changes to their pricing structure for use of the Google Maps API has sent many people (myself included) looking for alternatives. I’ve been having a lot of success with Leaflet, and enjoying the learning process along the way!

One of my first goals was to replace the Google Maps in use on our Campus Buildings pages. Previously I was using the “Embed API,” which is basically just an iframe with its src set to call Google Maps with whatever parameters you want for your map. I thought it would be simplest to set up something analogous as a drop-in replacement. So I created a separate file, we’ll call it leaflet-map.html that I could embed via an iframe and to which I could pass parameters.

Of the five projects I’ve redone in Leaflet, this is the simplest. The code is just this:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Leaflet Map for Campus Buildings Template</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script data-require="jquery@3.1.1" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <!-- Load Leaflet's .js and .css from CDN -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.1/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>
    
    <style>
        html,
        body,
        #map {
          height: 100%;
          width: 100%;
          margin: 0;
          padding: 0;
        }
      </style>

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

    <script>
        ///////////////////////////
        // Collect and parse parameters
        ///////////////////////////        
        var params = {};
        window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
              params[key] = value;
        });         

        ///////////////////////////
        // Set defaults
        ///////////////////////////  
        var lat = 34.4797, 
            lng = -113.336,
            zoom = 15;

        ///////////////////////////
        // Assign values from parameters, if applicable
        ///////////////////////////                
        if (params.coords) {
          const input = params.coords;
          [lat, lng] = input.split(','); 
        }

        if (params.zoom) {
          zoom = params.zoom;
        }

        ///////////////////////////
        // Create the map
        ///////////////////////////  
        var map = L.map('map').setView([lat, lng], zoom);
                
        ///////////////////////////
        // Set our basemap (only one is needed for this app)
        ///////////////////////////          
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
        }).addTo(map);

        ///////////////////////////
        // Add a marker at the specified latitude and longitude
        ///////////////////////////  
        var marker = L.marker([lat, lng]).addTo(map);
       
    </script>  

</body>
</html>

I can then simply embed this by using the following code in my app: <iframe src="[https://mysite.com]/leaflet-map.html?coords=&zoom=18"></iframe>

is a Handlebars expression whose data originates from a Google Sheet; see for more information. To make this map work for your use case, simply replace with whatever will give you your coordinates in a string. If you have latitude and longitude stored separately, even better: you can skip the string splitting and just refer to them by params.lat and params.lng.

Categories:

Updated: