leafleat-marker-svg-and-legend

by tomik23

HTML

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

CSS

html,
body {
  height: 100%;
  margin: 0;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji;
}

#map {
  width: 100%;
  height: 100%;
}

.legend {
  background: #fff;
  padding: 8px;
  border-radius: 5px;
}

.legend .row {
  display: flex;
  line-height: 30px;
}

.legend i {
  display: block;
  width: 30px;
  height: 30px;
  margin-right: 5px;
}

JavaScript

// MAP

const map = L.map('map').setView([52.237049, 21.017532], 13)

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)

// LEGENDS

const legend = L.control({
  position: 'bottomright'
})

const div = L.DomUtil.create('div', 'legend')
const color = ['F7FADA', 'B6E1C9', '72C7D4', '64A1CC', '5F6CB3']
const label = ['2-12.5', '12.6-16.8', '16.9-20.9', '21-25.9', '26-plus']
const rows = []

legend.onAdd = function(map) {
  color.map((item, index) => {
    rows.push(`
        <div class="row">
          <i style="background: #${item}"></i>${label[index]}
        </div>  
    `)
  })
  div.innerHTML = rows.join('')
  return div
}

legend.addTo(map)

// MARKERS

const markers = [
  [52.228956, 21.003799],
  [52.258071, 20.986805],
  [52.242728, 21.041565],
  [52.234213, 21.029034],
  [52.251661, 21.003456]
]

function colorMarker(color) {
  const svgTemplate = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" class="marker">
      <path stroke="#000000" fill="#${color}" d="M15.938 32S6 17.938 6 11.938C6 .125 15.938 0 15.938 0S26 .125 26 11.875C26 18.062 15.938 32 15.938 32zM16 6c-2.209 0-4 1.791-4 4s1.791 4 4 4 4-1.791 4-4-1.791-4-4-4z"/>
    </svg>`

  const icon = L.divIcon({
    className: 'marker',
    html: svgTemplate,
    iconSize: [40, 40],
    iconAnchor: [12, 24],
    popupAnchor: [7, -16]
  })

  return icon
}

markers.map((marker, index) => {
  const lat = marker[0]
  const lng = marker[1]
  L.marker([lat, lng], {
    icon: colorMarker(color[index])
  }).bindPopup(`color: #${color[index]}<br>${label[index]}`).addTo(map)
})

// GET latlng onClick

// map.on('click', function (e) {
//   console.log(e.latlng)
//   alert(e.latlng)
// })