from vanilla javascript into react hooks - javascript

I tried to use leafletTimeDimension into react but I wanna convert it into react hooks to be easy to work with, I have problem understanding how to write this code into react:
var geoJSONLayer = L.geoJSON(data, {
pointToLayer: function (feature, latLng) {
if (feature.properties.hasOwnProperty('last')) {
return new L.Marker(latLng, {
icon: icon
});
}
return L.circleMarker(latLng);
}
});
var geoJSONTDLayer = L.timeDimension.layer.geoJson(geoJSONLayer, {
updateTimeDimension: true,
duration: 'PT2M',
updateTimeDimensionMode: 'replace',
addlastPoint: true
});
The problem is that I don't know how effectively pass reference to sub element

Related

Using Prototypal Pattern with Creating a Leaflet Map: error with onEachFeature function

I have the following code that I call to create a copy object of map, and initialize the Leaflet map. This works and loads properly. However, the onEachFeature and/or the clickFeature functions are not working properly.
var map = {
mapUrl: "",
maxZoom: 18,
minZoom: 2,
map: L.map('worldMap').setView([51.505, -0.09], 2),
create: function(values) {
var instance = Object.create(this);
Object.keys(values).forEach(function(key) {
instance[key] = values[key];
});
return instance;
},
initLeafletMap: function() {
L.tileLayer(this.mapUrl, {
attribution: '',
maxZoom: this.maxZoom,
minZoom: this.minZoom,
id: 'mapbox.streets'
}).addTo(this.map);
//add continents' outlines
$.getJSON("/static/continents.json",
(function(style, onEachFeature, map) {
return function(continents) {
console.log(typeof(continents));
L.geoJson(continents, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
};
}(this.style, this.onEachFeature, this.map))
);
},
style: function() {
return {
weight: 2,
opacity: 1,
color: 'beige',
dashArray: '3',
fillOpacity: 0
};
},
onEachFeature: function(feature, layer) {
layer.on({
click: this.clickFeature
});
},
clickFeature: function(e) {
do something here();
},
So when I click on the map, I know the onEachFeature function is called, but it does not call clickFeature. Instead I get this error in the console:
leaflet.js:5 Uncaught TypeError: Cannot read property 'call' of undefined
at e.fire (leaflet.js:5)
at e._fireDOMEvent (leaflet.js:5)
at e._handleDOMEvent (leaflet.js:5)
at HTMLDivElement.r (leaflet.js:5)
Much probably simply need to bind the this context when you pass your onEachFeature method as argument of your IIFE to build the callback to your AJAX call:
this.onEachFeature.bind(this)
See also Leaflet- marker click event works fine but methods of the class are undefined in the callback function
BTW you could also attach your click event listener directly on the Leaflet GeoJSON Layer Group instead of doing it for each child layer.

Dynamic template with dynamic scope compilation

I have a very specific need that cannot realy be solved with standard data-binding.
I've got a leaflet map that I want to bind with a vue view-model.
I succeeded to display geojson features kinda bounds to my view, but I'm struggling at displaying a popup bound with vue.js
The main question is : "How to open a popup (possibly multiple popups at the same time) and bind it to a view property "
For now I've come to a working solution, but this is aweful :
map.html
<div id="view-wrapper">
<div id="map-container"></div>
<div v-for="statement in statements" id="map-statement-popup-template-${statement.id}" style="display: none">
<map-statement-popup v-bind:statement="statement"></map-statement-popup>
</div>
</div>
<!-- base template for statement map popup -->
<script type="text/template" id="map-statement-popup-template">
{{ statement.name }}
</script>
map.js
$(document).ready(function() {
var map = new L.Map('map-container');
map.setView(new L.LatLng(GLOBALS.MAP.STARTCOORDINATES.lng, GLOBALS.MAP.STARTCOORDINATES.lat), GLOBALS.MAP.STARTZOOM);
var osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
osm.addTo(map);
//Initialize map dynamic layers
var mapLayers = {};
//View-model data-bindings
var vm = new Vue({
el: '#view-wrapper',
data: {
statements: []
},
methods: {
getStatements: function() {
return $.get('api/statements');
},
updateStatements: function() {
var that = this;
return that.getStatements().then(
function(res) {
that.statements = res.data;
}
);
},
refreshStatements: function() {
mapLayers.statements.layer.clearLayers();
if(this.statements && this.statements.length){
var geoJsonStatements = geoJsonFromStatements(this.statements);
mapLayers.statements.layer.addData(geoJsonStatements);
}
},
handleStatementFeature: function(feature, layer) {
var popupTemplateEl = $('#map-statement-popup-template-' + feature.properties.statement.id);
layer.bindPopup(popupTemplateEl.html());
var statementIndex = _.findIndex(this.statements, {statement:{id: feature.properties.statement.id}});
if(feature.geometry.type === 'LineString') {
this.statements[statementIndex].layer = {
id: L.stamp(layer)
};
}
},
openStatementPopup: function(statement) {
if(statement.layer) {
var featureLayer = mapLayers.statements.layer.getLayer(statement.layer.id);
featureLayer.openPopup();
}
}
},
created: function() {
var that = this;
//Set dynamic map layers
var statementsLayer = L.geoJson(null, {
onEachFeature: this.handleStatementFeature
});
mapLayers.statements = {
layer: statementsLayer
};
map.addLayer(mapLayers.statements.layer);
this.updateStatements().then(this.refreshStatements);
this.$watch('statements', this.refreshStatements);
},
components: {
'map-statement-popup': {
template: '#map-statement-popup-template',
props: {
statement: null
}
}
}
});
function geoJsonFromStatementsLocations(statements){
var geoJson = {
type: "FeatureCollection",
features: _.map(statements, function(statement) {
return {
type: "Feature",
geometry: {
type: "LineString",
coordinates: statement.coordinates
},
properties: {
statement: statement
}
};
});
};
return geoJson;
}
});
This seems pretty aweful to me, because I have to loop over statements with a v-for, render a div for my custom element for every statement, hide it, then use it in the popup, grabbing it with a dynamic id technique.
I would like to do something like this :
map.html
<div id="view-wrapper">
<div id="map-container"></div>
</div>
<!-- base template for statement map popup -->
<script type="text/template" id="map-statement-popup-template">
{{ statement.name }}
</script>
map.js
$(document).ready(function() {
[...]
//View-model data-bindings
var vm = new Vue({
el: '#view-wrapper',
data: {
statements: []
},
methods: {
handleStatementFeature: function(feature, layer) {
var popupTemplateEl = $('<map-statement-popup />');
var scope = { statement: feature.properties.statement };
var compiledElement = this.COMPILE?(popupTemplateEl[0], scope);
layer.bindPopup(compiledElement);
}
},
components: {
'map-statement-popup': {
template: '#map-statement-popup-template',
props: {
statement: null
}
}
}
});
function geoJsonFromStatementsLocations(statements){
var geoJson = {
type: "FeatureCollection",
features: _.map(statements, function(statement) {
return {
type: "Feature",
geometry: {
type: "LineString",
coordinates: statement.coordinates
},
properties: {
statement: statement
}
};
});
};
return geoJson;
}
});
... but I couldn't find a function to "COMPILE?" based on a defined scope. Basically I want to :
Create a custom element instance
Pass it a scope
Compile it
EDIT : Actually, I could find $compile function. But it's often used to compile appended child to html. I don't want to append it THEN compile it. I'd like to compile it then let leaflet append it for me.
Would this work for you? Instead of using a component, you create a new element to be passed to bindPopup, and you new Vue on that element, with your data set appropriately.
new Vue({
el: 'body',
data: {
popups: [1, 2, 3],
message: "I'm Dad",
statements: []
},
methods: {
handleFeature: function(id) {
const newDiv = document.createElement('div');
const theStatement = {
name: 'Some name for ' + id
};
newDiv.innerHTML = document.getElementById('map-statement-popup-template').innerHTML;
new Vue({
el: newDiv,
data: {
statement: theStatement
},
parent: this
});
// Mock call to layer.bindPopup
const layerEl = document.getElementById(id);
this.bindPopup(layerEl, newDiv);
},
bindPopup: function(layerEl, el) {
layerEl.appendChild(el);
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div class="leaflet-zone">
<div v-for="popup in [1,2,3]">
<button #click="handleFeature('p-' + popup)">Bind</button>
<div id="p-{{popup}}"></div>
</div>
</div>
<template id="map-statement-popup-template">
{{ statement.name }} {{$parent.message}}
</template>
I think you could do the same thing with $compile, but $compile is poorly (really un-) documented and intended for internal use. It is useful for bringing a new DOM element under control of the current Vue in the current scope, but you had a new scope as well as a new DOM element, and as you noted, that binding is exactly what Vue is intended to do.
You can establish a parent chain by specifying the parent option as I have updated my snippet to do.

Mapbox map already initialized

I have an Angular service function to build a mapbox map like so:
app.service("MapService", [function(){
//mapbox vars
var map = {
minZoom: 11,
id: "xxxxxxxx",
token: "xxxxxxxx"
};
//build map
this.buildMap = function(lat, lon, zoom){
//map bounds
var southWest = L.latLng(54.04407014753034, -0.745697021484375),
northEast = L.latLng(53.45698455620496, -2.355194091796875),
bounds = L.latLngBounds(southWest, northEast);
//build map object
L.mapbox.accessToken = map.token;
map.obj = L.mapbox.map("map", map.id, {
maxBounds: bounds,
zoomControl: false,
minZoom: map.minZoom,
attributionControl: false
}).setView([lat, lon], zoom, {
pan: { animate: true },
zoom: { animate: true }
});
}
}]);
This simply populates a div:
<div id="map"></div>
When I go to a new Angular view and call this function again (to populate a new div with id map with the map) it gives me the error:
Map container is already initialized
How do I solve this problem?
You have to destroy the map before reinitializing it. Use the following
if(map.obj != undefined) map.obj.remove();
before
map.obj = L.mapbox.map("map", map.id, {
Using a directive is much more suitable for this kind of purpose, you won't run into stuff like this. In the following directive i'm using Leaflet, but it's just the same as using Mapbox (Mapbox is an extended version of Leaflet):
angular.module('app').directive('leaflet', [
function () {
return {
restrict: 'EA',
replace: true,
template: '<div></div>',
link: function (scope, element, attributes) {
scope.$emit('leaflet-ready', new L.Map(element[0]));
}
};
}
]);
Use it in your view:
<leaflet></leaflet>
Controller:
angular.module('app').controller('map1Controller', function($scope) {
$scope.$on('leaflet-ready', function (e, leaflet) {
// leaflet var contains map instance, do stuff
})
});
Here's an example of the concept: http://plnkr.co/edit/SFgGhVUtBOqsIwYuwNuv?p=preview

Best method to label polygon in leaflet?

I am labeling 6 polygons in a GeoJson file. I am using the circleMarker on the each polygon centroid then calling .bindLabel, but I get this error: "circleMarker.bindLabel is not a function". Leaflet.label.js is called.
The map.
Code for GeoJSON:
var districts = L.geoJson(null, {
style: function (feature) {
return {
weight: 1,
opacity: 1,
color: 'blueviolet',
fillColor: 'plum',
fillOpacity: 0.5
};
},
onEachFeature: function (feature, layer) {
layer.on('mouseover', function () {
this.setStyle({
'fillColor': '#0000ff'
});
});
layer.on('mouseout', function () {
this.setStyle({
'fillColor': 'plum'
});
});
layer.on('click', function () {
window.location = feature.properties.URL;
});
var circleMarker = L.circleMarker(layer.getBounds().getCenter());
// e.g. using Leaflet.label plugin
circleMarker.bindLabel(feature.properties['NAME'], { noHide: true })
.circleMarker.addTo(map);
}
});
$.getJSON("data/districts.geojson", function (data) {
districts.addData(data);
});
You're calling a circleMarker method on your circleMarker object instance. That will never work. L.CircleMarker doesn't have a circleMarker method. This won't work:
circleMarker.bindLabel(feature.properties['NAME'], { noHide: true }).circleMarker.addTo(map);
This will:
circleMarker.bindLabel(feature.properties['NAME'], { noHide: true }).addTo(map);
And this will too:
circleMarker.bindLabel(feature.properties['NAME'], { noHide: true });
circleMarker.addTo(map);
But if you want to add a label without using L.CircleMarker you can simply do:
onEachFeature: function (feature, layer) {
layer.bindLabel(feature.properties['NAME'], { 'noHide': true });
}
You're also loading your scripts in the incorrect order:
<script src="assets/leaflet-label/leaflet.label.js"></script>
<script src="assets/leaflet-0.7.2/leaflet.js"></script>
Leaflet.label wants to extend classes from Leaflet, but it can't because Leaflet itself isn't loaded yet. So yes, you've loaded Leaflet.label, just not at the correct time. You could see this in your console, because Leaflet.label should throw an error when it doesn't find Leaflet. The correct way:
<script src="assets/leaflet-0.7.2/leaflet.js"></script>
<script src="assets/leaflet-label/leaflet.label.js"></script>

Polygon labels with Leaflet

Using leaflet 7.3 and polygon data in GeoJSON, how can I add labels from field: NAME?
Here is example of current GeoJSON polygon data. I would like to enable fixed labels in center of polygon, overlap OK.
var districts = L.geoJson(null, {
style: function (feature) {
return {
color: "green",
fill: true,
opacity: 0.8
};
},
onEachFeature(feature, layer) {
layer.on('mouseover', function () {
this.setStyle({
'fillColor': '#0000ff'
});
});
layer.on('mouseout', function () {
this.setStyle({
'fillColor': '#ff0000'
});
});
layer.on('click', function () {
window.location = feature.properties.URL;
});
}
});
$.getJSON("data/districts.geojson", function (data) {
districts.addData(data);
});
In onEachFeature callback, you can get the center of the L.Polygon created by GeoJSON layer and bind a label to it.
var polygonCenter = layer.getBounds().getCenter();
// e.g. using Leaflet.label plugin
L.marker(polygonCenter)
.bindLabel(feature.properties['NAME'], { noHide: true })
.addTo(map);
Here is an example: http://jsfiddle.net/FranceImage/ro54bqbz/ using Leaflet.label

Categories