Skip to content

Latest commit

 

History

History
95 lines (80 loc) · 2.68 KB

leaflet-openstreetmap.md

File metadata and controls

95 lines (80 loc) · 2.68 KB

Leaflet OpenStreetMap

Image of Leaflet OpenStreetMap

Tutorial

  1. Download files from Leaflet here and enqueue JavaScript & CSS by following Enqueue Scripts & CSS
  2. Create a Div and:
    • Set idmap
    • Set width100%
    • Set height300px
    • Add JavaScript
       var latitude = 51.505;
       var longitude = -0.09;
       var zoom = 13;
      
       // Initialize the map
       var map = L.map('mapid').setView([latitude, longitude], 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 markers, circles and polygons

Marker

var marker = L.marker([latitude, longitude]).addTo(map);

Circle

var circle = L.circle([latitude, longitude], {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5,
    radius: 500
}).addTo(map);

Polygon

var polygon = L.polygon([
    [latitude_1, longitude_1],
    [latitude_2, longitude_2],
    [latitude_3, longitude_3]
]).addTo(map);

Add text to marker

Image of Leaflet Map Marker Text

marker.bindPopup("<b>Hello world!</b><br>I am a popup.");

You can add .openPopup(); if you want the text to immediately open on load.
You can add any HTML-code so you can for e.g. insert images like this
Image of Leaflet Map Marker Example

Markers with custom icons

Image of Leaflet Custom Marker

var customIcon = L.icon({
    iconUrl: 'https://someurl.com/image.png',
    iconSize: [45, 45]
});

var marker = L.marker([latitude, longitude], {icon: customIcon}).addTo(map)

Events

function onMapClick(e) {
    alert("You clicked the map at " + e.latlng);
}

map.on('click', onMapClick);

Make sure to read OpenStreetMaps policy on tile-usage!

  • Find the policy here