Leaflet show multiple markers and setView - leaflet

I have sample code that uses Leaflet and open street map. Nevertheless, i am not sure how could i add more markers. Besides i don't really understand the sense of setView function i read that it's for centering map, but what is the sense to have it since there is only one marker which should be automaticly as map center point, and from the other hand if there will be more markers what is a sense of setView?
Additional question: Is Leaflet and open street map free for commercial use?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js" integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw==" crossorigin=""></script>
</head>
<body>
<div id="mapDiv" style="width: 800px; height: 500px"></div>
<script>
// position we will use later
var lat = 40.73;
var lon = -74.00;
// initialize map
map = L.map('mapDiv').setView([lat, lon], 13);
// set map tiles source
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap contributors',
maxZoom: 18,
}).addTo(map);
// add marker to the map
marker = L.marker([lat, lon]).addTo(map);
// add popup to the marker
marker.bindPopup("<b>ACME CO.</b><br />This st. 48<br />New York").openPopup();
</script>
</body>
</html>
</pre>

there is only one marker which should be automaticly as map center point
There is nothing in Leaflet itself that would automatically center a map view on your only Marker.
On the other hand, the sample code you show does achieve this, using setView on the same coordinates as your only Marker.
if there will be more markers what is a sense of setView?
setView gives you the ability to define which part of the map you want to initially display in your viewport, independently from your map content / layers (in your case: your markers). Obviously you can define a view that shows all your Markers at once as well.
i am not sure how could i add more markers.
Do L.marker([lat, lon]).addTo(map); as many times as needed, with lat and lon different each time as needed.
Is Leaflet and open street map free for commercial use?
Leaflet is distributed under a BSD 2-clause license, commercial use is permitted.
OpenStreetMap data is free, but not the tiles generated by OSM servers. There are many services generating similar tiles from OSM data or other sources that you can check out. E.g. you can search for "leaflet providers".

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js" integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw==" crossorigin=""></script>
</head>
<body>
<div id="mapDiv" style="width: 800px; height: 500px"></div>
<script>
// position we will use later
var lat = 40.73;
var lon = -74.00;
// initialize map
map = L.map('mapDiv');
// set map tiles source
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap contributors',
maxZoom: 18,
}).addTo(map);
/*
L.tileLayer('http://{s}.google.com/vt?lyrs=s&x={x}&y={y}&z={z}', {
maxZoom: 13,
subdomains:['mt0','mt1','mt2','mt3']
}).addTo(map);
*/
map.locate({setView: false, maxZoom: 8});
// add marker to the map
map.setView(new L.LatLng(lat, lon), 18);
marker = L.marker([lat, lon]).addTo(map);
// add popup to the marker
marker.bindPopup("<b>ACME CO.</b><br />This st. 48<br />New York").openPopup();
</script>
</body>
</html>
</pre>
Map Tiles

Related

Using Turf with Leaflet

I've made a leaflet map and was trying to implement turf.
As a quick test, I just wanted to put a buffer around one of my markers. But somehow I can still only see the two markers on my map. I basically followed the steps from this document. https://lib.dr.iastate.edu/gis_tasksheets/3/
I'm not sure where I made a mistake, I hope someone can tell me.
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Leaflet Map"</title>
<!-- leaflet.css, leaflet.js, turf.js von externer Quelle einbinden -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.4.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.4.0/dist/leaflet.js"></script> <!-- Load Leaflet code library-->
<script src='https://cdnjs.cloudflare.com/ajax/libs/leaflet-omnivore/0.3.4/leaflet-omnivore.min.js'></script> <!-- Load Omnivore to convert CSV to GeoJSON format -->
<script src="http://code.jquery.com/jquery-3.5.1.min.js"></script><!-- Load jQuery and PapaParse to read data from a CSV file -->
<script src="https://cdn.jsdelivr.net/npm/papaparse#5.3.0/papaparse.min.js"></script>
<script src='https://unpkg.com/#turf/turf/turf.min.js'></script>
<script>
var buffered = turf.buffer(point);
</script>
</head>
<body>
<div id='Karte' style='height: 800px; width: 100%;'></div>
<script type='text/javascript'>
var Karte = L.map('Karte').setView([48.896465, 10.996526], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
'attribution': 'Kartendaten © OpenStreetMap Mitwirkende',
'useCache': true
}).addTo(Karte);
var marker1 = L.marker([48.896465, 10.996526]).addTo(Karte);
var marker2 = L.marker([48.892750, 10.990300]).addTo(Karte);
var point = turf.point([48.896465, 10.996526]);
var buffered = turf.buffer(point, 50, {units: 'meter'});
buffer = L.geoJSON(buffered);
buffer.addTo(Karte);
</script>
</body>
</html>
Turf use geojson and geojson has the coordinate format lnglat, leaflet has latlng.
You have to swap your coords in the turf.point function:
var point = turf.point([10.996526,48.896465]);
Update
Remove also following:
<script>
var buffered = turf.buffer(point);
</script>
And change meter to meters
{units: 'meters'}
Demo
Be careful, leaflet works with [lat, lon] coordinates while geoJSON (and turf) is [lon, lat].
var coords1 = [48.896465, 10.996526];
var coords2 = [48.892750, 10.990300];
var marker1 = L.marker(coords1).addTo(Karte);
var marker2 = L.marker(coords2).addTo(Karte);
//add buffers
var point1 = turf.point([coords1[1], coords1[0]]);
var buffered1 = turf.buffer(point1, 50, {units: 'meters'})
L.geoJSON(buffered1).addTo(Karte);
var point2 = turf.point([coords2[1], coords2[0]]);
var buffered2 = turf.buffer(point2, 50, {units: 'meters'})
L.geoJSON(buffered2).addTo(Karte);
Check fiddle: https://jsfiddle.net/rp1320mf/
I would also like to add a note. Working with buffers or doing other distance-related tasks may be very inaccurate in Geographic Coordinate Systems. You should use it only if you dont really care about accuracy.

How to get the nearest Feature of an leaflet WMS Map?

I am quiet new to Web Services and I am facing a problem.
I have a Map linked with a WMS.
I added a basemap and my WMS Date as a tileLayer and the show up correctly on my map.
Now I want the nearest Feature to PopUp when I click anywhere on the map.
I already searched the Web but could not find a solution I understood. (https://gist.github.com/rclark/6908938)
Can anyone help me with this?
This is my code so far:
<!DOCTYPE html>
<html>
<head>
<title>XXX</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.6.0/dist/leaflet.js"
integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
crossorigin=""></script>
<style type="text/css">
#nrwMap { height: 800px; width: 1300px;}
</style>
</head>
<body>
<div id="Map"></div>
<script type="text/javascript">
var mymap = L.map('Map').setView([51.28, 7.33], 8);
var url = 'http://www.xxx.xxx.com/wms/';
var basemap = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox/streets-v11'
})
basemap.addTo(mymap);
var featureLayer = L.tileLayer.wms(url, {
layers: 'layerName',
format: 'image/png',
transparent: true
});
featureLayer.addTo(mymap);
</script>
</body>
</html>
Leaflet.GeometryUtil has a function/feature called closestLayer. It might help.
mymap.on('click', onMapClick);
function onMapClick(e) {
nearestLayer = L.GeometryUtil.closestLayer(mymap, layersToSearch, e.latlng)
// It will return the layer, latlng of point on layer nearest to the 'click' and distance from the 'click' }

Leaflet tile layer with dronedeploy

I am trying to display my dronedeploy map with leaflet.js, but the link which is generated by the Leaflet Tile Layer market app gives me an access denied error.
I am on a 30 day trial account but I have a few weeks remaining.
Also, is this the best way to display the data in leaflet? I noticed you can export the map as GeoTiff tiles, but I cannot find any examples on how to import/display these in leaflet
Okay so after replacing the {z}/{x}/{y}.png in the url with valid tile numbers, I got back some results.
I used this page to calculate a valid tile number:
http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
However this was unnecessary to get my map displayed in leaflet.
All I had to do was use the url when defining a tile layer, here's a complete example:
<!DOCTYPE html>
<html>
<head>
<title>Quick Start - Leaflet</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.3/dist/leaflet.css" integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ==" crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.0.3/dist/leaflet.js" integrity="sha512-A7vV8IFfih/D732iSSKi20u/ooOfj/AGehOKq0f4vLT1Zr2Y+RX7C+w8A1gaSasGtRUZpF/NZgzSAu4/Gc41Lg==" crossorigin=""></script>
</head>
<body>
<div id="mapid" style="width: 600px; height: 400px;"></div>
<script>
var mymap = L.map('mapid').setView([14.0, -8.2474], 13);
// add base map layer
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 22,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(mymap);
// url generated from "Leaflet / Mapbox / Fulcrum Tile Layer" market place app on dronedeploy
// (url truncated)
var leafletTileLayerUrl = 'https://public-tiles.dronedeploy.com/1494366194_KUJOSCARTOPENPIPELINE_ortho_vdt/{z}/{x}/{y}.png?Policy=.....'
// add custom map layer
L.tileLayer(leafletTileLayerUrl, {
maxZoom: 22,
}).addTo(mymap);
</script>
</body>
</html>

unable to dispaly polygon on the map using Leaflet draw plugin

I am trying to use draw plugin from here http://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html#l-draw
and tried using it locally as shown below
<html>
<head>
<title>A Leaflet map!</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.2/leaflet.draw.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.2/leaflet.draw.js"></script>
<style>
#map{ height: 100% }
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var drawControl = new L.Control.Draw({
draw : {
position : 'topleft',
polygon : true,
polyline : false,
rectangle : true,
circle : false
},
edit : false
});
map.addControl(drawControl);
</script>
</body>
</html>
I am getting the drawing control and map but the polygon draw is not shown up after drawing is completed not sure how to do it
Please help in getting the polygon drawn on the map as shown in this demo
http://leaflet.github.io/Leaflet.draw/docs/examples/full.html
You must create a feature group and add the layers when they are created ...
var drawnItems = L.featureGroup().addTo(map);
map.on(L.Draw.Event.CREATED, function (event) {
var layer = event.layer;
drawnItems.addLayer(layer);
});
see the source of http://leaflet.github.io/Leaflet.draw/docs/examples/full.html

How do I delete multiple markers from a Leaflet map?

I am trying to delete all the markers on my map, but code below only the last added marker will be deleted.
Is there a way to get a new a instance of map i mean on click of a button is there a way to reinitialize the map in leaflet?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://npmcdn.com/leaflet#1.0.0-rc.3/dist/leaflet.css" />
</head>
<body>
<script src="https://npmcdn.com/leaflet#1.0.0-rc.3/dist/leaflet.js"></script>
<script src="../leaflet/lib/AnimatedMarker.js"></script>
<style>
#mapid { height: 500px; }
</style>
<div id="mapid"></div>
<script>
var mymap = L.map('mapid').setView([40.68510, -73.94136], 13);
L.tileLayer('http://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', {
attribution: '© Openstreetmap France | © OpenStreetMap'
}).addTo(mymap);
var marker = L.marker([40.68510, -73.94136]).addTo(mymap);
var marker = L.marker([40.68576, -73.94149]).addTo(mymap);
var marker = L.marker([40.68649, -73.94165]).addTo(mymap);
mymap.removeLayer(marker);
</script>
</body>
</html>
Instead of adding markers to the map, add your markers to a layerGroup and add the layerGroup to the map.
You can remove the markers using clearLayers() method.
var markers = L.layerGroup([marker1, marker2]).addTo(map);
markers.clearLayers();