Leaflet lowest zoom level is still too high with L.CRS.Simple - leaflet

Trying to retrieve part of a district, however for some reason cannot see the whole area, even if zoom level is at 0, where (supposedly) we should see the whole world.
I am using L.CRS.Simple because this uses the EPSG:3763 and cannot see that one on the CRS list. I am retrieving the data in JSON cause when tying with geoJSON, was not able to transform the 3D coordinates data into 2D planes ones.
const queryRegionText = "where=OBJECTID > 0"
const geoJsonURL2 = "https://sig.cm-figfoz.pt/arcgis/rest/services/Internet/MunisigWeb_DadosContexto/MapServer/2/query?f=json&returnGeometry=true&geometryType=esriGeometryPolyline&spatialRel=esriSpatialRelIntersects&outFields=*&outSR=3763&" + queryRegionText
var map = L.map('mapid', {
crs: L.CRS.Simple
}).setView([-58216.458338, 42768.347232], 0);
L.control.scale({ metric: true }).addTo(map);
fetch(geoJsonURL2).then(function (response) {
response.json().then(function (data) {
data.features.forEach(element => {
if (element.geometry.rings) {
element.geometry.rings.forEach(point => {
L.polyline(point, { color: 'red' }).addTo(map);
})
}
});
});
});
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(map);
}
map.on('click', onMapClick);
<html>
<head>
<title>Leaflet - testing</title>
<meta charset="utf-8" />
<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>
</head>
<body>
<div id="mapid" style="width: 600px; height: 400px;"></div>
</body>
</html>

TL;DR: When creating the map, set the minimum zoom below zero. This should work:
var map = L.map('mapid', {
crs: L.CRS.Simple, minZoom: -6
}).setView([-57728, 55296], -6);
Explanation
Normally, Leaflet translates from a latitude/longitude coordinate system to screen pixels using an assumption that the world is 256 pixels high at Zoom level 0. At each higher Zoom Level, the number of pixels doubles (explained nicely in the Zoom levels tutorial). With this assumption, the options for the map default to {minZoom: 0, maxZoom: Infinity} (as you are not adding any Layer that sets these values to anything different).
When you use L.CRS.Simple, at Zoom level 0 it maps 1 coordinate unit to 1 screen pixel. Your data looks like it is about 18000 coordinate units tall, so it doesn't fit in your 400 pixel high map. To make it fit, we need each screen pixel to map to about 45 coordinate units. 2^5 is 32, and 2^6 is 64, so we need to zoom out between 5 and 6 times. Luckily, Leaflet accepts negative Zoom Levels, so setting zoom to -6 does the trick. But to make it work properly, you need to set {minZoom: -6}, so the map doesn't get stuck at zoom level 0. There's a good worked example in the Non-geographical Maps tutorial.
Using L.CRS.Simple should work for you, so long as the approximation holds that each latitude unit is the same length as each longitude unit (a square world). Since this isn't generally true in the real world, using the Simple projection will cause some distortion. If the distortion is significant for the features you are interested in, then you will need to look up how to use EPSG:3763 properly, using L.CRS and Proj4Leaflet, as suggested by #IvanSanchez.

So, after some reading on the proj4leaflet, come up with this code. Thanks in advance for the comments and the reply above.
const queryRegionText = "where=OBJECTID > 0"
const geoJsonURL2 = "https://sig.cm-figfoz.pt/arcgis/rest/services/Internet/MunisigWeb_DadosContexto/MapServer/2/query?f=geojson&returnGeometry=true&geometryType=esriGeometryPolyline&spatialRel=esriSpatialRelIntersects&outFields=*&outSR=3763&" + queryRegionText
const map = L.map('map', {
center: [40.14791, -8.87009],
zoom: 13
});
proj4.defs("EPSG:3763", "+proj=tmerc +lat_0=39.66825833333333 +lon_0=-8.133108333333334 +k=1 +x_0=0 +y_0=0 +ellps=GRS80 +units=m +no_defs");
fetch(geoJsonURL2).then(function (response) {
response.json().then(function (data) {
L.Proj.geoJson(data).addTo(map);
});
});
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(map);
}
map.on('click', onMapClick);
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" />
<link rel="stylesheet" href="main.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.7.4/proj4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4leaflet/1.0.2/proj4leaflet.js"></script>
</head>
<body class="">
<div id="map" style="width: 600px; height: 400px;"></div>
</div>
<script src="main.js"></script>
</body>

Related

How to distinguish leaflet zoom triggered by map.fitBounds from user mousewheel?

I have a map which is refreshed every 30 seconds and on each refresh I fit bounds to the new data. I would like to change the way I fit bounds if a user has manipulated the map, e.g. changed zoom level. My problem is that zoom triggered from fitBounds is indistinguishable from user action.
How do I capture/extend mousewheel on the map?
Basically there are multiple ways todo same, but you can go with following simple way to distinguish user zoom triggered.
The onwheel event occurs when the mouse wheel is rolled up or down over an element.
var map = L.map('map', {
// Set latitude and longitude of the map center (required)
center: [12.99766, -84.90838],
// Set the initial zoom level, values 0-18, where 0 is most zoomed-out (required)
zoom: 5,
// scrollWheelZoom: false
});
// Create a Tile Layer and add it to the map
var tiles = new L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png').addTo(map);
document.getElementById("map").addEventListener("wheel", myFunction);
function myFunction() {
alert("Mouse wheel Scrolled by user.")
}
#map {
width: 500px;
height: 400px;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.0.3/dist/leaflet.js"></script>
<div id="map"></div>
Hope this will helps you.

Using minZoom with map.fitBounds without getting error

I have a Leaflet map that I am trying to plot multiple points using map.fitbounds() but I would like the set a minZoom so the user cant zoom all the way out past a zoom level of 9. I currently use the below to add pins to a map except sometimes when a map as multiple points where the map would need to fitbounds at a wider zoom it causes the map to fail. When the map fitbounds is set higher than 9 then it works fine but below 9 it doesnt plot.
I was wondering if someone would know how to both safeguard a map from failing with a minZoom and using fitBounds in certain instances and to also stop a user from zooming so far out.
map.options.minZoom = 9;
map.options.maxZoom = 15;
var fg = L.featureGroup().addTo(map);
for ( var i=0; i < markersArray.length; ++i )
{
var linkid = (markersArray[i]['linkid']);
var linkurl = (markersArray[i]['linkurl']);
L.marker( [markersArray[i].lat, markersArray[i].lng], {icon: myIcon} )
.bindPopup( '<div id="mapPinDetails"><h3>' + markersArray[i].name + '</h3>' + markersArray[i].address + '<br /></div>' )
.addTo(fg);
}
map.fitBounds(fg.getBounds());
below 9 it doesnt plot
It does, but since you do not allow your map to zoom out below 9, it remains at zoom level 9 and you may not see your outer markers. But if you pan you can see them. The view center is the same that would have been achieved with a lower zoom:
var map = L.map('map', {
minZoom: 9,
maxZoom: 15,
}).setView([48.86, 2.35], 11);
var fg = L.featureGroup().addTo(map);
L.marker([49, 2.35]).addTo(fg);
L.marker([48.5, 2.35]).addTo(fg);
map.fitBounds(fg.getBounds());
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
<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-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script>
<div id="map" style="height: 180px"></div>
If you need further help, you will have to explain what you mean by "it causes the map to fail" and if possible share a reproducible example.

Fit map to bounds exactly

Is there a way to fit the map exactly to bounds? (or as close a possible).
For example, in this jsfiddle, even without padding the map leaves a lot of padding above and below the points:
http://jsfiddle.net/BC7q4/444/
map.fitBounds(bounds);
$('#fit1').click(function(){ map.fitBounds(bounds); });
$('#fit2').click(function(){ map.fitBounds(bounds, {padding: [50, 50]}); });
I'm trying to fit a map as precisely as possible to a set of bounds that closely match the map shape without all the extra padding.
Setting a map's ne corner and sw corner would work as well, but I don't think that functionality exists.
You are very probably looking for the map zoomSnap option:
Forces the map's zoom level to always be a multiple of this, particularly right after a fitBounds() or a pinch-zoom. By default, the zoom level snaps to the nearest integer; lower values (e.g. 0.5 or 0.1) allow for greater granularity. A value of 0 means the zoom level will not be snapped after fitBounds or a pinch-zoom.
Because its default value is 1, after your fitBounds the map will floor down the zoom value to the closest available integer value, hence possibly introducing more padding around your bounds.
By specifiying zoomSnap: 0, you ask the map not to snap the zoom value:
var map = L.map('map', {
zoomSnap: 0 // http://leafletjs.com/reference.html#map-zoomsnap
}).setView([51.505, -0.09], 5);
// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var southWest = new L.LatLng(40.712, -74.227),
northEast = new L.LatLng(40.774, -74.125),
bounds = new L.LatLngBounds(southWest, northEast);
L.marker([40.712, -74.227]).addTo(map);
L.marker([40.774, -74.125]).addTo(map);
map.fitBounds(bounds);
$('#fit1').click(function() {
map.fitBounds(bounds);
});
$('#fit2').click(function() {
map.fitBounds(bounds, {
padding: [50, 50]
});
});
body {
padding: 0;
margin: 0;
}
#map {
height: 300px;
margin-top: 10px;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet-src.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<button id="fit1">fit without bounds</button>
<button id="fit2">fit with bounds</button>
<div id="map"></div>

Leaflet JS + Leaflet.Deflate - Changing default marker icon to custom icon

In my previous post 'Leaflet JS - changing esri shape into marker on certain zoom level
' I was able to resolve an issue which i had with the leaflet JS library and changing the polygon shapes to markers icons when hitting a certain zoom level.
I was advised by 'Ivan Sanchez' to use the 'Leaflet.Deflate' plugin and this works like a charm, so now the various shapes are being transformed into markers after a certain zoomlevel, however now I'm struggling to change the default leaflet marker icon to a custom marker icon, so my question now is:
Is it possible to change the default marker icon to a custom marker icon while using the 'Leaflet.ShapeFile' and 'Leaflet.Deflate' plugin and what would be the best approach to do this?
I wanted to make a JSFiddle, but I don't JSFiddle allows me to attach the zip file contains the shapefiles, so I will post the code I have got so far below here, thanks for your help, advise and support:
<!doctype html>
<html lang="en">
<head>
<meta charset='utf-8' />
<title>v4</title>
<link rel="stylesheet" type="text/css" href="lib/leaflet/leaflet.css" />
<!--[if lte IE 8]> <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.ie.css" /> <![endif]-->
<link rel="stylesheet" type="text/css" href="lib/leaflet/L.Control.Sidebar.css" />
<style>
html { height: 100% }
body { height: 100%; margin: 0; padding: 0; }
#map { height: 100% }
</style>
</head>
<body>
<div id="map"></div>
<script src="lib/jquery/jquery-3.1.1.min.js"></script>
<script src="lib/leaflet/leaflet.js"></script>
<script src="lib/leaflet/catiline.js"></script>
<script src="lib/leaflet/leaflet.shpfile.js"></script>
<script src="lib/leaflet/shp.js"></script>
<script src="lib/leaflet/L.Control.Sidebar.js"></script>
<script src="lib/leaflet/L.Deflate.js"></script>
<script>
// init map
var m = L.map('map').setView([52.472833, 1.749609], 15);
// clicking on the map will hide the sidebar plugin.
m.on('click', function () {
sidebar.hide();
});
// init Deflate plugin
L.Deflate({ minSize: 10 }).addTo(m);
// Init side bar control
var sidebar = L.control.sidebar('sidebar', { closeButton: true, position: 'right' });
m.addControl(sidebar);
// Init esri shape file via leaflet.shapefile, shp.js plugin
var businessProperties = new L.Shapefile('data/businessshapes.zip', { style: propertyStyle, onEachFeature: propertyOnEachFeature }).addTo(m);
// create on-click Feature
function propertyOnEachFeature(feature, layer) {
layer.on( {
mouseover: highlightFeature,
mouseout: resetHighlight,
click: function populate() {
sidebar.toggle();
document.getElementById('pinfoHeader').innerHTML = "<h2>" + feature.properties.Building + " - Detailed Information</h2><br />";
document.getElementById('pTitle').innerHTML = "Name: " + feature.properties.Building
document.getElementById('pDetails').innerHTML = "SHAPE_Leng: " + feature.properties.SHAPE_Leng + "<br/ >SHAPE_Area: " + feature.properties.SHAPE_Area
}, highlightFeature, zoomToFeature
});
}
// style the properties style
function propertyStyle(feature) {
return {
fillColor: getPropertyColor(feature.properties.BusType),
weight: 2,
opacity: 1,
color: 'white',
dashArray: 3,
fillOpacity: 0.7
}
}
// set color per property according to the data table of the Esri Shape file.
function getPropertyColor(propStatus) {
if (propStatus == 'TypeA') {
return 'red';
} else if (propStatus == 'TypeB') {
return 'green';
} else {
return 'yellow';
}
}
// set the highlighted color for polygon
function highlightFeature(e) {
var layer = e.target;
layer.setStyle( {
weight: 2,
color: 'black',
fillColor: 'white',
fillOpacity: 0.2
});
if (!L.Browser.ie && !L.Browser.opera) {
layer.bringToFront();
}
}
// reset the highlighted color for polygon after mouse leave polygon
function resetHighlight(e) {
businessProperties.resetStyle(e.target);
}
//Extend the Default marker class to overwrite the leaflet.deflate marker icon???
var TestIcon = L.Icon.Default.extend({
options: {
iconUrl: 'assets/images/markers/business.png'
}
});
var testIcon = new TestIcon();
businessProperties.addTo(m);
// Init base maps for switch
var grayscale = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', { id: 'MapID', attribution: 'Map maintained by Demo LTD, — Map data © OpenStreetMap,' }).addTo(m);
var streets = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { id: 'MapID', attribution: 'Map maintained by Demo LTD, — Map data © OpenStreetMap,' });
var baseMaps = {
"Streets": streets,
"Grayscale": grayscale
};
// Init overlay map switch
var overlayMaps = {
"Bussines Properties": businessProperties
};
// Add switches to map control
L.control.layers(baseMaps, overlayMaps).addTo(m);
</script>
</body>
</html>
Is it possible to change the default marker icon to a custom marker icon while using the 'Leaflet.Deflate' plugin?
The answer is: No.
The current code for Leaflet.Deflate uses a default marker and a default marker only, see https://github.com/oliverroick/Leaflet.Deflate/blob/991f51ca82e7bb14a17c8d769b4c378c4ebaf700/src/L.Deflate.js#L42
You could hack your way around it, but I would rather recommend filing a feature request in the Leaflet.Deflate repo. It should be possible to modify the Leaflet.Deflate repo to allow line/polygon features to have some extra properties to be used as marker options.

Mapbox non-geographic

I'm trying to mixed up for at least a week , mapbox with leaflet to did a Non geographic map.
My first step was to build it with maptiler.com which generated with the tiled a code based on leaflet. But i want to add to this code a Geojson proprites.
I saw that in Mapbox there is already a geojson popup built-in.
This is why i want to use my leaflet map code + mapbox popup, it's possible ?
Thanks,
Jade
<!DOCTYPE html>
<html>
<head>
<title>map</title>
<meta charset="utf-8"/>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.js'></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.css' rel='stylesheet' />
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.ie.css" />
<![endif]-->
<script>
L.mapbox.accessToken = 'pk.eyJ1IjoiamFkZTIyOTMiLCJhIjoiRDdweEFrZyJ9.Yk4XeNmp3SExkU41Z7BU3w';
function init() {
var mapMinZoom = 3;
var mapMaxZoom = 6;
var map = L.map('map', {
maxZoom: mapMaxZoom,
minZoom: mapMinZoom,
crs: L.CRS.Simple
}).setView([0, 0], mapMaxZoom);
var mapBounds = new L.LatLngBounds(
map.unproject([0, 7680], mapMaxZoom),
map.unproject([10496, 0], mapMaxZoom));
map.fitBounds(mapBounds);
L.tileLayer('{z}/{x}/{y}.png', {
minZoom: mapMinZoom, maxZoom: mapMaxZoom,
bounds: mapBounds,
noWrap: true
}).addTo(map);
// The GeoJSON representing a point feature with a property of 'video' for the Vimeo iframe
var geoJson = {
features: [{
type: 'Feature',
properties: {
'marker-color': '#f00',
'marker-size': 'large',
'marker-symbol': 'rocket',
video: '<iframe src="//player.vimeo.com/video/106112939" width="380" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> <p><h2>How Simplicity Will Save GIS</h2><p>Vladimir Agafonkin from FOSS4G on Vimeo.</p>',
},
geometry: {
type: 'Point',
coordinates: [0,0]
}
}]
};
var myLayer = L.mapbox.featureLayer().addTo(map);
// Add the iframe in a marker tooltip using the custom feature properties
myLayer.on('layeradd', function(e) {
var marker = e.layer,
feature = marker.feature;
// Create custom popup content from the GeoJSON property 'video'
var popupContent = feature.properties.video;
// bind the popup to the marker http://leafletjs.com/reference.html#popup
marker.bindPopup(popupContent,{
closeButton: false,
minWidth: 320
});
});
// Add features to the map
myLayer.setGeoJSON(geoJson);
}
</script>
<style>
html, body, #map { width:100%; height:100%; margin:0; padding:0; }
background-color:white;
</style>
</head>
<body onload="init()">
<div id="map"></div>
</body>
</html>
It seems that you're asking 2 separate questions here. The original question about non-geographic maps and your follow-up question about adding an iframe to a leaflet popup. I'll try to address your follow-up question:
Let's take the Mapbox example you linked (https://www.mapbox.com/mapbox.js/example/v1.0.0/video/) and adapt it to work with the video you would like to display.
If you've already got some GeoJSON data, you can edit it to include a video property. Let's look at the GeoJSON code from the Mapbox example:
var geoJson = {
features: [{
type: 'Feature',
properties: {
'marker-color': '#f00',
'marker-size': 'large',
'marker-symbol': 'rocket',
video: '<iframe src="//player.vimeo.com/video/106112939" width="380" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> <p><h2>How Simplicity Will Save GIS</h2><p>Vladimir Agafonkin from FOSS4G on Vimeo.</p>',
},
geometry: {
type: 'Point',
coordinates: [0,0]
}
}]
};
See that video property? Its value contains the iframe code that will end up inside the popup for the map marker it corresponds to. I went ahead and added the iframe code from your YouTube video to the above example and you can see it in action on jsfiddle here: http://jsfiddle.net/danswick/tcxvpw84/.
Your GeoJSON data probably doesn't have a video property, but you can add it using a text editor or geojson.io.
Further down in our example code, we access that video property, set it to a variable, and bind it to our marker's popup:
// Create custom popup content from the GeoJSON property 'video'
var popupContent = feature.properties.video;
// bind the popup to the marker http://leafletjs.com/reference.html#popup
marker.bindPopup(popupContent,{
closeButton: false,
minWidth: 320
});
Mapbox just uses Leaflet's bindPopup method which comes standard with L.Marker. If you create a L.GeoJSON layer, you can add a popup to each feature using the onEachFeature option of L.GeoJSON which takes a function with two parameters: feature and layer. In there you can bind a popup to your feature:
For example when you have features like this one, with a property called name:
{
"type": "Feature",
"properties": {
"name": "E"
},
"geometry": {
"type": "Point",
"coordinates": [0, 0]
}
}
You could then use that name value when binding a popup to your feature like this:
// Create new GeoJSON layer
L.geoJson(data, {
// Define the onEachFeature function which runs on every feature
onEachFeature: function (feature, layer) {
// Bind a popup to the layer using the name property
layer.bindPopup(feature.properties.name);
}
}).addTo(map);
Here's a working example on Plunker: http://plnkr.co/edit/iPLHqi?p=preview
Thanks, to take time to reply.
But actually i wanted to use geojson just to put iframe in a leaflet popup.
like this :
L.marker(map.unproject([452, 410])).addTo(map).bindPopup("<iframe width="560" height="315" src="https://www.youtube.com/embed/zP71_cXfiu0" frameborder="0" allowfullscreen></iframe>");
But it doesn't work but with the same syntax this work : I just saw in this exemple that with geojson it's might work :
https://www.mapbox.com/mapbox.js/example/v1.0.0/video/
L.marker(map.unproject([452, 410])).addTo(map).bindPopup("https://www.youtube.com/embed/zP71_cXfiu0");
Sorry if i'm a little bit confusing, because i'm designer and all this "code thing" it's new for me :)