I am trying to fire an event when the mouse wheel is used:
map.on('mousewheel', function() {
alert('foo');
});
But that doesn't seem to work, nor does "wheel". Any ideas?
You could draw some inspiration from Leaflet source code handling the zoom on mousewheel and listen to the mousewheel events on the map container. Something like:
L.DomEvent.on(map.getContainer(), 'mousewheel', function() {
console.log("zoom", map.getZoom())
});
And a demo
var map = L.map('map').setView([35.772219, -78.675272], 10);
L.DomEvent.on(map.getContainer(), 'mousewheel', function() {
console.log("zoom", map.getZoom())
});
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.5.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.5.1/dist/leaflet.js"></script>
<div id="map" style="height: 100px"></div>
Related
I would like to show geojson point coordinates as a line on a leaflet map.
A simplified code with some test data looks like this:
<html>
<head>
<!-- Load leaflet library and use its styling css -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"> </script>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" /> //not included
</head>
<body>
<div class="pagewrapper">
<div id="map"></div>
<button onclick="myFunction()">Click me</button>
</div>
<script type="text/javascript">
//add map and set view
var map = L.map('map').setView([48.8,13.03],6);
// add background layer "opentopomap"
var backgroundlayer = L.tileLayer ('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png');
map.addLayer(backgroundlayer);
//get geojson data
function myFunction() {
$.ajax({
type: 'GET',
dataType:"json",
url: "https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_populated_places.geojson",
method: 'GET',
success: function(response) {
visualizer.sendDataToMap(response);
},
error:function(error) {
}
});
var visualizer = {};
//make geojson object and add to map
visualizer.sendDataToMap = function(jsonData) {
L.geoJson(jsonData).addTo(map);;
};
};
</script>
</body>
</html>
The part "visualizer.sendDataToMap(..)" might seem strange but is needed for some reason.
I managed to show the points on the map. But what I need is to show them as line (connect the first point with the second, connect the second point with the third ..).
I thought about writing the coordinates into an array which I then can use further in L.polyline() and use for some other calculations. I tried with response.geometry.coordinates and fiddled around with "coordsToLatLng" and some other suggestions I found in the forum. Maybe I need to loop through the coordinates, but I dont know how to do that. Could not get anything to work with my example.
Any hints would be appreciated.Thanks.
You can extract the coordinates from the geojson features by looping over geojson features array and mapping latitude and longitude. Then you will end up with an array of latLngs which is what you want to create the lines between the marker coordinates.
//make geojson object and add to map
visualizer.sendDataToMap = function(jsonData) {
console.log(jsonData)
L.geoJson(jsonData).addTo(map);
const latlngs = jsonData.features.map(feature => [feature.properties.LATITUDE, feature.properties.LONGITUDE]);
L.polyline(latlngs, {
color: 'red'
}).addTo(map);
};
};
Demo
I have written a Svelte component that displays a map using Leaflet. The following code of the component works.
I'm just wondering if this is the way to do it, or if there is a "more correct" or "smarter" way? Especially in view of the await import('leaflet'); in loadMap() and the way the CSS is loaded from the CDN in onMount()...
<script>
import { onMount } from 'svelte';
let map;
onMount(() => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'https://unpkg.com/leaflet#1.6.0/dist/leaflet.css';
link.onload = () => loadMap();
document.head.appendChild(link);
return () => {
map.remove();
link.parentNode.removeChild(link);
};
});
async function loadMap() {
await import('leaflet');
map = L.map('map').setView([49, 12], 13);
L.tileLayer('https://a.tile.openstreetmap.org/{z}/{x}/{y}.png ', {
attribution:
'Map data © OpenStreetMap contributors, CC-BY-SA',
maxZoom: 18,
}).addTo(map);
}
</script>
<style>
#map {
height: 480px;
}
</style>
<div id="map" />
You could use <svelte:head> to load the css and javascript: According to the docs:
This element makes it possible to insert elements into document.head. During server-side rendering, head content is exposed separately to the main html content.
So the head component would look like this:
<svelte: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>
</svelte:head>
Here is a full REPL to play around.
What am I doing wrong? The intent is to have a few (say 6) leafletjs panes, each containing many markers and polylines, so the panes can be hidden independently. Here is a simplified program showing just two lines and markers in jsfiddle. The problem is, the polylines all get grouped in the same SVG and all get hidden together. Each pane in the example should show one polyline and one marker.
I don't want to remove the polylines from the map to hide them, then recreating them would not perform well.
If needed, the polylines could be drawn using D3 on top of the leaflet map but I was hoping it could all be done in leaflet.
Thanks!
JS:
'use strict';
document.addEventListener("DOMContentLoaded", function(event) {
var map = L.map('map').setView([30.5, -0.09], 2);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var pane1 = map.createPane('pane1');
var pane2 = map.createPane('pane2');
function hide(pane) {
pane.style.display = 'none';
}
function show(pane) {
pane.style.display = '';
}
let icon = new L.Icon.Default();
function dr(pane, latlng){
L.polyline([[45.421, -75.697], latlng], {
weight: 2,
pane: pane
}).addTo(map);
L.marker(latlng, {
icon: icon,
pane: pane
}).addTo(map);
}
// define two locations with lines from Ottawa
dr(pane1, [ 42.3732216, -72.5198537 ]);
dr(pane2, [ 35.9606384, -83.9207392 ]);
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function loop(){
for( var i = 0; i<100; i++){
hide(pane1);
show(pane2);
await sleep(1000);
hide(pane2);
show(pane1);
await sleep(1000);
}
}
loop();});
HTML:
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.5.1/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.6.0/leaflet-src.js" integrity="sha256-wc8X54qvAHZGQY6nFv24TKlc3wtO0bgAfqj8AutTIu0=" crossorigin="anonymous"></script>
<style>
html, body {
height: 100%;
margin: 0;
}
#map {
width: 900px;
height: 500px;
}
</style>
</head>
<body>
<div id='map'></div>
</body>
</html>
<script src="c.js"></script>
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 can I fade out the following?
It does also need to be removed completely, not just only alpha 0 but also display:none and visibility:hidden after the fade out.
FIDDLE: http://jsfiddle.net/fourroses666/ywMUx/2/
js:
<script type="text/javascript" language="javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$('.go-away').click(function() {
$('.message').removeClass('show');
});
</script>
css:
<style>
.message{display:none; visibility:hidden;}
.message.show{display:block; visibility:visible;}
.go-away{float:right; cursor:pointer; cursor:hand;}
</style>
html:
<div class="message show">Pizza is nice! <div class="go-away">x</div></div>
Try this
$('.go-away').click(function() {
$(this).parent().fadeOut();
});
fadeOut makes it invisible, the 400 is how many milliseconds to fade out over, and then function() { $(this).remove() } is the callback function (called after the fadeOut animation has completed) that will remove the element from the DOM. Here's a working fiddle. Let me know if this helps or if you have any questions :)
$('.go-away').click(function() {
$('.message').fadeOut(400, function() {
$(this).remove();
});
});