Hello world, leafletjs

In this post we'll explore a "hello world" using the open source leafletjs library.

Step by Step:

  1. Include Leaflet: The HTML code includes the Leaflet CSS and JavaScript files from a CDN.
  2. Create a Map: The JavaScript code creates a map instance and sets its initial view using L.map('map').setView([latitude, longitude], zoom).
  3. Add Tile Layer: The L.tileLayer method adds a tile layer to the map, which provides the base map imagery. In this case, we're using OpenStreetMap tiles.
  4. Add a Marker: The L.marker method creates a marker at a specified location ([51.5020469956198, -0.14175590508964123]) and adds it to the map.
  5. Add a Popup: The bindPopup method attaches a popup to the marker, which will appear when the marker is clicked.

Remember:

  • Replace the coordinates in setView and L.marker with your desired locations.
  • Explore Leaflet's extensive documentation for more features and customization options: https://leafletjs.com/

Code

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Leaflet Map Hello World</title>
    <link
      rel="stylesheet"
      href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
    />
  </head>
  <body>
    <div id="map" style="height: 400px"></div>
    <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
    <script>
      // JavaScript code will go here
    </script>
  </body>
</html>



Javascript

var map = L.map("map").setView([51.505, -0.09], 13); // Set initial center and zoom

L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution:
    '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);

// Add a marker
L.marker([51.5020469956198, -0.14175590508964123])
  .addTo(map)
  .bindPopup("Hello world!")
  .openPopup();


Final

<!DOCTYPE html>
<html>
  <head>
    <title>Leaflet Map Hello World</title>
    <link
      rel="stylesheet"
      href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
    />
  </head>
  <body>
    <div id="map" style="height: 400px"></div>
    <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
    <script>
      var map = L.map("map").setView([51.5020469956198, -0.14175590508964123], 13); // Set initial center and zoom

      L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        attribution:
          '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
      }).addTo(map);

      // Add a marker
      L.marker([51.5020469956198, -0.14175590508964123])
        .addTo(map)
        .bindPopup("Hello world!")
        .openPopup();
    </script>
  </body>
</html>

Popular posts from this blog

Google Bard writing code for drawing maps via Google Maps

Hello