How do I display multiple geojson properties in a popup using Mapbox-GL? - mapbox

I am trying to display two propeties from a geojson file in a popup on a map with points.
Here is an example of one item from the geojson file:
{ "type": "Feature", "properties": { "LONG": 144.760809, "LAT": -37.866606, "STOP_ID": 19924, "STOP_NAME": "Aircraft ", "2016_17_PATRONAGE": 294702, "2016_17_PATRONAGE_DAILY": 805.2, "METRO": "Yes" }, "geometry": { "type": "Point", "coordinates": [ 144.760809, -37.866606 ] } },
I am trying to display both the STOP_NAME and 2016_17_PATRONAGE_DAILY attributes in the same popup.
I have tried looking at this example and this example but neither approach seems to work.
This is my code so far (that works):
map.on('click', 'layername', function (e) {
var coordinates = e.features[0].geometry.coordinates.slice();
var name = e.features[0].properties.STOP_NAME;
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(name)
.addTo(map);
});
I tried this code using the examples above:
map.on('click', 'layername', function (e) {
var coordinates = e.features[0].geometry.coordinates.slice();
var name = e.features[0].properties.STOP_NAME;
var patronage = e.features[0].properties.2016_17_PATRONAGE;
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(name) + ' (' + properties.2016_17_PATRONAGE + ')')
.addTo(map);
});
This didn't work and I got a message: "SyntaxError: identifier starts immediately after numeric literal"
I'm fairly new to Mapbox-GL-JS so would appreciate any assistance.

You're so close. Just change that setHTML line to include an expression that references both properties:
.setHTML(e.features[0].properties.STOP_NAME + ' (' + e.feature[0].properties.2016_17_PATRONAGE + ')')
For convenience, I tend to do:
var p = e.features[0].properties;
So this would be:
.setHTML(p.STOP_NAME + ' (' + p.2016_17_PATRONAGE + ')')

Related

Leaflet + Supercluster: L.marker's autoPan not working

I'm using the mapbox supercluster library to cluster a fairly large amount of point data and plotting it with leaflet inside a shiny app. At maxZoom the points are shown and are getting draggable for the user in case the location is wrong. Mapbox supercluster uses a static kdbush spatial index, so each time a L.marker is moved, the cluster will be reloaded (not a problem in my case, because supercluster is extremely fast).
However, it is only possible to drag an L.marker used with supercluster inside the visible map bounds. This makes sense, because the L.marker's are generated on the fly for only the visible map bounds. If the L.marker are defined with options {draggable:true,autoPan:true} an error occurs in case L.marker is dragged outside of the visible map extent:
Uncaught TypeError: t is null
leaflet 1.3.3/dist/leaflet.js:5
leaflet 1.3.3/dist/leaflet.js:5
at https://unpkg.com/leaflet#1.3.3/dist/leaflet.js:5
_adjustPan https://unpkg.com/leaflet#1.3.3/dist/leaflet.js:5
_adjustPan self-hosted:891
_adjustPan self-hosted:844
or in my shiny app I get the following error:
Uncaught TypeError: Cannot set property '_leaflet_pos' of null
at Object.Lt [as setPosition] (eval at <anonymous> (jquery.min.js:2), <anonymous>:5:9959)
at e._adjustPan (eval at <anonymous> (jquery.min.js:2), <anonymous>:5:71149)
It would be really cool to have some sort of autopan for L.marker's used with supercluster. I know the user could just zoom out to drag the point to the intended location. This is not really an option in my case, because there are quickly too many points in the visible map extent which will slow down map panning (that's why I use the clustering in the first place).
I tried to center the leaflet map during the drag event using panTo
layer.on('drag',function(e){
//console.log('marker dragstart event');
var position=e.target.getLatLng();
map.panTo(new L.latLng(position.lat,position.lng));
});
but it seems that this somehow stops the drag event.
My question is: Is there a way to get an autopan for L.marker used with supercluster?
I set up a minimal reproducible example below. This example plots a single point (var marker) as well as three points (var markers) with supercluster. The single point can be dragged outside the visible map extent whereas the cluster points cannot.
var map = L.map('map').setView([51.505, -1.09], 9);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
var marker = new L.marker([51.505, -1.09],{
draggable: true,
autoPan:true
}).bindPopup('autopan working').addTo(map);
// Empty Layer Group that will receive the clusters data on the fly.
var markers = L.geoJson(null, {
pointToLayer: createClusterIcon,
onEachFeature: onEachFeature
}).addTo(map);
var clusterData = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties":{
"id":0
},
"geometry": {
"type": "Point",
"coordinates": [-1.0,51.5]
}
},
{
"type": "Feature",
"properties":{
"id":1
},
"geometry": {
"type": "Point",
"coordinates": [-1.1,51.6]
}
},
{
"type": "Feature",
"properties":{
"id":2
},
"geometry": {
"type": "Point",
"coordinates": [-0.9,51.4]
}
}
]
}
function onEachFeature(f, layer) {
//add drag event
layer.on('drag',function(e){
//console.log('marker dragstart event');
//var position=e.target.getLatLng();
//map.panTo(new L.latLng(position.lat,position.lng));
});
layer.on('dragend',function(e){
//console.log('marker dragend event');
var changedPos = e.target.getLatLng();
//console.log('new location '+changedPos);
//load cluster again
clusterData.features[f.properties.id].geometry.coordinates[1]=changedPos.lat;
clusterData.features[f.properties.id].geometry.coordinates[0]=changedPos.lng;
index.load(clusterData.features);
update();
});
}
// Update the displayed clusters after user pan / zoom.
map.on('moveend', update);
function update() {
if (!ready) return;
var bounds = map.getBounds();
var bbox = [bounds.getWest(), bounds.getSouth(), bounds.getEast(), bounds.getNorth()];
var zoom = map.getZoom();
var clusters = index.getClusters(bbox, zoom);
//console.log('clusters '+clusters);
markers.clearLayers();
markers.addData(clusters);
}
// Zoom to expand the cluster clicked by user.
markers.on('click', function(e) {
//console.log('check data' + e.layer.feature.properties.cluster_id);
var clusterId = e.layer.feature.properties.cluster_id;
var center = e.latlng;
var expansionZoom;
if (clusterId) {
expansionZoom = index.getClusterExpansionZoom(clusterId);
map.flyTo(center, expansionZoom);
}
});
var ready = false;
//load data
const index = new Supercluster({
radius: 150,
maxZoom:10
});
index.load(clusterData.features);
ready= true;
update();
function createClusterIcon(feature, latlng) {
if (!feature.properties.cluster){
return L.marker(latlng,{draggable:true,autoPan:true}); //add autoPan:true
}
var count = feature.properties.point_count;
var size =
count < 100 ? 'small' :
count < 1000 ? 'medium' : 'large';
var icon = L.divIcon({
html: '<div><span>' + feature.properties.point_count_abbreviated + '</span></div>',
className: 'marker-cluster marker-cluster-' + size,
iconSize: L.point(40, 40)
});
return L.marker(latlng, {
icon: icon
});
}
#map {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
<script src="https://unpkg.com/supercluster#7.1.0/dist/supercluster.min.js"></script>
<link href="https://cdn.rawgit.com/mapbox/supercluster/v4.0.1/demo/cluster.css" rel="stylesheet"/>
<script src="https://unpkg.com/leaflet#1.3.3/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet#1.3.3/dist/leaflet.css" rel="stylesheet"/>
<div id="map"></div>

Mapbox - Pointer on click not defined

I am trying to add a popup to my map icons in Mapbox GL JS. So far I have been unsuccessful.
When I create a layer, in the layer's data, I have specified several properties. However when I try and add a popup to the icon, all of the properties are not present. Attempting to access them simply returns undefined.
Adding the layer:
function addRedAirports() {
map.addSource('hoggitRed', {
type: 'geojson',
cluster: true,
clusterMaxZoom: 14, // Max zoom to cluster points on
clusterRadius: 10, // Radius of each cluster when clustering points (defaults to 50)
data: redAirportArray[0]
});
map.addLayer({
"id": 'reds',
"type": "symbol",
"source": "hoggitRed",
"layout": {
"icon-image": "redIcon",
"icon-size": 0.075,
"icon-anchor": "bottom",
"icon-allow-overlap": true
}
});
Here is the contents of the data (redAirportArray[0]). I am looping through an api to get this data.
When I pass this data to mapbox, the properties are complete and correct. However when I try access them for a popup, I get undefined. Console logging the mapbox layer shows none of the inputted properties present..
(I have condensed this code slightly.. every loop I create a feature and then push it to the feature collection. I combined the two in this snippet for the sake of simplicity)
let redAirportArray = [{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": { //SETTING THE PROPERTIES
"test": 'test',
"ID": airportsRed[x].Id,
"team": airportsRed[x].Coalition
},
"geometry": {
"type": "Point",
"coordinates": [airportsRed[x].LatLongAlt.Long, airportsRed[x].LatLongAlt.Lat]
}
}]
Adding a popup on click
map.on('click', 'reds', function (e) {
var coordinates = e.features[0].geometry.coordinates.slice();
let team = e.features[0].properties.ID;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(team)
.addTo(map);
});
Thanks in advance and I hope you can help!
With the way your layer is currently being added, you're looking for properties in the wrong location. e.features[0] is not defined since e is the feature you just clicked. Your pop up code should look something like this:
map.on('click', 'reds', function (e) {
var coordinates = e.geometry.coordinates.slice(); // Changed
let team = e.properties.ID; // Changed
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(team)
.addTo(map);
});

Dynamically add data, remove markers outside of bounds, add markers inside of bounds

I've been struggling with this feature for weeks, but am starting to think it's not possible. Hopefully someone here can prove me wrong! :)
Using Mapbox GL. On page load, map renders with markers within the given bounds. I'm trying to mimic functionality where the user drags the map, and based on the new bounds, new markers are drawn and old ones are removed. Data for the new markers are dynamic based on an API request. I managed to find a function after much Googling to test if a point is in bounds of a map and that works, but given how the function works to add/remove the marker, dynamic data doesn't seem to fit in.
I've created a fiddle here and hard-coded a new "feature" but it's not getting drawn. There is most likely a second part of this issue, but maybe i can figure it out on my own once this is deemed feasible
Any advice would be greatly appreciated. Thanks in advance!
geojson.features.forEach(function (marker) {
// create a DOM element for the marker
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = 'url(https://placekitten.com/g/' + marker.properties.iconSize.join('/') + '/)';
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';
el.addEventListener('click', function () {
window.alert(marker.properties.message);
});
// add marker to map
var point = new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates);
map.on("dragend", function() {
if ( inBounds(marker.geometry.coordinates, map.getBounds()) == false ) {
point.remove();
} else {
geojson.features.push({
"type": "Feature",
"properties": {
"message": "Lurman",
"iconSize": [20, 20]
},
"geometry": {
"type": "Point",
"coordinates": [
-59.29223632812499,
-17.28151823530889
]
}
})
point.addTo(map);
}
})
});
function inBounds(point, bounds) {
var lng = (point[0] - bounds._ne.lng) * (point[0] - bounds._sw.lng) < 0;
var lat = (point[1] - bounds._ne.lat) * (point[1] - bounds._sw.lat) < 0;
return lng && lat;
}
I was able to resolve this by using layers and updating it on dragend.

map on click fires when GeoJSON is clicked on leaflet 1.0

In leaflet 1.0 beta2, when clicking on a GeoJSON with a click function assigned along with a map click function defined, they both fire instead of just one. This doesn't happen in the older versions of leaflet. See fiddle for examples. Any workarounds for this?
Leaflet 7.7
http://jsfiddle.net/tator/5e209s9c/14/
Leaflet 1.0 beta2
http://jsfiddle.net/tator/em9cLfk4/4/
// Create the map
var map = L.map('map').setView([41, -98], 5);
//when map is clicked run identify
map.on('click', identify);
// Identify function
function identify(e) {
alert('click on the map');
};
//example geojson
var states = [{
"type": "Feature",
"properties": {"party": "Republican"},
"geometry": {
"type": "Polygon",
"coordinates": [[
[-104.05, 48.99],
[-97.22, 48.98],
[-96.58, 45.94],
[-104.03, 45.94],
[-104.05, 48.99]
]]
}
}, {
"type": "Feature",
"properties": {"party": "Democrat"},
"geometry": {
"type": "Polygon",
"coordinates": [[
[-109.05, 41.00],
[-102.06, 40.99],
[-102.03, 36.99],
[-109.04, 36.99],
[-109.05, 41.00]
]]
}
}];
//style the polygon with clickedgeojson function
parpoly = L.geoJson(states, {
style: {
color: '#ff7800',
weight: 1.5,
opacity: 1,
fillOpacity: 0
},
onEachFeature: function(feature, layer) {
layer.on({
click: clickedgeojson
});
}
});
//clickedgeojson function
function clickedgeojson(e) {
alert('click on json');
};
// Set up the OSM layer
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{maxZoom: 18}).addTo(map);
//add the geojson to map
parpoly.addTo(map);
Use L.DomEvent's stopPropagation method:
Stop the given event from propagation to parent elements.
http://leafletjs.com/reference-1.0.0.html#domevent-stoppropagation
//clickedgeojson function
function clickedgeojson(e) {
L.DomEvent.stopPropagation(e);
alert('click on json');
};
Here's a working fork of your Fiddle: http://jsfiddle.net/hakw66nj/
Or you can add the click event to the nonBubblingEvents array in your layer's options object. This goes currently undocumented so i can't link to any documentation just to the commit on Github:
Add nonBubblingEvents option (fix #3604)
https://github.com/Leaflet/Leaflet/commit/74018f284e8c58d022a9a127406867438aa2a4d0
new L.GeoJSON(collection, {
nonBubblingEvents: ['click']
})
Here's a fork of your Fiddle using this solution: http://jsfiddle.net/hdd8rgkm/
iH8 gave you a good answer if you want to stop propagation altogether. However if you still want the map function to fire you can just add in a variable check. Example here.
var idGeo = 0;
// Identify function
function identify(e) {
if(idGeo ==1){
idGeo = 0;
}else{
alert('click on the map');
idGeo = 0;
}
};
//clickedgeojson function
function clickedgeojson(e) {
idGeo = 1;
alert('click on json');
};

in-place Update Leaflet GeoJSON feature

I was hoping that GeoJSON.addData() would return the newly created subLayer of the GeoJSON object, but it does not. Why Do I need something like this?
(currently using Leaflet 1.0Beta2)
I am using Leaflet GeoJson to show live data in a GeoJSON (point, line, polygon). It is a CRUD interface (Create, Update and Delete). I receive WebSocket messages with GeoJSON data, each one with a GUID.
I the case of a CREATE I just do a GeoJSon.AddData() to the appropriate layer.
But for the UPDATE and DELETE I want a handle for the layer that was added to the GeoJSON so that I can update its location, or update the Geometry. addData is not giving me this handle. And it is really hard to get it from onEachFeature() or from pointToLayer()
Currently, I do have a way that works but ugly. I have to do is search the entire layer with GeoJSon.eachLayer(fn)
whenever an update or delete occurs. It seems a bit expensive.
{even if Leaflet is not truly engineered for this live r/t display of data, it is working, and it seems sad if you cannot use it for watching a lot of sensor data, IoT) as we are doing.
this.delete = function (layerName, feature) {
if (!(layerName in self.myLayers)) {
alert("live.display: Missing Layer: " + layerName);
return;
}
var layerInfo = Live.myLayers[layerName];
var base = layerInfo.layer;
var id = feature.properties.objectID;
this.find(layerName, id, function (layer) {
this.removeLayer(layer);
Tools.debug(16, "live.delete:", "killed object: " + id);
});
}
this.find = function (layerName, id, action) {
var base = Live.myLayers[layerName].layer;
base.eachLayer(function (feature) {
if (!("objectID" in feature.feature.properties)) { return; }
var objectID = feature.feature.properties.objectID;
if (objectID == id) {
action.call(base, feature);
}
});
}
Instead (or in parallel) of "merging" all created GeoJSON features into a single Leaflet GeoJSON layer group (which you do with addData), why not creating first each feature in its own Leaflet GeoJSON layer, so that it gives you the handle you are looking for (then you could simply record this handle in an object / mapping with the key being your objectID for example)?
If desired, you could even still merge the individual layers into your single GeoJSON layer group after that.
var myGeoJsonLayerGroup = L.geoJson().addTo(map);
var myFeaturesMap = {};
function addNewFeatureToGeoJsonLayerGroup(newGeoJsonData) {
var newGeoJSONfeature = L.geoJson(newGeoJsonData);
myFeaturesMap[newGeoJsonData.properties.objectID] = newGeoJSONfeature;
myGeoJsonLayerGroup.addLayer(newGeoJSONfeature);
}
function updateFeature(updatedGeoJsonData) {
var updatedFeature = myFeaturesMap[updatedGeoJsonData.properties.objectID];
updatedFeature.clearLayers(); // Remove the previously created layer.
updatedFeature.addData(updatedGeoJsonData); // Replace it by the new data.
}
function deleteFeature(deletedGeoJsonData) {
var deletedFeature = myFeaturesMap[deletedGeoJsonData.properties.objectID];
myGeoJsonLayerGroup.removeLayer(deletedFeature);
}
Demo (not using GeoJSON): http://jsfiddle.net/ve2huzxw/94/
EDIT:
A slightly more simple solution would be to store the reference to each individual layer through the onEachFeature function of the GeoJSON layer group:
var myFeaturesMap = {};
var myGeoJsonLayerGroup = L.geoJson({
onEachFeature: function (feature, layer) {
myFeaturesMap[feature.properties.objectID] = layer;
}
}).addTo(map);
function addNewFeatureToGeoJsonLayerGroup(newGeoJsonData) {
myGeoJsonLayerGroup.addData(newGeoJsonData);
}
function updateFeature(updatedGeoJsonData) {
deleteFeature(updatedGeoJsonData); // Remove the previously created layer.
addNewFeatureToGeoJsonLayerGroup(updatedGeoJsonData); // Replace it by the new data.
}
function deleteFeature(deletedGeoJsonData) {
var deletedFeature = myFeaturesMap[deletedGeoJsonData.properties.objectID];
myGeoJsonLayerGroup.removeLayer(deletedFeature);
}
If you want to store references to the actual layers being created, you can access them from the layeradd event on your L.GeoJSON instance:
var geojson = new L.GeoJSON().on(
'layeradd', function (e) {
console.log(e.layer);
}
).addTo(map);
// This addData call will fire the handler above twice
// because it adds two features.
geojson.addData({
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [90, 0]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-90, 0]
}
}]
});
If someone still looking for another short method to update GeoJSON, you can try something like this,
//function to clear the previous geojson feature
function clearMap() {
map.eachLayer(function(layer){
if(layer.myTag && layer.myTag === 'previousLayer'){
lmap.removeLayer(layer);
}
});
}
function geojsonUpdate(geojsonData){
var geojsonLayer = L.geoJson(geojsonData, {
onEachFeature: function (feature, layer) {
layer.myTag = 'previousLayer'
);
},
});
geojsonLayer.addTo(lmap);
lmap.fitBounds(geojsonLayer.getBounds());
}
//function call
clearMap();
geojsonUpdate(data);