Cannot set style on leaflet L.geoJSON layer - leaflet

I am having a bit of trouble setting the style on a L.geoJSON based layer,my code looks like this:
var addProperties = function addProperties(prop,map)
{
//the API does not seem to support adding properties to an existing feature,
//the idea here is simple:
//(1) currentFeature.toGeoJson() needs to be called to obtain a json representation
//(2) set the properties on the geojson
//(3) create a new feature based on the geojson
//(4) remove res and add the new feature as res
var style = function style(feature){
var markerStyle = {
draggable: 'true',
icon: L.AwesomeMarkers.icon({
icon: 'link',
prefix: 'glyphicon',
markerColor: 'red',
spin: true
})
};
if(feature.geometry.type==='Point')
return markerStyle;
};
var onEachFeature = function onEachFeature(feature,layer){
console.log("Inside on each feature,checking to see if feature was passed to it ",feature);
layer.on('click',function(e){
//open display sidebar
console.log("Checking to see if setupTabs exists ",setupTabs);
setupTabs('#display-feature-tabs');
console.log("Checking to see if featureInfo exists ",featureInfo);
var featureInfoAPI =featureInfo('feature-properties');
featureInfoAPI.swap(feature.properties);
setTimeout(function() {
sidebar.show();
}, 100);
});
};
console.log("Inside add properties");
var geoJSON,feature;
if(res != null)
{
geoJSON = res.toGeoJSON();
geoJSON.properties = prop;
console.log(geoJSON);
feature = L.geoJson(geoJSON,{style:style,onEachFeature:onEachFeature});
console.log("The new feature that has been created ",feature);
removeFeature(map);
addFeature(feature);
feature.addTo(map);
}
};
I have also tried the style method as well,I am looking to add styles to the active layer for points(styles will also be added for lines and polylines by type).

To style point features, you should use pointToLayer option instead.

Related

Leaflet L.Icon marker not removing on Map reload

Map contains two types of markers
Circle icon is added by:
let circle = new customCircleMarker([item.latitude, item.longitude], {
color: '#2196F3',
fillColor: '#2196F3',
fillOpacity: 0.8,
radius: radM,
addressId: item.address_id
}).bindTooltip(`Address: <b>${item.address}</b><br/>
Patients from this address: <b>${item.total_patients}</b><br/>
Production: <b>$${item.total_production}</b><br/>`)
.addTo(this.mapInstance).on('click', this.circleClick);
Icon marker is added in the following method:
// create marker object, pass custom icon as option, pass content and options to popup, add to map
// create marker object, pass custom icon as option, pass content and options to popup, add to map
L.marker([item.latitude, item.longitude], { icon: chartIcon })
.bindTooltip(`Address: <b>${item.address}</b><br/>
Patients from this address: <b>${item.total_patients}</b><br/>
Production: <b>$${item.total_production}</b><br/>`)
.addTo(this.mapInstance).on('click', this.circleClick);
On clearing map Icon marker is not removed
Map clearing function:
if (this.mapInstance) {
for (let i in this.mapInstance._layers) {
if (this.mapInstance._layers[i]._path !== undefined) {
try {
this.mapInstance.removeLayer(this.mapInstance._layers[i]);
} catch (e) {
console.log('problem with ' + e + this.mapInstance._layers[i]);
}
}
}
}
You're checking for a _path property before removing. It will skip the L.Marker layers because they don't have a _path property, only vector layers (extended from L.Path) do.
If you ever need to delete only certain layer types from your map you are best off by grouping them in a grouping layer like L.LayerGroup or L.FeatureGroup and then using their clearLayers method:
var layerGroup = new L.LayerGroup([
new L.Marker(...),
new L.CircleMarker()
]).addTo(map);
layerGroup.clearLayers();
If that is not an option you could iterate the map's layers and then check the instance of the layer:
function customClearLayers () {
map.eachLayer(function (layer) {
if (layer instanceof L.Marker || layer instanceof L.CircleMarker) {
map.removeLayer(layer);
}
});
}

Leaflet Draw not taking properties when converting FeatureGroup to GeoJson

I'm unable to convert my Layer properties into the properties of the GEOJson object using Leaflet(0.7.7)/Leaflet.Draw(latest). My workflow is:
1 Create Map: var map = L.map('#map', options);
2 Create a FeatureGroup: features= new L.FeatureGroup();
3 Add to the Leaflet Map: map.addLayer(features);
4 On the draw:created event, I'm capturing e.layer and adding a bunch of properties:
var layer = e.layer;
layer.properties = { Title: 'Hello' };
features.addLayer(layer);
geo_features = features.toGeoJSON();
However, my geo_features always have empty property attributes in each of the features and I can't figure it out!
iH8's initial answer was almost correct.
To specify properties that will appear in a vector layer's GeoJSON export (i.e. through its .toGeoJSON() method), you have to fill its feature.type and feature.properties members:
var myVectorLayer = L.rectangle(...) // whatever
var feature = myVectorLayer.feature = myVectorLayer.feature || {};
feature.type = "Feature";
feature.properties = feature.properties || {};
feature.properties["Foo"] = "Bar";
Now myVectorLayer.toGeoJSON() returns a valid GeoJSON feature object represented by:
{
"type": "Feature",
"properties": {
"Foo": "Bar"
// More properties that may be pre-filled.
},
"geometry": // The vector geometry
}
A (kind of ugly workaround) is using a L.GeoJSON layer and add the drawn layer's GeoJSON to it by using it's addData method. Afterwards grab the last layer in the L.GeoJSON layer's _layers object. At that point the layer has a valid GeoJSON feature property you can edit:
var geojson = new L.GeoJSON().addTo(map);
var drawControl = new L.Control.Draw({
edit: {
featureGroup: geojson
}
}).addTo(map);
map.on('draw:created', function (e) {
geojson.addData(e.layer.toGeoJSON());
var layers = geojson._layers,
keys = Object.keys(layers),
key = keys[keys.length - 1],
layer = layers[key];
layer.feature.properties = {
'Foo': 'Bar'
};
});
For your L.GeoJSON call include feature callback onEachFeature to options
L.GeoJSON(featureData,{onEachFeature:function(feature,layer){
//console.log(feature,layer);
// do something like
feature.setStyle( convertLayerOptionsFromFeatureProperties( feature.properties ) );
}} )

MapBox - Add a clusterGroup clickable with Layer Control

I'm still learning and I'm a bit stuck. I may be trying to do to much at once. I have a MapBox map working great with a clickable layer menu taken from examples on the MapBox site. I also have a MarkerClusterGroup which also works and is always visible on the map. Is there a way I could somehow have the MarkerClusterGroup clickable on/off just like layers identified in var overlays = { ...
Below is the code that I think needs the help:
var layers = {
Streets: L.mapbox.tileLayer('mapbox.streets').addTo(map),
Satellite: L.mapbox.tileLayer('mapbox.satellite'),
Light: L.mapbox.tileLayer('mapbox.light'),
};
var overlays = {
DataA: L.mapbox.featureLayer().loadURL('/data/ctsnew.geojson'),
DataB: L.mapbox.featureLayer().loadURL('/data/selectZipcodes.geojson'),
};
// Since featureLayer is an asynchronous method, we use the `.on('ready'`
// call to only use its marker data once we know it is actually loaded.
Markers: L.mapbox.featureLayer('examples.map-h61e8o8e').on('ready', function(e) {
// The clusterGroup gets each marker in the group added to it
// once loaded, and then is added to the map
var clusterGroup = new L.MarkerClusterGroup();
e.target.eachLayer(function(layer) {
clusterGroup.addLayer(layer);
});
map.addLayer(clusterGroup);
});
Could be something as simple as misuse of brackets. Thanks in advance.
You have to include your Marker Cluster Group in your overlays object. For example you could instantiate it just before defining overlays, even if your Cluster Group is empty for now.
Then you fill it once it has downloaded its data.
var layers = {
Streets: L.mapbox.tileLayer('mapbox.streets').addTo(map),
Satellite: L.mapbox.tileLayer('mapbox.satellite'),
Light: L.mapbox.tileLayer('mapbox.light'),
};
var clusterGroup = L.markerClusterGroup();
var overlays = {
DataA: L.mapbox.featureLayer().loadURL('/data/ctsnew.geojson'),
DataB: L.mapbox.featureLayer().loadURL('/data/selectZipcodes.geojson'),
Markers: clusterGroup
};
// Since featureLayer is an asynchronous method, we use the `.on('ready'`
// call to only use its marker data once we know it is actually loaded.
L.mapbox.featureLayer('examples.map-h61e8o8e').on('ready', function(e) {
// The clusterGroup gets each marker in the group added to it
// once loaded, and then is added to the map
e.target.eachLayer(function(layer) {
clusterGroup.addLayer(layer);
});
map.addLayer(clusterGroup); // use that line if you want to automatically add the cluster group to the map once it has downloaded its data.
});

Leaflet: How to toggle GeoJSON feature properties from a single collection?

I have a single GeoJSON object that contains over 2000+ features and each feature is part of one category (i.e. "Electrical", "Military", etc). There are a total of about 38 categories.
Here's the schema example of my collection:
{"type":"Feature","properties":{"category":"Electrical","Name":"Plant No 1"},"geometry":{"type":"Point","coordinates":[81.73828125,62.59334083012024]}},{"type":"Feature","properties":{"category":"Electrical","Name":"Plane No 2"},"geometry":{"type":"Point","coordinates":[94.5703125,58.722598828043374]}},{"type":"Feature","properties":{"category":"Military","Name":"Base 1"},"geometry":{"type":"Point","coordinates":[104.4140625,62.91523303947614]}}
Here's my L.geoJson function that iterates through the
collection:
var allPoints = L.geoJson(myCollection, {
onEachFeature: function(feature, layer){
layer.bindPopup(L.Util.template(popTemplate, feature.properties));
},
"stylel": function(feature){
return { "color": legend[feature.properties.category]
}
}}).addTo(map);
How can I assign each category property to my L.control function so the user can toggle on/off the various categories from the collection? I could do this if I made each category a dataset and an individual geoJSOn layer, but that's too much work to do all 38 categories.
My attempt:
L.control.layers({
'Street Map': L.mapbox.tileLayer('mapbox.streets').addTo(map)
},{
'Electrical': myCollection[feature.properties.category["Electrical"]],
'Military': myCollection[feature.properties.category["Military"]]
});
Is there a better way to do this? Thanks!
You can simply assign your layers within the onEachFeature function. You could even automate the creation of Layer Groups for each category.
Result:
var categories = {},
category;
function onEachFeature(feature, layer) {
layer.bindPopup(L.Util.template(popTemplate, feature.properties));
category = feature.properties.category;
// Initialize the category array if not already set.
if (typeof categories[category] === "undefined") {
categories[category] = [];
}
categories[category].push(layer);
}
// Use function onEachFeature in your L.geoJson initialization.
var overlays = {},
categoryName,
categoryArray;
for (categoryName in categories) {
categoryArray = categories[categoryName];
overlays[categoryName] = L.layerGroup(categoryArray);
}
L.control.layers(basemaps, overlays).addTo(map);
EDIT: replaced overlays to be a mapping instead of an array.
Iterate your GeoJSON collection and create multiple L.GeoJSON layers, one per category and add them as overlays to your L.Control.Layers instance.
var controlLayers = L.control.layers({
'Street Map': L.mapbox.tileLayer('mapbox.streets').addTo(map)
}).addTo(map);
// Object to store category layers
var overlays = {};
// Iterate the collection
collection.features.forEach(function (feature) {
var category = feature.properties.category;
// Check if there's already an overlay for this category
if (!overlays[category]) {
// Create and store new layer in overlays object
overlays[category] = new L.GeoJSON(null, {
'onEachFeature': function () {},
'style': function () {}
});
// Add layer/title to control
controlLayers.addOverlay(overlays[category], category);
}
// Add feature to corresponding layer
overlays[category].addData(feature);
});
Here's an example on Plunker: http://plnkr.co/edit/Zv2xwv?p=preview

Working with openlayers and typescript classes

/// <reference path="openlayers.d.ts" />
class MapComponent {
element: HTMLElement;
map: OpenLayers.Map;
constructor(element: HTMLElement) {
// Setup our map object
this.element = element;
this.map = new OpenLayers.Map(this.element);
}
init() {
// Setup our two layer objects
var osm_layer_map = new OpenLayers.Layer.OSM("OSM");
// Add layers to the map
this.map.addLayers([osm_layer_map]);
// Add a layer switcher control
this.map.addControl(new OpenLayers.Control.LayerSwitcher({}));
// Zoom the map to the max extent
if (!this.map.getCenter()) {
this.map.zoomToMaxExtent();
}
}
}
window.onload = () => {
var el = document.getElementById('map');
var mc = new MapComponent(el);
mc.init();
}
I have the above piece of code to work with a simple HTML file with only 1 of ID, 'map' with style: height and width # 500px.
I have tried several other ways to get the map to display but so far all i got was a white page (blank).
Can anybody point me in the right direction?
Solutions tried so far:
using jquery with ready function
replace window.onload with a call direct from the html, <script><script/>
place document.getElementById() in the new OpenLayers.Map(here); when first creating this.map
placing the window.onload call above and below (currently)
using export class or public init() or both
As of now, I just want it to work.
Seems that creating the map with the element provided and later defining the options doesn't work.
Instead either initialize the map with options
var options = {
projection: "EPSG:3857",
maxExtent: new OpenLayers.Bounds(-200000, -200000, 200000, 200000),
center: new OpenLayers.LonLat(-12356463.476333, 5621521.4854095)
};
this.map = new OpenLayers.Map(this.element, options);
Or call this.map.render(this.element) at the end of your init method.
Also make sure your div is actually visible and has some size specified, otherwise it might be not visible...