Leaflet map with countries border only
Leaflet map with countries border only
License: public domain
by Alexander Farber
HTML
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1/dist/leaflet.css">
<script src="https://cdn.jsdelivr.net/npm/leaflet@1/dist/leaflet-src.js"></script>
<div id="myMap"></div>
CSS
html, body {
margin: 0;
padding: 0;
}
#myMap {
position: absolute;
width: 100%;
height: 100%;
}
JavaScript
'use strict';
function processNominatimReply(data) {
console.log('Received Nominatim reply:');
console.log(data);
data.features.forEach(function(feature) {
bordersGroup.addData(feature);
});
var bbox = data.features[0].bbox;
var topLeft = L.latLng(bbox[1], bbox[0]);
var bottomRight = L.latLng(bbox[3], bbox[2]);
var countryBounds = L.latLngBounds(topLeft, bottomRight);
var name = data.features[0].properties.display_name;
var tooltip = L.tooltip()
.setLatLng(countryBounds.getCenter())
.setContent(name)
.addTo(namesGroup);
myMap.flyToBounds(countryBounds);
}
function sendNominatimRequest(countryCode) {
var url = 'https://nominatim.openstreetmap.org/search?polygon_geojson=1&format=geojson&polygon_threshold=0.1&country=' + countryCode;
console.log('Sending Nominatim query to the URL ' + url);
var request = new XMLHttpRequest();
request.open('GET', url, false);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.response);
processNominatimReply(data);
}
};
request.send();
}
var startPosition = [51.4661, 7.2491];
var myMap = L.map('myMap').setView(startPosition, 14);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(myMap);
var namesGroup = L.layerGroup().addTo(myMap);
var bordersGroup = L.geoJSON().addTo(myMap);
var overlays = {
'Show country names': namesGroup,
'Show country borders': bordersGroup
};
L.control.layers(null, overlays, {
collapsed: false
}).addTo(myMap);
var countries = ['es', 'de', 'lv'];
countries.forEach(function(country) {
sendNominatimRequest(country);
});