Offsett the center of leaflet map - leaflet

I have different text boxes in a scrollable overlay that triggers flyto() on different places on the map. Now each popup appears in the center of the div holding the map and gets covered by the overlay.
How can I offsett where the popup are shown?
Ive tried this:
const createMap = () => {
map = L.map('newmap', { zoomControl: false }).setView(mapData[0].coordinates, 7)
...
.addTo(map)
const offset = map.getSize().x * 0.4
map.panBy(new L.Point(-offset, 0), { animate: false })
}
But the map centeres itself when this function runs:
const markAndFly = () => {
currentItem.subscribe((newIndex) => {
//removes previous marker if value is set
if (marker !== null) {
map.removeLayer(marker)
}
const place = mapData[newIndex].coordinates
//adding marker to a first, and then new layer
marker = new L.marker(place, { icon: L.divIcon($useIcon) })
map.addLayer(marker)
//moves the map to the next place
map.flyTo(place, 7, {
animate: true,
duration: 1.5,
})
}
}
Ive tried including the offset-part to this last function, but the map still centers.
Any ideas?

Related

How to automatically add roofs as polygons in Mapbox

Currently I am getting streets from the geocoding api then displying houses in that street in satelite view. Is there a way to automatically detect house roofs and automatically draw polygons over them?
mapboxgl.accessToken = accessToken;
const map = new mapboxgl.Map({
container: 'map', // container ID
style: 'mapbox://styles/mapbox/satellite-v9', // style URL
center: [lng, lat], // starting position [lng, lat]
zoom: 17, // starting zoom
});
const draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
polygon: true,
trash: true
},
// Set mapbox-gl-draw to draw by default.
// The user does not have to click the polygon control button first.
defaultMode: 'draw_polygon'
});
map.addControl(draw)
map.addControl(new mapboxgl.NavigationControl())
map.on('draw.create', updateArea)
map.on('draw.delete', updateArea)
map.on('draw.update', updateArea)
function updateArea(e) {
const data = draw.getAll()
const answer = document.getElementById('calculated-area')
if (data.features.length > 0) {
const area = turf.area(data)
// Restrict the area to 2 decimal points.
const rounded_area = Math.round(area * 100) / 100
const areaInCM = rounded_area * 10000
answer.innerHTML =
`<p><strong>${areaInCM.toLocaleString('en-US')}</strong> square centimeters</p>`;
} else {
answer.innerHTML = ''
if (e.type !== 'draw.delete')
alert('Click the map to draw a polygon.')
}
}

Custom transform control for geoman

I am trying to add a custom transform control to geoman, to do certain transformations with polylines and polygons. I see that on edit, geoman draws hint lines above vertices etc. I would like my tool to highlight polylines/polygons with the same type of hints. Below is the skeleton of my action:
const ConvertAction = L.Toolbar2.Action.extend({
options: {
toolbarIcon: {
html:
'<div class="icon-maps icon-convert" title="Convert point"></div>',
tooltip: 'Convert point'
}
},
addHooks: () => {
// draw polygon
// map.pm.enableDraw();
changeConvert();
}
});
function changeConvert() {
convert = true;
map.eachLayer(function (layer) {
if (layer.feature && layer.feature.geometry.type === 'Point') {
layer._icon.style['pointer-events'] = 'auto';
}
});
}
Is there an internal function or something that I could use to outline shapes? When I enable Edit layers tool already built into the geoman, shapes are outlined for me. How could I achieve this from my code without having to reimplement the entire thing?
Thus far, after quickly reviewing geoman code, I was able to come up with:
const ConvertAction = L.Toolbar2.Action.extend({
options: {
toolbarIcon: {
html:
'<div class="icon-maps icon-convert" title="Convert point"></div>',
tooltip: 'Convert point'
}
},
addHooks: () => {
// draw polygon
// map.pm.enableDraw();
if (!convert) changeConvert();
else disableConvert();
}
});
function changeConvert() {
convert = true;
map.eachLayer(function (layer) {
if (
layer?.feature?.geometry.type === 'Polygon' ||
layer?.feature?.geometry.type === 'LineString'
) {
const coords = layer.getLatLngs();
const markerGroup = new L.LayerGroup();
markerGroup._pmTempLayer = true;
const createMarker = (latlng) => {
const marker = new L.Marker(latlng, {
draggable: true,
icon: L.divIcon({ className: 'marker-icon' })
});
layer.options.pane =
(map.pm.globalOptions.panes &&
map.pm.globalOptions.panes.vertexPane) ||
'markerPane';
marker._pmTempLayer = true;
markerGroup.addLayer(marker);
return marker;
};
const handleRing = (coordsArr) => {
// if there is another coords ring, go a level deep and do this again
if (Array.isArray(coordsArr[0])) {
return coordsArr.map(handleRing, this);
}
// the marker array, it includes only the markers of vertexes (no middle markers)
const ringArr = coordsArr.map(createMarker);
return ringArr;
};
const markers = handleRing(coords);
map.addLayer(markerGroup);
}
});
}
function disableConvert() {
convert = false;
map.eachLayer(function (layer) {
if (
layer.dragging &&
layer.options?.draggable === true &&
layer._pmTempLayer === true
) {
console.log('temp layer:', layer);
map.removeLayer(layer);
}
});
update();
}
Seems like an excessive amount of code, and reimplementation [and probably not as good the geoman version as I don't fully understand geoman code by far] of existing functionality.
How do I simplify/fix this?

adding layer on search for leaflet map changes polygon opacity

I have two leaflet maps which are loaded with geojson on the basis of a search button click. This shows some polygons with a style opacity 0.3 so you can see the street names under the polygons.
It works great except that any additional searches and loading of polygons starts to change the opacity of the polygon, making it more solid so you cant read the names of the streets under the polygon.
I try clearing the geojson layer before adding to the map, but the issue persists.
I have created a rough code pen of the issue here:
https://codepen.io/joomkit/pen/xxXgLPJ?editors=1111
Essentially just click the search button to load the layer no need to fill the listener runs a function and gets static data.
I have tried various methods to remove layer. A second click on the search is meant to clear the layer and load a new one. In the example it's just reloading the original data but the opacity is clearly demonstrated.
Main code is also below.
var geoMap2;
var lamap = new L.Map("map2", {
center: new L.LatLng(51.44094723464765, 0.048892332250943187),
// center: new L.LatLng(39.75621,-104.99404),
zoom: 14,
maxZoom: 18
});
var osm2 = L.tileLayer(
"https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png",
{
attribution:
'© OpenStreetMap contributors © CARTO',
subdomains: "abcd",
maxZoom: 18
}
);
lamap.addLayer(osm2);
searchButton.addEventListener("click", function (e) {
let searchQuery = inputSearch.value;
// searchOpenFunding(searchQuery);
setLaMap(data);
});
function setLaMap(data) {
removeLayers();
let geojsonFeatureCollection2 = {
type: "FeatureCollection",
features: setFeatureCollection2(data)
};
geoMap2 = L.geoJSON(geojsonFeatureCollection2, {
style: polyStyleLAMap,
onEachFeature: function myonEachFeatureLaMap(feature, layer) {
layer.myTag = "myGeoJSON";
}
}).addTo(lamap);
lamap.setMaxBounds(lamap.fitBounds(geoMap2.getBounds()));
lamap.setZoom(13);
}
var removeLayers = function () {
lamap.eachLayer(function (layer) {
if (layer.myTag && layer.myTag === "myGeoJSON") {
lamap.removeLayer(layer);
console.log("rem layer from ");
}
});
};
function setFeatureCollection2(data) {
for (const [key, item] of Object.entries(data)) {
// setup lealfet geojson collection from data mapit api is incomplete pe ritem so we build it here
geoJsonFeatures2.push({
type: "Feature",
properties: {
craftentryId: item.id,
areaId: item.mapitAreaId,
lsoacode: item.lsoacode,
localauthority: item.localauthority,
openForFunding: item.openForFunding,
fundableRegion: item.fundableRegion,
title: item.title,
popupContent: ""
},
geometry: item.geojson
});
}
return geoJsonFeatures2;
}
function polyStyleLAMap(feature) {
return {
fillColor: getFillColorLaMap(feature.properties.openForFunding),
weight: 1,
opacity: 1,
color: getBorderColor(feature.properties.openForFunding),
dashArray: "0",
fillOpacity: 0.3
};
}
function getFillColorLaMap(d) {
return d === true ? "#FFFFFF" : d === false ? "#FED976" : "#FED976";
}
function getBorderColor(d) {
return d === true ? "#0e9c12" : d === false ? "#adabab" : "#cccccc";
}
Look here https://codepen.io
The code I modified is:
// 029A, 029C
function setLaMap(data) {
removeLayers();
let geojsonFeatureCollection2 = {
type: "FeatureCollection",
features: setFeatureCollection2(data),
};
console.log(geojsonFeatureCollection2);
const geoMap2 = L.geoJSON(geojsonFeatureCollection2, {
style: polyStyleLAMap,
onEachFeature: function (feature, layer) {
layer.myTag = "myGeoJSON";
},
});
map.addLayer(geoMap2);
map.setMaxBounds(map.fitBounds(geoMap2.getBounds()));
// map.setZoom(13);
}
function removeLayers() {
map.eachLayer((layer) => {
if (layer.myTag && layer.myTag === "myGeoJSON") {
console.log(layer);
map.removeLayer(layer);
}
});
}
You need to keep the geojson layer in a global variable and remove it before over writing with the new layer data.
var geoMap2;
function setLaMap(data){
if(geoMap2) { // if geoMap2 is set remove it
lamap.removeLayer(geoMap2)
}
const geojsonFeatureCollection2 = {
"type": "FeatureCollection",
"features": setFeatureCollection2(data)
}
geoMap2 = L.geoJSON(geojsonFeatureCollection2, {
style: polyStyleLAMap,
onEachFeature: myonEachFeatureLaMap
})
.........

How to add marker onto polygon layer using leaflet.pm?

Lines and polygons are added without problems, but when trying to add markers on top of a polygon layer ("lyrPoly"), it interprets that I want to click on the polygon (e.g. opens popup) instead of adding marker. How can I avoid this? I am using leaflet.pm to add markers, linestrings and polygons.
This is the code for the marker:
map.on('pm:create', function(e) {
e.marker;
var type = e.layerType,
layer = e.layer;
$(document).ready(function() {
var jsnMarker = layer.toGeoJSON().geometry;
jsnMarker = {
type: "MultiPoint",
coordinates: [jsnMarker.coordinates]
};
})
});
$(function() {
$('.check').change(function() {
var data = $(this).val();
if (data == "versionOne") {
var markerStyle = {
draggable: false,
icon: customIcon,
};
var options = {
markerStyle,
}
map.pm.enableDraw('Marker', options);
} else if (data == "versionTwo") {
var markerStyle = {
draggable: false,
icon: otherIcon,
};
var options = {
markerStyle,
}
map.pm.enableDraw('Marker', options);
}
$('.check').trigger('change');
});
And inside the ajax function I use this:
lyrMarker = L.geoJSON(jsnMarker, {
pointToLayer: function (feature, latlng) {
if(feature.properties.marker_type=="versionOne"){
return L.marker(latlng, {
icon: customIcon
})
}else if
(feature.properties.marker_type=="versionTwo"){
return L.marker(latlng, {
icon: otherIcon
})
} ,
onEachFeature: forEachMarker
});
For the polygon-layer I have a corresponding "onEachFeature"-function that looks like this:
function forEachFeature(feature, layer) {
var att = feature.properties;
var popupContent =
"Popup-content" ;
layer.bindPopup(popupContent, {
offset: [0, -120]
});
layer.on("click", function (e) {
lyrPoly.setStyle(style); //resets layer colors
layer.setStyle(highlight); //highlights selected.
});
};
Adding marker to the background/basemap works fine, but not onto the polygon layer. Why is that, and what would be a good solution? I don't want to add the marker to the same layer as the polygons, but avoid polygons "getting in the way".
I've had ideas about making the polygon layer interactive: false while in adding-marker-mode, but haven't succeeded.
Update your click event and test if drawing mode is enabled:
function forEachFeature(feature, layer) {
var att = feature.properties;
var popupContent =
"Popup-content" ;
layer.bindPopup(popupContent, {
offset: [0, -120]
});
layer.on("click", function (e) {
if(!map.pm.Draw.Marker.enabled()){
lyrPoly.setStyle(style); //resets layer colors
layer.setStyle(highlight); //highlights selected.
}
});
};
Update
To disable the popup open event add following code at the top of your file. Before you create a Layer with a Popup:
L.Layer.include({
_openPopup: function (e) {
var layer = e.layer || e.target;
//This IF is new
if(map.pm.Draw.Marker.enabled()){
return;
}
if (!this._popup) {
return;
}
if (!this._map) {
return;
}
// prevent map click
L.DomEvent.stop(e);
// if this inherits from Path its a vector and we can just
// open the popup at the new location
if (layer instanceof L.Path) {
this.openPopup(e.layer || e.target, e.latlng);
return;
}
// otherwise treat it like a marker and figure out
// if we should toggle it open/closed
if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
this.closePopup();
} else {
this.openPopup(layer, e.latlng);
}
},
});
Example: https://jsfiddle.net/falkedesign/dg4rpcqe/

Open the popups of all markers that are visible on the map with a zoom > 10

I need to open all the markers that are visible on the map at Zoom,
10. I also use leaflet.markercluster.
Init map:
initMap() {
this.map = L.map('map', {
center: [55.55, 37.61],
zoom: 9,
layers: this.layer
})
this.tileLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution:
'© OpenStreetMap, ©'
})
this.tileLayer.addTo(this.map)
this.map.on('zoom', function(ev) {
???
})
Add marker layer:
this.markerLayer = new L.LayerGroup() // layer contain searched elements
// this.map.addLayer(this.markerLayer)
for (const i in data) {
...
const marker = new L.Marker(new L.latLng(loc), { title: title, icon: icon })// se property searched
marker.bindPopup(title)
this.markerLayer.addLayer(marker)
}
Use leaflet marker cluster:
this.markersLayer = L.markerClusterGroup({
iconCreateFunction: function(cluster) { ... },
singleMarkerMode: false
})
this.markersLayer.addLayer(this.markerLayer)
this.map.addLayer(this.markersLayer)
You should add your markers to an array before / after adding them to the map to access them easily.
var markers = [];
for (const i in data) {
const marker = new L.Marker(new L.latLng(loc), { title: title, icon: icon })
marker.bindPopup(title)
this.markerLayer.addLayer(marker)
markers.push(marker);
}
after that you can just loop through your markers array and use openPopUp function of marker to open popups of your markers programmatically.
for(i = 0; i< markers.length;i++){
markers[i].openPopup();
}