Hello
I try to implement a leaflet pluging, for display a local hosted shapefile. The display of the shapefile work, but i want to add a layer control (for togle shapefile layer).
the plugin link : https://github.com/calvinmetcalf/shapefile-js
the demo link :http://leaflet.calvinmetcalf.com/#3/32.69/10.55
I want to implement the layer control on demo page
<script>
var m = L.map('map').setView([0, 0 ], 10);
var watercolor =
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: 'Map tiles by <a href="http://stamen.com">Stamen
Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY
3.0</a> — Map data © OpenStreetMap contributors, CC-BY-SA'
}).addTo(m);
var shpfile = new L.Shapefile('Fr_adm.zip', {
onEachFeature: function(feature, layer) {
if (feature.properties) {
layer.bindPopup(Object.keys(feature.properties).map(function(k) {
return k + ": " + feature.properties[k];
}).join("<br />"), {
maxHeight: 200
});
}
}
});
shpfile.addTo(m);
shpfile.once("data:loaded", function() {
console.log("finished loaded shapefile");
});
// initialize stylable leaflet control widget
var control = L.control.UniForm(null, overlayMaps, {
collapsed: false,
position: 'topright'
}
);
// add control widget to map and html dom.
control.addTo(m);
</script>
The shapefile Fr_adm.zip is displayed, but no layer control.
Thank for your help.
Your problem is that overlayMaps is not defined. Open your console and you should see an error stating this.
Looking at the documentation for L.control.UniForm maps (an extension of leaflet), we can see:
/ **
* standard leaflet code.
** /
// initialize stylable leaflet control widget
var control = L.control.UniForm(null, overlayMaps, {
collapsed: false,
position: 'topright'
}
);
What is overlayMaps in this? To answer we need to take a look at the documentation for standard leaflet code. overlayMaps is a list of key, object pairs:
... we’ll create two objects. One will contain our base layers and
one will contain our overlays. These are just simple objects with
key/value pairs. The key sets the text for the layer in the control
(e.g. “Streets”), while the corresponding value is a reference to the
layer (e.g. streets).
var baseMaps = {
"Grayscale": grayscale,
"Streets": streets
};
var overlayMaps = {
"Cities": cities
};
Consequently, overlayMaps in your example should look like:
var overlayMaps = {"Name To Display":shpfile }
Once defined you should be able to create your layer control as normal.
i see a mistake in the code, no overlayer value. So i try with this :
<script type="text/javascript" charset="UTF-8">
//----------------
var watercolor = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
});
var geo = L.geoJson({features:[]},{onEachFeature:function popUp(f,l){
var out = [];
if (f.properties){
for(var key in f.properties){
out.push(key+": "+f.properties[key]);
}
l.bindPopup(out.join("<br />"));
}
}});
var m = L.map('map', {
center: [10, -1],
zoom: 6,
layers: [watercolor, geo ]
});
//}}).addTo(m);
var base = 'Fr_admin.zip';
shp(base).then(function(data){
geo.addData(data);
});
var baseMaps = {
"BaseLayer": watercolor
};
var overlays = {
"shapefile": geo
};
L.control.layers(baseMaps,overlays).addTo(m);
</script>
It 's work, i can chose to display the shapefile or not.
But dont return all segmentation like here :http://leaflet.calvinmetcalf.com/#3/32.69/10.55
thank you
Related
I already saw the same question here: StackOverflow
But none of the answers helped or atleast I didn't understand it.
If I place a new marker on the map by clicking and then remove the marker by clicking again and then attempt to zoom, I get the error:
TypeError: Cannot read properties of null (reading '_latLngToNewLayerPoint')
at NewClass._animateZoom
A more simple example of this happening is when I click a marker to see the popup. After seeing the popup, I close the popup and then try to zoom and I get errors on every zoom.
When I first close the popup, I get a warning saying that listener not found which is odd, because I close the popup by simply clicking on the map and I DO have a listener for when I click on the map.
here is the code:
var mapLink = 'Esri';
var wholink = 'i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community';
var satelliteLayer = L.tileLayer(
'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
attribution: '© ' + mapLink + ', ' + wholink,
maxZoom: 18,
});
var osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap'
});
var mapboxUrl = 'https://api.mapbox.com/styles/v1/johnmichel/ciobach7h0084b3nf482gfvvr/tiles/{z}/{x}/{y}?access_token=pk.eyJ1Ijoiam9obm1pY2hlbCIsImEiOiJjaW9iOW1vbHUwMGEzdnJseWNranhiMHpxIn0.leVOjMBazNl6v4h9MT7Glw';
var mapboxAttribution = 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox'
var streets = L.tileLayer(mapboxUrl, { id: 'mapbox/streets-v11', tileSize: 512, zoomOffset: -1, attribution: mapboxAttribution });
var map = L.map("mapContainer", {
center: [lat, lng],
zoom: 10,
layers: [osm, satelliteLayer, streets],
maxZoom: 18,
minZoom: 10,
smoothWheelZoom: true, // enable smooth zoom
smoothSensitivity: 1, // zoom speed. default is 1
smoothZoom: true,
smoothZoomDelay: 1000 // Default to 1000
}).on('click', this.onMapClick);
map.on('moveend', this.onMapMoved)
var baseMaps = {
"OpenStreetMap": osm,
"Satellite": satelliteLayer,
"Mapbox Streets": streets
};
var kayakLaunchLayer = L.layerGroup([]);
var yourPin = L.layerGroup([]);
this.markerLayerGroup = L.layerGroup();
this.singleMarkerLayerGroup = L.layerGroup();
var layerControl = L.control.layers(baseMaps).addTo(map);
map.addLayer(kayakLaunchLayer);
map.addLayer(yourPin);
this.markerLayerGroup = kayakLaunchLayer;
this.singleMarkerLayerGroup = yourPin;
// layerControl.addOverlay(this.markerLayerGroup, "Kayak Launches");
// layerControl.addOverlay(this.singleMarkerLayerGroup, "Your Pin");
map.invalidateSize();
this.map = map;
this.map is a variable defined in data in my Vue component and so is this.singleMarkerLayerGroup and this.markerLayerGroup.
And this is the function where I actually add the markers to the this.markerLayerGroup so that I can see them as an overlay on the map:
var lat = launch.loc.coordinates[1];
var lng = launch.loc.coordinates[0];
var marker = L.marker([lat, lng]).addTo(this.markerLayerGroup).on('click', this.onMarkerClick);
var photoImgwithContent = `<h2>${launch.name}</h2><img src="${launch.images[0]}" height="150px" width="150px"/><h3></h3>${this.capitalizeFirstLetter(launch.waterType)}`;
marker.bindPopup(photoImgwithContent);
Now what is wrong with any of this? I have restructured the code to follow documentation as closely as possible and still stumped.
But strangely, if I turn off zoom animation by applying this map option: zoomAnimation:false, then the error is gone but the map look terrible without zoom animation.
This seems like a similar situation as in Uncaught TypeError: this._map is null (Vue.js 3, Leaflet), since you seem to use Vue.js 3, and the error occurs when zooming the map after some Layers/Popup are removed:
the culprit is the proxying of this.map by Vue, which seems to interfere with Leaflet events (un)binding. It looks like Vue 3 now automatically performs deep proxying
A solution consists in "unwrapping" / un-proxying the map and the Layer Groups (i.e. all Leaflet objects that you store in this Vue component data) whenever you use them, e.g. with Vue3's toRaw utility function:
var marker = L.marker([lat, lng])
.addTo(toRaw(this.markerLayerGroup));
See also the Vue 3 guide to Reduce Reactivity Overhead for Large Immutable Structures.
I have a Leaflet map with markers and filters (checkboxes) and I would like to count the number of markers as the filters change.
I added this code which I found here Getting the count of markers in a layer in leaflet :
var counter = 0;
function onEachFeature(feature, layer) {
counter++;
console.log(counter)
}
L.geoJson(geojsonFeature, {
onEachFeature: onEachFeature
}).addTo(map);
The code works well but returns a NaN property. I would like to know if there is a way to reach the counter result as I would like to insert it in a div to my Leaflet Map?
Thanks a lot!
The first question is, do you have a geojson feature / geojson group or only markers?
If you have a GeoJSON group:
The simplest way would be to get all child layers of the geojson group, which is the marker count:
var group = L.geoJson(geojsonFeature, {
onEachFeature: onEachFeature
}).addTo(map);
var counter = group.getLayers().length;
If you have only markers on the map (not in a group):
You can loop through all layers of the map and check if the layer is existing on the map:
var counter = 0;
map.eachLayer((layer)=>{
if(layer instanceof L.Marker){
counter++;
}
});
Displaying the data as Control
L.MarkerCounterControl = L.Control.extend({
options: {
position: 'topright'
//control position - allowed: 'topleft', 'topright', 'bottomleft', 'bottomright'
},
onAdd: function (map) {
var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control fitall');
this.button = L.DomUtil.create('a', '', container);
this.button.style.width = 'auto';
this.button.style.padding = '2px 5px';
this.button.innerHTML = '0 Markers';
L.DomEvent.disableClickPropagation(this.button);
return container;
},
setCount(count) {
this.button.innerHTML = count+' Markers';
}
});
var control = new L.MarkerCounterControl().addTo(map)
control.setCount(10)
You can call after each layer change control.setCount(counter)
Demo: https://plnkr.co/edit/dyQKVQFDm5sBHzUK
I tried this. It does give me the correct number, but I am still tinkering with how to put it inside the L.control
var lg_cityMarkers = L.layerGroup([romaMarker, fidenaeMarker, antemnaeMarker, caeninaMarker, politoriumMarker]);
var totalCities = lg_cityMarkers.getLayers().length;
alert(totalCities);
You can see this live on this page: https://elcuentoderoma.com/rome/
Disclaimer: I am affiliated with this site.
I am working with the application Beta_Here which uses leaflet plugins, all libraries are local except for few(css related)
Usage of application live
First View:This application get input from user and set the distance
calculation formula accordingly....
Second View : After entering input e.g 9, second view will be loaded
where we can draw shapes....
Introduction
I have setup the script which will load two imageoverlays(layers) and
we can toggle them from top right and we can draw or measure from
bottom left....
Problem
When we draw shapes or put markers on an image, controls work nearly
perfect but when we toggle the layers, there starts the problem....
all shapes go to the background or (it seems they disappeared)
Main Question
How can we bind the drawings and marker to the specific
layer(imageoverlay) if there is a way as we can see the drawing are
not bind with the images but the map container..... (Pardon me if you
feel i am doing something stupid because i have limited knowledge
about layers so i came up with my question here....
If someone has idea about how to solve this problem, please do help or
any kind of reference will be appreciated... Thanks for your time
Working Script
var map = L.map('map', {
minZoom: 1,
maxZoom: 4,
center: [0, 0],
zoom: 0,
crs: L.CRS.Simple
});
// dimensions of the image
var w = 3200,
h = 1900,
mainurl = 'assets/img/isbimg.jpg';
childurl = 'assets/img/fjmap.png';
// calculate the edges of the image, in coordinate space
var southWest = map.unproject([0, h], map.getMaxZoom() - 1);
var northEast = map.unproject([w, 0], map.getMaxZoom() - 1);
var bounds = new L.LatLngBounds(southWest, northEast);
var featureGroup = L.featureGroup().addTo(map);
var drawControl = new L.Control.Draw({
edit: {
featureGroup: featureGroup
},
draw: {
polygon: true,
polyline: true,
rectangle: true,
circle: true,
marker: true
}
}).addTo(map);
map.on('draw:created', showPolygonArea);
map.on('draw:edited', showPolygonAreaEdited);
// add the image overlay,so that it covers the entire map
L.control.layers({
Main: L.imageOverlay(mainurl, bounds),
Child: L.imageOverlay(childurl, bounds)
}, null, { collapsed: false }).addTo(map);
L.control.nanomeasure({ nanometersPerPixel: 10000 }).addTo(map);
// tell leaflet that the map is exactly as big as the image
map.setMaxBounds(bounds);
L.tileLayer({
attribution: 'SmartMinds',
maxZoom: 18
}).addTo(map);
//polygon area customization
function showPolygonAreaEdited(e) {
e.layers.eachLayer(function (layer) {
showPolygonArea({ layer: layer });
});
}
function showPolygonArea(e) {
var userInputCustom = prompt("Please enter image name : choose between a to f");
featureGroup.addLayer(e.layer);
e.layer.bindPopup("<div style='width:200px;height:200px;background-image: url(assets/img/" + userInputCustom + ".png);background-size: 195px 195px;;background-repeat: no-repeat;'></div>");
e.layer.openPopup();
}
});
I would contain those FeatureGroup and ImageOverlay pairs into L.LayerGroup's. Then you can switch between those groups. Then you can keep track of the currently selected group, and add your features to the featurelayer of that group. I can explain it better with code through comments:
Basic map, nothing special:
var map = L.map('map', {
'center': [0, 0],
'zoom': 1,
'layers': [
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
'attribution': 'Map data © OpenStreetMap contributors'
})
]
});
// Bounds for the map and imageoverlays
var bounds = L.latLngBounds([[40.712216, -74.22655],[40.773941, -74.12544]]);
// Set bounds on the map
map.fitBounds(bounds);
The grouping part:
// New layergroup, note it's not added to the map yet
var layerGroup = new L.LayerGroup(),
imageOverlayUrl = 'https://placeholdit.imgix.net/~text?txtsize=33&txt=Overlay 1&w=294&h=238',
// New imageoverlay added to the layergroup
imageOverlay = new L.ImageOverlay(imageOverlayUrl, bounds).addTo(layerGroup),
// New featuregroup added to the layergroup
featureGroup = new L.FeatureGroup().addTo(layerGroup);
// Second layergroup not added to the map yet
var layerGroup2 = new L.LayerGroup(),
imageOverlayUrl2 = 'https://placeholdit.imgix.net/~text?txtsize=33&txt=Overlay 2&w=294&h=238',
// New imageoverlay added to the second layergroup
imageOverlay2 = new L.imageOverlay(imageOverlayUrl2, bounds).addTo(layerGroup2),
// New featuregroup added to the second layergroup
featureGroup2 = new L.FeatureGroup().addTo(layerGroup2);
Default drawcontrol and layercontrol with both layergroups added as baselayers:
var layerControl = new L.control.layers({
'Group 1': layerGroup,
'Group 2': layerGroup2
}).addTo(map);
var drawControl = new L.Control.Draw().addTo(map);
Here's where the magic happens ;) :
// Variable to hold the selected layergroup's featuregroup.
var currentFeatureGroup;
// Catch the layer change event
map.on('baselayerchange', function (layersControlEvent) {
// Loop over the layers contained in the current group
layersControlEvent.layer.eachLayer(function (layer) {
// If it's the imageoverlay make sure it's in the background
if (layer instanceof L.ImageOverlay) {
layer.bringToBack();
// If not then it's the featuregroup, reference with variable.
} else {
currentFeatureGroup = layer;
}
});
});
// Catch draw created event
map.on('draw:created', function (e) {
// Store created feature into the current featuregroup
currentFeatureGroup.addLayer(e.layer);
});
That's it. Pretty basic just meant as an example but it does what you want it to do. A real implementation would look different, with errorhandling because for instance when you draw and have no baselayer/overlay selected it fail etc. Here's a working example on Plunker to play with: http://plnkr.co/edit/6cGceX?p=preview
Pretty simple question: How can I make the map markers in Leaflet clickable and route the user to an other page? Every marker has its own page.
I've tried the following without success; somehow all the markers point to the same page, which is the last assigned URI.
var markers = [
{ coords: [51.505, -0.09], uri: '/some-page' },
...
];
for(x in markers)
{
L.marker(markers[x].coords).on('click', function() {
window.location = markers[x].uri;
}).addTo(map);
}
This issue is really driving me nuts.
Okay, I finally came to a solution; when a marker is added to the map it gets assigned an ID called "_leaflet_id". This can be fetched through the target object, and also set to a custom value after it has been added to the map.
So the final solution is simply:
var x = markers.length;
while(x--)
{
L.marker(markers[x].coords).on('click', function(e) {
window.location = markers[e.target._leaflet_id].uri;
}).addTo(map)._leaflet_id = x;
}
(I replaced the for-in loop with a reversed while loop)
You could also use a popup which can display HTML
marker.bindPopup(htmlString);
i found a similar code which may help you. here is jsfiddle link http://jsfiddle.net/farhatabbas/qeJ78/
$(document).ready(function () {
init_map();
add_marker();
});
var map;
function init_map() {
map = L.map('map').setView([37.8, -96], 4);
L.tileLayer('http://{s}.tile.cloudmade.com/{key}/22677/256/{z}/{x}/{y}.png', {
attribution: 'Map data © 2011 OpenStreetMap contributors, Imagery © 2012 CloudMade',
key: 'BC9A493B41014CAABB98F0471D759707'
}).addTo(map);
}
function add_marker() {
var points = [
["P1", 43.059908, -89.442229, "http://www.url_address_01.com/"],
["P2", 43.058618, -89.442032, "http://www.url_address_02.com/"],
["P3", 43.058618, -86.441726, "http://www.url_address_03.com/"]
];
var marker = [];
var i;
for (i = 0; i < points.length; i++) {
marker[i] = new L.Marker([points[i][1], points[i][2]], {
win_url: points[i][3]
});
marker[i].addTo(map);
marker[i].on('click', onClick);
};
}
function onClick(e) {
console.log(this.options.win_url);
window.open(this.options.win_url);
}
I wrote a script that first geocodes an address and then displays a map of that address.
The trouble is, it only works in Chrome / Chromium. Other browsers (Firefox 10 & IE9) display a grey box. A problem that could be related, if I add a marker to the map, the marker does not show in Chrome.
I know that :
I connect with the API successfully with my API key.
The address is properly geocoded.
I use jQuery UI dialog to display the map. This, however, does not seem to be a problem. Removing the dialog and using a static div creates the same "grey box" result.
Below is my script, how I invoke it, and the website that I am using this on.
Here's the script:
function Map(properties)
{
var that = this;
// the HTML div
this.element = properties.element;
// address string to geocode
this.address = properties.address;
// title to use on the map and on the jQuery dialog
this.title = properties.title;
this.latlng = null;
this.map = null;
this.markers = [];
// geocode address and callback
new google.maps.Geocoder().geocode({'address': this.address}, function(data)
{
// geocoded latitude / longitude object
that.latlng = data[0].geometry.location;
// map options
var options =
{
zoom: 16,
center: that.latlng,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create a map
that.map = new google.maps.Map(that.element, options);
// add a marker
that.markers.push(new google.maps.Marker({map: that.map,
position: that.latlng,
title: that.title + "\n" +
that.address}));
});
this.get_google_map = function()
{
return that.map;
}
// creates a jQuery UI dialog with a map
this.show_in_dialog = function()
{
// because the dialog can resize, we need to inform the map about this
$(that.element).dialog({ width: 400, height: 300, title: that.title,
resizeStop: function(event)
{
google.maps.event.trigger(that.map, 'resize');
},
open: function(event)
{
google.maps.event.trigger(that.map, 'resize');
}});
}
this.center = function()
{
that.map.setCenter(that.latlng);
}
}
Here's how I invoke it :
// grab the address via HTML5 attribute
var address = $("#address").attr("data-address");
// ... and the title
var title = $("#address").attr("data-title") + " Map";
var map_element = document.createElement('div');
// append the newly created element to the body
$("body").append(map_element);
// create my own map object
var map = new Map({ element : map_element,
address : address,
title : title });
// bind a link to show the map
$("#map_link").click(function()
{
map.center();
map.show_in_dialog();
return false;
});
And here's the URL of the problem (click on map):
http://testing.fordservicecoupons.com/dealer/30000/premium_coupon_page
Last but not least, I combine and obfuscate my JavaScripts, so what you see above is not exactly the same as in the source on the website.
This doesn't look good:
resizeStop: function(event) { google.maps.event.trigger(that.element, 'resize'); },
open: function(event) { google.maps.event.trigger(that.element, 'resize'); }
you trigger the resize-event on the element that contains the map(that.element), but you must trigger resize on the google.maps.Map-object (what should be that.map in this case)
Wow... Here was the issue.
The layout that I built was a fluid layout. So, one of the first CSS rules that I have written was:
img, div { max-width: 100%; }
So that divs and images can scale. Well, for whatever reason, Google maps DOES NOT like this rule with the end result being a grey box.
And so I added another rule - an exception for Google maps:
img.no_fluid, div.no_fluid { max-width: none; }
And then, in javascript:
// AFTER DIALOG CREATION
$(dialog).find('*').addClass("no_fluid");
The find('*') will get us all the descendants.
Viola!