Let's say I'm a purple polyline and am using a purple icon for markers with one layer but wanted to use orange polylines and orange marker icon's for another layer. How would I do that? Is there an onlayerchange event? But even if there were how could I change all the icon's for all the markers? Alternatively, maybe I could delete all the markers and then replace them, albeit with a different icon, but idk how to delete markers, en masse or otherwise.
Any ideas?
I am not sure if I understood correctly but here is what you can do.
If you want to toggle between markers with polylines and assign different color you can use this plugin and return icon markers by passing the color.
const icon = (color) => L.icon({
iconSize: [25, 41],
iconAnchor: [10, 41],
popupAnchor: [2, -40],
iconUrl: `https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-${color}.png`,
shadowUrl: "https://unpkg.com/leaflet#1.6/dist/images/marker-shadow.png"
});
and then you have the latlngs and assing to the markers an icon with the prefered color
var places1 = [
{ latlng: [39.61, -105.02], popup: 'This is Littleton, CO.'},
{ latlng: [39.74, -104.99], popup: 'This is Denver, CO.'},
{latlng: [39.73, -104.8], popup: 'This is Aurora, CO.'}
];
places1.forEach(place => L.marker(place.latlng, {
icon: icon('violet')
}).bindPopup(place.popup).addTo(cities1))
and here define the polyline color
L.polyline(places1.map(({latlng}) => latlng), {
color: 'purple'
}).addTo(cities1);
Similarly you can follow the same steps for any other overlay
<!DOCTYPE html>
<html>
<head>
<title>Layers Control Tutorial - 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.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<style>
html,
body {
height: 100%;
margin: 0;
}
#map {
width: 600px;
height: 400px;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
var cities1 = L.layerGroup();
var cities2 = L.layerGroup();
var map = L.map('map', {
center: [39.73, -104.99],
zoom: 10,
});
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
const icon = (color) => L.icon({
iconSize: [25, 41],
iconAnchor: [10, 41],
popupAnchor: [2, -40],
iconUrl: `https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-${color}.png`,
shadowUrl: "https://unpkg.com/leaflet#1.6/dist/images/marker-shadow.png"
});
var places1 = [{
latlng: [39.61, -105.02],
popup: 'This is Littleton, CO.'
},
{
latlng: [39.74, -104.99],
popup: 'This is Denver, CO.'
},
{
latlng: [39.73, -104.8],
popup: 'This is Aurora, CO.'
}
];
places1.forEach(place => L.marker(place.latlng, {
icon: icon('violet')
}).bindPopup(place.popup).addTo(cities1))
var places2 = [{
latlng: [39.77, -105.23],
popup: 'This is Golden, CO.'
},
{
latlng: [39.75, -105.16],
popup: 'This is Applewood, CO.'
}
];
places2.forEach(place => L.marker(place.latlng, {
icon: icon('orange')
}).bindPopup(place.popup).addTo(cities2))
L.polyline(places1.map(({
latlng
}) => latlng), {
color: 'purple'
}).addTo(cities1);
L.polyline(places2.map(({
latlng
}) => latlng), {
color: 'orange'
}).addTo(cities2);
var overlays = {
"cities1": cities1.addTo(map),
"cities2": cities2
};
L.control.layers(null, overlays).addTo(map);
</script>
</body>
</html>
For the scenario you want to change the color upon baselayer change:
you can still reuse icon() function and use now the follow chunk to change the color dynamically when the layer is changed by listening to map's baselayerchange event
function addMarkersAndPolyline(color) {
places.forEach(place => L.marker(place.latlng, {
icon: icon(color)
}).bindPopup(place.popup).addTo(cities))
L.polyline(places.map(({
latlng
}) => latlng), {
color
}).addTo(cities);
}
<!DOCTYPE html>
<html>
<head>
<title>Layers Control Tutorial - 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.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<style>
html,
body {
height: 100%;
margin: 0;
}
#map {
width: 600px;
height: 400px;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
var cities = L.layerGroup();
var map = L.map('map', {
center: [39.73, -104.99],
zoom: 10,
});
var mbAttr = 'Map data © OpenStreetMap contributors, ' +
'Imagery © Mapbox',
mbUrl = 'https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
var grayscale = L.tileLayer(mbUrl, {
id: 'mapbox/light-v9',
tileSize: 512,
zoomOffset: -1,
attribution: mbAttr
}),
streets = L.tileLayer(mbUrl, {
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
attribution: mbAttr
});
var baseLayers = {
"Grayscale": grayscale.addTo(map),
"Streets": streets
};
const icon = (color) => L.icon({
iconSize: [25, 41],
iconAnchor: [10, 41],
popupAnchor: [2, -40],
iconUrl: `https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-${color}.png`,
shadowUrl: "https://unpkg.com/leaflet#1.6/dist/images/marker-shadow.png"
});
var places = [{
latlng: [39.61, -105.02],
popup: 'This is Littleton, CO.'
},
{
latlng: [39.74, -104.99],
popup: 'This is Denver, CO.'
},
{
latlng: [39.73, -104.8],
popup: 'This is Aurora, CO.'
}
];
function addMarkersAndPolyline(color) {
places.forEach(place => L.marker(place.latlng, {
icon: icon(color)
}).bindPopup(place.popup).addTo(cities))
L.polyline(places.map(({
latlng
}) => latlng), {
color
}).addTo(cities);
}
addMarkersAndPolyline('violet')
map.on('baselayerchange', function(e) {
cities.clearLayers();
if (e.name === 'Streets') {
addMarkersAndPolyline('orange');
return
}
addMarkersAndPolyline('violet');
});
var overlays = {
"cities1": cities.addTo(map),
};
L.control.layers(baseLayers, overlays).addTo(map);
</script>
</body>
</html>
I used leaftlet to include map in my website, but i am seeing big infinite circles on the screen over map.
CDN used.
<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>
JavaScript Code.
<!-- map working javascript -->
<script>
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=XgEM27Xb3yStMrCCnrfb' , { attribution: '© MapTiler © OpenStreetMap contributors' }, { noWrap: true }).addTo(map);
var marker = L.marker([0,0]).addTo(map);
// var layer = new L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
// noWrap: true
// });
</script>
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
I want to use the pic userPosition.png on my location when I accept the prompt of asking for location, right now it doesn't work.
<!DOCTYPE html>
<html lang="en">
<head>
<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>
<script src="./leaflet/leaflet.js"></script>
<style></style>
</head>
<body>
<h2 style="text-align: center;">My interactive map</h2>
<div id="mapid" style="width: 100%;height: 500px;"></div>
<script>
var mymap;
mymap = L.map("mapid").setView([55.70584, 13.19021], 12);
L.tileLayer(
"https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFkc2pvaGFuc2VuIiwiYSI6ImNrNWkxZnA3bzA5NnIza3M2cGczNnprMHcifQ.Z2h9R1lODB6zPZ2Ex92BrA",
{
attribution:
'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: "mapbox/streets-v11",
accessToken: "your.mapbox.access.token"
}
).addTo(mymap);
function onLocationFound(e) {
var radius = e.accuracy / 2;
L.marker(e.latlng)
.addTo(map)
.bindPopup("You are within " + radius + " meters from this point")
.openPopup();
}
function onLocationError(e) {
alert(e.message);
}
map.on("locationfound", onLocationFound);
map.on("locationerror", onLocationError);
map.locate({
setView: true,
maxZoom: 16
});
var popup = L.popup();
var marker = L.marker();
var circle = L.circle();
var newMarkerIcon = L.Icon.extend({
options: {
iconSize: [38, 95],
shadowSize: [50, 64],
iconAnchor: [22, 94],
shadowAnchor: [4, 62],
popupAnchor: [-3, -76]
}
});
var blackMarker = new newMarkerIcon({ iconUrl: "userPosition.png" });
function onMapClick(e) {
L.marker(e.latlng, "Insert postition PNG pic here")
.addTo(mymap)
.bindPopup("You clicked the map at " + e.latlng.toString());
}
mymap.on("click", onMapClick);
</script>
</body>
</html>
Use this :
L.marker([e.latlng], { icon: YourIconHere })
.bindPopup("You are within " + radius + " meters from this point")
.openPopup()
.addTo(map);
You can also add circle like that:
L.circle([e.latlng], radius,
{ weight: 1, color: 'blue', fillColor: '#cacaca', fillOpacity: 0.2 })
.addTo(map);
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