Skip to content

Instantly share code, notes, and snippets.

@typable
Last active Apr 28, 2021
Embed
What would you like to do?
Leaflet OSM

OpenStreetMap API

A Leaflet JS implementation to provide Map-Views based on OSM (OpenStreetMap).
Leaflet Docs

Leaflet CDN:

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css">
<script type="text/javascript" src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"></script>

Setup Map:

// init map
let map = L.map('map').setView([{lat}, {lon}], {zoom});

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

// add marker
let marker = L.marker([{lat}, {lon}], {opt}).addTo(map);
marker.bindTooltip({text}, {opt});
marker.bindPopup({code}, {opt});

// add polyline
let polyline = L.polyline([[{lat}, {lon}], [..], ..], {opt}).addTo(map);

Locate current location:

if('geolocation' in navigator) {
	navigator.geolocation.getCurrentPosition(function(position) {
		let lat = position.coords.latitude;
		let lon = position.coords.longitude;
		let alt = position.coords.altitude;
		console.log('lat: ' + lat + ', lon: ' + lon + ', alt: ' + alt);
	}, function(error) {
		// log error
	}, {
		enableHighAccuracy: true,
		maximumAge: 0,
		timeout: 5000
	});
}

navigator.permissions.query({ name: 'geolocation' })
	.then(function(snapshot) {
		if(snapshot.state === 'granted') {
			// success
		}
		else if(snapshot.state === 'prompt') {
			// request permission
		}
	})
	.catch(console.error);

KML

Docs: leaflet-kml

Load KML file:

// fetch -> text() = data
const parser = new DOMParser();
const kml = parser.parseFromString(data, 'text/xml');
const track = new L.KML(kml);
map.addLayer(track);

Fit bounds to track:

const bounds = track.getBounds();
map.fitBounds(bounds);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment