Skip to content

Instantly share code, notes, and snippets.

@jreviews
Created July 12, 2020 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jreviews/4f85f94606f7dc41c15c1318cb586e92 to your computer and use it in GitHub Desktop.
Save jreviews/4f85f94606f7dc41c15c1318cb586e92 to your computer and use it in GitHub Desktop.
Add GeoJSON layers to MapsPro Module/Widget Developer Filter
<?php
defined('MVC_FRAMEWORK') or die;
function add_geojson_layer_to_map_module($output, $params)
{
$asset_manager = S2Object::make('asset_manager');
$script = "
<script>
const jrGeojsonStyles1 = function(feature) {
switch (feature.properties.type) {
case 'Type 1': return {
stroke: true,
weight: 0.5,
color: '#ff0000',
fillColor: '#ff0000',
fillOpacity: 0.3
};
case 'Type 2': return {
stroke: true,
weight: 1,
color: '#09b838',
fillColor: '#09b838',
fillOpacity: 0.3
};
default: return {
stroke: true,
weight: 1,
color: '#fcba03',
fillColor: '#fcba03',
fillOpacity: 0.3
}
}
}
const jrGeojsonStyles2 = function(feature) {
return {
color: '#ff7800',
weight: 5,
opacity: 0.65
};
}
const layers = [
{ filename: 'layer1.geojson', stylesFn: jrGeojsonStyles1 },
{ filename: 'layer2.geojson', stylesFn: jrGeojsonStyles2 },
{ filename: 'layer3.geojson' }
];
document.addEventListener('jr-map-initialized', function(event) {
console.log('Geojson Filter: map initialized');
layers.map(layer => jreviews.addGeoJSONLayer(event.target, layer))
});
jreviews.addGeoJSONLayer = function(target, layer) {
async function loadGeojson() {
const response = await fetch('/'+layer.filename);
const data = await response.json();
return data;
}
loadGeojson().then( (geojson) => {
console.log('GeoJSON layer '+layer.filename+' was loaded');
let map = jQuery(target).data('map');
const options = {};
if ( layer.stylesFn ) {
options.style = layer.stylesFn;
}
L.geoJSON(geojson, options).addTo(map);
});
};
</script>
";
return $output.$script;
}
Clickfwd\Hook\Filter::add('after_filter_output_maps_mapview_index', 'add_geojson_layer_to_map_module', 10);
@jreviews
Copy link
Author

Add one or more GeoJSON layers to the map Joomla module and WordPress widget.

Passing a stylesFn is optional.

For the first layer layer1.geojson, the above example uses the feature.properties.type to add different styles based on the value of a specific attribute type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment