Using Leaflet in a Svelte App - the Correct Way - leaflet

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.

Related

Having mutiple maps on screen using leaflet, want to fix it to single

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>

How can you put leaflet polylines in multiple panes?

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>

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' }

ArcGis layers on mapbox gl

I'm trying to add a layer from an api on ArcGis:
https://maps2.dcgis.dc.gov/dcgis/rest/services/DCGIS_DATA/Facility_and_Structure/MapServer/1
In leaflet it is posible with:
L.esri.featureLayer({
url:"https://maps2.dcgis.dc.gov/dcgis/rest/services/DCGIS_DATA/Facility_and_Structure/MapServer/1",
style: function () {
return { color: "#70ca49", weight: 2 };
}
}).addTo(map);
Is there a way to do this on mapboxgl?
Hi Jorge Monroy - Mapbox GL JS expects the data sources as such. In your case where you're wanting to load building footprints from an ArcGIS REST Service, your best bet is to load them as a geojson.
It looks like you're publishing the services from ArcServer 10.31. In that case, the way that I've loaded ArcGIS REST services is by exposing them through AGOL as explained there. If you have that option, that seems easiest. Otherwise, there are other (work-arounds)[https://gis.stackexchange.com/questions/13029/converting-arcgis-server-json-to-geojson] that I've no experience with.
Using Washington D.C. as an example, if you navigate to: http://opendata.dc.gov/datasets/building-footprints and then click on APIs, you can copy the link to the geojson service.
You can then load into MapboxGL JS through the data property of the geojson source shown there.
You can use leaflet-mapbox-gl.js to integrate leaflet and mapbox. Get token from mapbox and add it to below example to make it work.
References: https://github.com/mapbox/mapbox-gl-leaflet
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.css' rel='stylesheet' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.js'></script>
<script src="https://unpkg.com/mapbox-gl-leaflet/leaflet-mapbox-gl.js"></script>
<script src="https://unpkg.com/esri-leaflet/dist/esri-leaflet.js"></script>
<style>
html, body, #map {
margin:0; padding:0; width : 100%; height : 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var token = "";//add token before running this example
const INITIAL_VIEW_STATE = {
latitude: 45.528,
longitude: -122.680,
zoom: 13
};
var map = L.map('map').setView([45.528, -122.680], 13);
L.esri.basemapLayer("NationalGeographic").addTo(map);
var parks = L.esri.featureLayer({
url: "https://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/services/Portland_Parks/FeatureServer/0",
style: function () {
return { color: "#70ca49", weight: 2 };
}
}).addTo(map);
var gl = L.mapboxGL({
accessToken: token,
style: 'mapbox://styles/mapbox/dark-v10'
}).addTo(map);
//To add anything on mapbox, first access the mapbox using getMapboxMap()
gl.getMapboxMap().on('load', () => {
//To load any layer on mapbox
//gl.getMapboxMap().addLayer();
});
var popupTemplate = "<h3>{NAME}</h3>{ACRES} Acres<br><small>Property ID: {PROPERTYID}<small>";
parks.bindPopup(function(e){
return L.Util.template(popupTemplate, e.feature.properties)
});
</script>
</body>
</html>

How to specify accessToken for Mapbox with Leaflet

From Mapbox site I tested this code and success:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.cs
<style>
body { margin:0; padding:0; }
.map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map' class='map'> </div>
<script>
var map = new L.Map('map', {
center: new L.LatLng(51.505, -0.09),
zoom: 8,
layers: new L.TileLayer('https://a.tiles.mapbox.com/v3/mapbox.world-bright/{z}
});
</script>
</body>
</html>
How can I access my own map with markers and features? I suppose the "mapbox.world-bright" would be replaced by my own map.id, but how can I set the accessToken?
For some reasons I need to stick with Leaflet, and don't want to switch to mapbox.js.
It's just a matter of using the right url in L.TileLayer. You'll need to add your mapId and token and use the correct attribution. It's also much better if you load the tiles from multiple subdomains because your browser can handle up to four connection as once. Code example:
L.tileLayer('https://{s}.tiles.mapbox.com/v4/{mapId}/{z}/{x}/{y}.png?access_token={token}', {
attribution: '© Mapbox © OpenStreetMap',
subdomains: ['a','b','c','d'],
mapId: 'myMapId',
token: 'myUserToken'
});
To add the features of your map you'll need to query those in a separate request. Here's an example using jQuery. You'll need to swap the MAPID and TOKEN for your mapid and token ofcourse:
$.getJSON('http://a.tiles.mapbox.com/v4/MAPID/features.json?access_token=TOKEN', function (data) {
// Assuming the variable map contains your mapinstance
var geojson = L.geoJson(data).addTo(map);
map.fitBounds(geojson.getBounds());
});
Here's a working example on Plunker: http://plnkr.co/edit/h8F3kC?p=preview