How to change style in a Leaflet's imageOverlay apart from opacity? - leaflet

I would like to change the style of an ImageOverlay in Leaflet. As I saw from the imageOverlay instance apart from setUrl, setBounds, setOpacity methods there seems to be a setStyle method which only seems to work with opacity or with limited css attributes.
f.i
imageOverlay.setStyle({
opacity: 0.5
})
this works fine as expected.
For instance how would I change the borderColor or color or fill properties? I have used
imageOverlay.setStyle({
borderColor: '#FF0000 blue'
})
but no style is applied.
Below I give an example. I have two buttons implementing two functions. SetOpacity that works fine and setBorderColor that does not work.
Any recommendations are welcome.
#mapid {
height: 100vh;
}
body {
margin: 0px;
padding: 0px;
}
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.js"></script>
<button onclick='setOverlayOpacity()'>ChangeOpacity</button>
<button onclick='setOverlayBorderColor()'>Change Border Color</button>
<div id="mapid"></div>
<script>
var map = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
imageBounds = [
[40.712216, -74.22655],
[40.773941, -74.12544]
];
var imageOverlay = L.imageOverlay(imageUrl, imageBounds).addTo(map);
console.log(imageOverlay)
map.fitBounds(imageBounds)
function setOverlayOpacity() {
imageOverlay.setStyle({
opacity: 0.5
})
}
function setOverlayBorderColor() {
imageOverlay.setStyle({
borderColor: '#FF0000 blue'
})
}
</script>

The setStyle() method of L.ImageOverlay is not documented on purpose, and only for compatibility for L.FeatureGroup.setStyle(), which is mainly meant for setting style options for L.Path, not CSS rules.
In fact, the current implementation of L.ImageOverlay.setStyle() method only sets the opacity:
setStyle: function (styleOpts) {
if (styleOpts.opacity) {
this.setOpacity(styleOpts.opacity);
}
return this;
},
I think that what you want to do is to use L.ImageOverlay.getElement(), which returns a HTMLImageElement and then access its style property, e.g.:
myOverlay.getElement().style.border = '2px solid red';
Alternatively, use the className option to assign a CSS class to the ImageOverlay's HTMLImageElement, and add CSS rules accordingly.

Related

How to add custom UI to leaflet map?

I am using Leaflet to create a map game (very basic).
Basically I want to add an input <div> on the map so that when a user types in a location it will pan to a coordinate on the map.
I have tried creating elements and appending to the map <div> with variations of:
var d1 = document.getElementsByClassName('leaflet-control-container')[0];
d1.insertAdjacentHTML('afterbegin', '<div id="two">two</div>');
But the <div> is displayed behind the map and the image covers it.
How can I get it to show like the Zoom Control?
If I understand correctly, you would like to create your own "Control" (somehow visually similar to the Leaflet default Zoom Control, but with different functionality), that would allow looking for different locations and navigate to them.
As for styling a Control similar to Leaflet default ones (zoom, layers control), you need to:
Extend L.Control
Specify an onAdd method that returns the DOM element to be used as Control on the map. Steps 1 and 2 will make your Control add-able to a map corner as a standard Control, with proper z-index and margin.
Style it using your own class. To get a visual effect similar to the Zoom and Layers Controls, you can build on the leaflet-bar class:
.leaflet-bar {
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.65);
border-radius: 5px;
}
Example: (derived from the "Extending Leaflet: Handlers and Controls" tutorial)
var map = L.map('map').setView([48.86, 2.35], 11);
L.Control.MyControl = L.Control.extend({
onAdd: function(map) {
var el = L.DomUtil.create('div', 'leaflet-bar my-control');
el.innerHTML = 'My Control';
return el;
},
onRemove: function(map) {
// Nothing to do here
}
});
L.control.myControl = function(opts) {
return new L.Control.MyControl(opts);
}
L.control.myControl({
position: 'topright'
}).addTo(map);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
.my-control {
background: #fff;
padding: 5px;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.0/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.3.0/dist/leaflet-src.js" integrity="sha512-2h9aokfcaYW7k0VPn1JqbQDQCaNQRrZJwetlnQ88yJrtIzGLVW/2StdQKoE+TIVNNTUxf6SVa+2vW2KB2EXnnA==" crossorigin=""></script>
<div id="map" style="height: 200px"></div>
That being said, the Control functionality that you would like to implement sounds very similar to that of the Leaflet Control Search plugin (aka "leaflet-search")
A Leaflet control that search markers/features location by custom property.

How to draw a polyline with initial point in Leaflet

I'm using custom polyline drawer from Leaflet.draw
let polylineDrawer = new L.Draw.Polyline(map, {})
polylineDrawer.enable()
I need to programmatically add starting point to polyline
I've tried calling addVertex of L.Draw.Polyline. Looks like it's doesn't work with custom polyline drawer cause of addHooks or something... Tried to change sources, no results.
Also tried firing click on map after drawer is enabled. Like so:
let point = new L.LatLng(x, y)
map.fireEvent('click', {
latlng: point,
layerPoint: map.latLngToLayerPoint(point),
containerPoint: map.latLngToContainerPoint(point),
})
Also doesn't work
EDIT: Actually, AddVertex does work with custom polylines. It "didn't work" because I passed wrong arguments in my function. Somehow, I missed that.
Using addVertex on your drawer object does let you add a starting point to your line :
var polylineDrawer = new L.Draw.Polyline(map, {})
polylineDrawer.enable();
var latlng = L.latLng(48.8583736, 2.2922926);
polylineDrawer.addVertex(latlng);
and a demo
var style = {
stroke: true,
color: 'red',
weight: 4,
opacity: 0.5
};
var map = L.map(document.getElementById('map')).setView([48.8583736, 2.2922926], 15);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var drawnItems = new L.geoJson(null, {style: style}).addTo(map);
map.on(L.Draw.Event.CREATED, function (event) {
var layer = event.layer;
drawnItems.addLayer(layer);
});
var polylineDrawer = new L.Draw.Polyline(map, {})
polylineDrawer.enable();
var latlng = L.latLng(48.8583736, 2.2922926);
polylineDrawer.addVertex(latlng);
html, body {
height: 100%;
margin: 0;
}
#map {
width: 100%;
height: 100%;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.12/leaflet.draw.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.12/leaflet.draw.js"></script>
<div id='map'></div>

Leaflet.js: Use ctrl + scroll to zoom the map & Move map with two fingers on mobile

I'm using http://leafletjs.com/ ... is it possible to only:
Use ctrl + scroll to zoom the map
Move map with two fingers on mobile/tablet
... so similar what google maps does? With the comments ...
So far thats my setup:
// Leaflet Maps
var contactmap = L.map('contact-map', {
center: [41.3947688, 2.0787279],
zoom: 15,
scrollWheelZoom: false
});
There is an amazing library that does exactly that. Leaflet.GestureHandling
It is an add on to leaflet that works right of the box, it's also modular and can be installed using npm.
Here's a working example using leaflet and GestureHandling.
You can try it also on mobile.
P.S. It has multiple languages baked in:)
// Attach it as a handler to the map
const map = L.map('map', {
gestureHandling: true
}).setView([51.505, -0.09], 13);
// Add tile layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
#map {
height: 400px;
width: 400px;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.4.0/dist/leaflet.css"
integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
crossorigin=""/>
<link rel="stylesheet" href="//unpkg.com/leaflet-gesture-handling/dist/leaflet-gesture-handling.min.css"
type="text/css">
<script src="https://unpkg.com/leaflet#1.4.0/dist/leaflet.js"
integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg=="
crossorigin=""></script>
<script src="//unpkg.com/leaflet-gesture-handling"></script>
<div id="map"></div>
zoom map using ctrl + zoom. I did in custom way .
html code is below
<div id="map"></div>
css
.map-scroll:before {
content: 'Use ctrl + scroll to zoom the map';
position: absolute;
top: 50%;
left: 50%;
z-index: 999;
font-size: 34px;
}
.map-scroll:after {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
content: '';
background: #00000061;
z-index: 999;
}
jQuery
//disable default scroll
map.scrollWheelZoom.disable();
$("#map").bind('mousewheel DOMMouseScroll', function (event) {
event.stopPropagation();
if (event.ctrlKey == true) {
event.preventDefault();
map.scrollWheelZoom.enable();
$('#map').removeClass('map-scroll');
setTimeout(function(){
map.scrollWheelZoom.disable();
}, 1000);
} else {
map.scrollWheelZoom.disable();
$('#map').addClass('map-scroll');
}
});
$(window).bind('mousewheel DOMMouseScroll', function (event) {
$('#map').removeClass('map-scroll');
})
In simple way when user scroll on map then detect ctrl button is pressed or not then just I add one class that will showing message on map. and prevent screen zoom-in and zoom-out outside of map.
I managed to solve your second problem.
I used css for displaying the message using a ::after pseudo selector.
#map {
&.swiping::after {
content: 'Use two fingers to move the map';
}
}
And javascript to capture the touch events.
mapEl.addEventListener("touchstart", onTwoFingerDrag);
mapEl.addEventListener("touchend", onTwoFingerDrag);
function onTwoFingerDrag (e) {
if (e.type === 'touchstart' && e.touches.length === 1) {
e.currentTarget.classList.add('swiping')
} else {
e.currentTarget.classList.remove('swiping')
}
}
It checks if the type is a touchevent and if you are using 1 finger, if so it adds the class to the map with the message. If you use more than one finger it removes the class.
Working demo I suggest you using a mobile device.
Code pen from the demo

How can I add an icon to switch the mapboxgl style dynamically?

I want to add an icon as below in the mapboxgl view. Working with Angular2
When I click the icon it should automatically switch the styles (streets-v9, satelllite-v9)
I am following the link mapboxgl example
Did you see this API method?
https://www.mapbox.com/mapbox-gl-js/api/#map#setstyle
With that you can set a new style for the map when you e.g. click an icon or press a button or what ever you wish.
Take this as a reference to build upon:
https://jsfiddle.net/andi_lo/706pot8L/
mapboxgl.accessToken = 'pk.eyJ1IjoiZmFyYWRheTIiLCJhIjoiTUVHbDl5OCJ9.buFaqIdaIM3iXr1BOYKpsQ';
let map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-1.77, 52.73],
zoom: 3,
});
let icon = document.getElementById('icon');
icon.addEventListener('click', function(e) {
map.setStyle('mapbox://styles/mapbox/light-v9');
}, false)
#icon {
position: absolute;
top: 15px;
left: 15px;
color: black;
}
#map {
height: 500px;
}
<link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.css" rel="stylesheet"/>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.js"></script>
<div id="map"></div>
<button id="icon">
Switch layers
</button>
What you want is a "control" that switches layers. Mapbox-GL-JS doesn't include such a thing, nor is there one listed as a plugin (yet).
You should use Mapbox-GL-JS's iControl class to create the control, then add styling and behaviour following Mapbox's instructions:
function LayerSwitchControl() { }
LayerSwitchControl.prototype.onAdd = function(map) {
this._map = map;
this._container = document.createElement('div');
this._container.className = 'mapboxgl-ctrl';
// change this next line to include a layer-switching icon
this._container.textContent = 'Hello, world';
return this._container;
};
LayerSwitchControl.prototype.onRemove = function () {
this._container.parentNode.removeChild(this._container);
this._map = undefined;
};
You'll then need to add code to:
Add the control
Respond to click events as appropriate.
This is my working code,
This is zoom level control

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.