Leaflet: Add Markers

Add Markers to a Leaflet map

by Geoapify

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.js"></script>
<div id="my-map"></div>

CSS

html,
body,
#my-map {
  width: 100%;
  height: 100%;
  margin: 0;
}

.popup-container {
  font-family: Arial, sans-serif;
  line-height: 1.5;
}

.popup-title {
  margin: 0 0 5px;
  font-size: 14px;
  font-weight: bold;
  color: #2a2a2a;
}

.popup-address {
  font-size: 12px;
  color: #444;
}

JavaScript

// Leaflet has native support for raster maps, So you can create a map with a few commands only!

// The Leaflet map Object
const map = L.map("my-map").setView([48.1500327, 11.5753989], 10)

// The API Key provided is restricted to JSFiddle website
// Get your own API Key on https://myprojects.geoapify.com
const myAPIKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a"

// Retina displays require different mat tiles quality
const isRetina = L.Browser.retina

const baseUrl =
  "https://maps.geoapify.com/v1/tile/osm-bright/{z}/{x}/{y}.png?apiKey={apiKey}"
const retinaUrl =
  "https://maps.geoapify.com/v1/tile/osm-bright/{z}/{x}/{y}@2x.png?apiKey={apiKey}"

// Add map tiles layer. Set 20 as the maximal zoom and provide map data attribution.
L.tileLayer(isRetina ? retinaUrl : baseUrl, {
  attribution:
    'Powered by <a href="https://www.geoapify.com/" target="_blank">Geoapify</a> | © OpenStreetMap <a href="https://www.openstreetmap.org/copyright" target="_blank">contributors</a>',
  apiKey: myAPIKey,
  maxZoom: 20,
  id: "osm-bright",
}).addTo(map)

// Add a marker with a custom icon generated by Geoapify Marker Icon API
const markerIcon = L.icon({
  // URL to the custom PNG icon with parameters:
  // - type=awesome: uses Font Awesome marker shape
  // - color: marker background color
  // - size: total icon height in pixels
  // - icon: Font Awesome icon name (e.g., "paw")
  // - contentSize: size of the icon inside the marker
  // - contentColor: color of the inner icon
  // - noWhiteCircle: removes white circle behind icon
  // - scaleFactor=2: generates retina-ready PNG
  iconUrl: `https://api.geoapify.com/v2/icon/?type=awesome&color=%23ffc3e8&size=60&icon=paw&contentSize=29&contentColor=%2334811a&noWhiteCircle&scaleFactor=2&apiKey=${myAPIKey}`,

  // Total size of the icon image (width, height in pixels)
  iconSize: [45, 66],

  // Anchor point of the icon (x, y), where the marker is "pinned" to the map
  // Set to bottom center...