Styling a geoJSON Feature Layer in MapBox - javascript

I just started playing with MapBox and am running into a confusing issue. I'm creating a map with a geoJSON layer using this code:
var map = L.mapbox.map('map', '<MapBoxID>');
var zipLayer = L.mapbox.featureLayer('data/blah.json');
zipLayer.addTo(map);
zipLayer.setStyle({color: 'red'});
The map appears and shows the geoJSON, but it ignores the styling. When I copy that last line into the JS console in my browser, it works fine, though.
What am I missing here? Also, I've tried at least a dozen different ways of including the style in the options directly in the featureLayer() call, but nothing has worked. How do I specify the style when creating the feature layer?

I'm guessing a bit here, since I don't know the Mapbox JS very well, but it sounds a lot like an async error. Strangely, I don't see anything in the Mapbox or Leaflet APIs about a callback for this function. But, you can pass straight GeoJSON to featureLayer(), so I'd suggest using jQuery (or your XHR library of choice) to grab the data:
var map = L.mapbox.map('map', '<MapBoxID>');
var zipLayer;
$.getJSON('data/blah.json', function(data) {
zipLayer = L.mapbox.featureLayer(data);
zipLayer.addTo(map);
zipLayer.setStyle({color: 'red'});
});
Hopefully that'll do the trick.

I would go the route of using the built-in featureLayer function, then listening for it to be ready. This should help get you pointed in the right direction:
var featureLayer = L.mapbox.featureLayer()
.loadURL('/example-single.geojson')
.on('ready', function(layer) {
this.eachLayer(function(marker) {
// See the following for styling hints:
// https://help.github.com/articles/mapping-geojson-files-on-github#styling-features
marker.setIcon(L.mapbox.marker.icon({
'marker-color': '#CC0000'
}));
});
})
.addTo(map);

Have you tried adding the zipLayer after setting the style?

Related

How to add markers to leaflet map with tabletop.js?

I'm using this quite nice guide to add markers from a Google sheet to a basic leaflet.js map:
https://rdrn.me/leaflet-maps-google-sheets/
The problem is, using these code snippets here i get all the data logged and returned in the console, but none of the points appear on the map itself.
This is probably some really basic JavaScript issue that i'm not able to see. Sorry, still learning.
Here's a jfiddle, linking to a demo sheets with one marker point
https://jsfiddle.net/xfs19cz7/1/
with the map part:
function init() {
Tabletop.init({
key: '*url to gsheets here*',
callback: myFunction,
simpleSheet: true
})
}
window.addEventListener('DOMContentLoaded', init)
function myFunction(data, tabletop) {
console.log(data);
}
var map = L.map('map-div').setView([64.6220498,25.5689638], 5);
var basemap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Basemap (c) OpenStreetMap',
minZoom: 5,
maxZoom: 18
});
basemap.addTo(map);
function addPoints(data, tabletop) {
for (var row in data) {
var marker = L.marker([
data[row].Latitude,
data[row].Longitude
]).addTo(map);
marker.bindPopup('<strong>' + data[row].Info + '</strong>');
}
}
This should add one point to a basic map. Now actually the map is not at all rendered, and no marker shows up. I can't find any issues in the code making the map show up blank, but there probably are some.
The marker from gsheets is however logged in the console, i suspect there is something missing in my code relating to really basic javascript functions / looping / sloppy syntax.
Also tried the init() and addPoints(data, tabletop) parts to a map i had where the map with the same basemap link, which rendereded OK. Adding this still left the map rendering, but no markers showed up. Again, the gsheets was loaded as an array of objects.
Could anyone point me to this, probably very basic, issue in the code?
edit:
callback: myFunction,
line above needs to be changed to
callback: addPoints,
also, init function needs to be called and position set to absolute. Thanks for the working fiddle in answer marked as correct below.
Fixes
Try setting map position absolute
calling the init() function
Working fiddle

Sort order of layers in Leaflet layer control

I have created a leaflet map to display some geoJSON data in separate vertical layers.
It works fine, except that the layer control will list the options out of order, i.e. "layer 0, layer 2, layer 1" as opposed to "layer 0, layer 1, layer 2". The data is loaded through AJAX calls, and so the layers are added to the control in the order which the calls complete, i.e. basically random.
According to the documentation for the layer control [ https://leafletjs.com/reference-1.3.0.html#control-layers ], if sortLayers is set to true, the default is to sort the layers by name, but that seems to not be happening.
So, I have tried passing in a sort function explicitly, but the doc does not give an example of what one should look like.
When my code looks like this:
var layerControlOptions = {
hideSingleBase : true,
autoZIndex : true,
sortLayers: true}
var layerControl = L.control.layers(null, null, layerControlOptions).addTo(map);
The control looks like this:
layer control with sortLayers: true and no sortFunction being defined
My best guess at writing my own sorting function:
var layerControlOptions = {
hideSingleBase : true,
autoZIndex : true,
sortLayers: true,
sortFunction: function(layerA, layerB, nameA, nameB){return
[nameA,nameB].sort();}}
var layerControl = L.control.layers(null, null,
layerControlOptions).addTo(map);
With this, the layer names appear in the same order as when no function is given. Not sure if I am writing it incorrectly, or it is simply equivalent to the default, which is returning the wrong order for some reason.
Seems like the same issue here: Leaflet Layer Control: Ordering
which has no accepted answer and makes no mention of the layer control options. I did try the solution which is proposed here, but it did not fix the problem either.
Any help on this would be greatly appreciated, thank you.
You may look at this solution to order layers in the controls (it does not order layers). I've mainly borrowed code from Leaflet specs code;
If you have not problem to sort things in the control but you have issue related to loading JSON/GeoJSON (hence layer too) in a particular order, you may want to combine fetch with Promise.all but it's not anymore about Leaflet but about JavaScript knowledge (look at this page to try to grasp fetch + Promise.all)
You can add the layers as you normally would and then sort them with a function that removes labels and re-add them as sorted.
function sortLabels() {
var controlLayers = {}
layerControl._layers.forEach(function(x) {
if (x.overlay) {
controlLayers[x.name] = x.layer
}
});
names = Object.keys(controlLayers).sort()
//remove and add sorted layernames
names.forEach(x => layerControl.removeLayer(controlLayers[x]))
names.forEach(x => layerControl.addOverlay(controlLayers[x], x))
}
var baseMaps = { "OpenStreetMap": tile_layer_osm, "ESRI World Imagery" : esri_satelite };
var overlayMaps = {nameC: layerC, nameA: layerA, nameB: layerB}
var layerControl = L.control.layers(baseMaps, overlayMaps, null, {collapsed: false}).addTo(map);
sortLabels()

d3 + leaflet path fill issue

I'm working on a timelapsed filled map using Leaflet as a baselayer and a d3 topojson file so I can color in some countries. I used http://bost.ocks.org/mike/leaflet/ to get started, and everything was going great until I tried to shade in the Russian Federation. Its landmass spans non-contiguous tiles, and when I try to add a fill style to my #RUS path, it behaves anomalously. Example is here: http://dataviz.du.edu/projects/scratch/study_abroad.html
Example will take 1.5 s to render completely, it shades 3 countries, with the Russian Federation shading last.
This example uses a topojson file that I have used in other, pure d3 projects and have filled #RUS in those contexts without this issue.
Can anyone help? Thanks in advance.
This example uses a topojson file that I have used in other, pure d3 projects and have filled #RUS in those contexts without this issue.
You must be mistaken because your TopoJSON file is actually corrupt. See here an example with that file straight from your server: http://plnkr.co/edit/QOTwV3?p=preview Mind that i'm using plain TopoJSON and Leaflet's GeoJSON layer but it's yielding the exact same results.
PS. Is there any reason as to why you're using D3 for this? Asking because what i see you doing can be done just using Leaflet and TopoJSON, without D3. Here's a simple example:
function delay(features) {
var geojsonLayer = new L.GeoJSON(null, {
style: getStyle,
}).addTo(map);
var delay = 100;
features.forEach(function(feature) {
delay = delay + 100;
setTimeout(function() {
geojsonLayer.addData(feature);
}, delay);
});
}
var url = 'http://crossorigin.me/http://dataviz.du.edu/projects/scratch/worldnew.json';
$.getJSON(url, function(data) {
var geojsonData = topojson.feature(data, data.objects.test);
delay(geojsonData.features);
});

Accessing Leaflet.js GeoJson features from outside

I want to interact with a leaflet powered map's GeoJson overlay (polygons) from outside of L.'s realm, but I don't seem to be able to access objects created by L..
Interaction would include:
getBounds(myFeature)
fitBounds(myFeature)
setStyle
etc
I can see Leaflet exposing L.GeoJSON.getFeature(), but I don't seem to be able to squeeze anything out of it. No documentation, and the inspector seems to suggest it does not take arguments... :\
Is this just there for future development?
You may use getLayer to get the feature by its id.
http://leafletjs.com/reference.html#layergroup-getlayer
var geojsonLayer = L.geoJson(data,{
onEachFeature: function(feature, layer) {
layer._leaflet_id = feature.id;
}});
geojsonLayer.addTo(map);
feature = geojsonLayer.getLayer(12345); //your feature id here
alert(feature.feature.id);

Google Maps API - Map.data scope issue

I am trying to add a GeoJSON layer to Google Maps (v3) by doing the following:
imageActive = {
url: "images/target_red.png",
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(11, 11),
} // ACTIVE marker image
jQuery.getJSON('home/gcpts/geojson.php', function(data){
points = map.data.addGeoJson(data);
console.log(points); //this works
});
map.data.setStyle({
clickable: true,
draggable: false,
});
map.data.addListener('click', function(event){
setActiveImage(event);
})
function setActiveImage(event){
for(var i = 0;i<points.length;i++){ //can't read "length" of undefined
points[i].revertStyles();
}
map.data.overrideStyle(event.feature, {
icon: imageActive,
});
}
However when I try to iterate through the "points" variable, I can't seem to "see" it. I mainly get undefined, or if I try to call the length of points (points.length), then it doesn't exist.
If I console.log(points) within the jQuery function, then I can see all of the features within the variable. If I place it on the outside, then I can't see it. Is there something I am missing about the scope?
It's my hope that I can set a "click" event and use event.feature to overrideStyle. Then when a different feature is clicked, then the style is removed from the other geoJson features and overrides the newly clicked feature.
It seems that this should work fine, but I can't seem to figure out how to iterate through the features.
Thanks!
(Also, I am using jQuery in "No conflict" mode...)
All of your variables are globally scoped because you aren't using the var keyword. It seems likely that some other script is looking for a points variable and overwrites yours. Assuming your code is already wrapped up in some kind of function (such as a jQuery ready handler), you may solve your problem by just using var. I'd add this line of code before you call getJSON():
var points = [];
The previous answer noted you need to ensure your "points" variable is scoped appropriately, but a better answer is that you don't need that variable at all: Since you are using map.data you can just use that directly to access your features, using something like:
map.data.foreEch(function(feature) {console.log(feature);})
Note of course your "map" variable must be appropriately scoped.
Additionally, you also don't need to use jQuery -- you can just load the data using map.data.loadGeoJson(theUrl) which will do the ajax for you

Categories

Resources