Update a Mapbox layer by zoom level when loading geojson - r

Very similar to this tutorial, I would like to create a MapBox map that at a zoomed out level shows regions (labelled Pcode in my data), but once zoomed it switched to a district level (labelled Name). Ideally both these layers would be part of a single geojson shapefile though that can be loaded from an external source (https://raw.githubusercontent.com/Laurent-Smeets-GSS-Account/geojsons/main/geojsons_files/Districts_261_simplified.json). my questions are
how can I format the geojson in such a way that is possible (in R)? (Maybe it is necessary to combine the district polygons into new region polygons and save a seperate geojson file with these regions that gets loaded at another zoom level?)
how do I load the data into Mapbox to make it switch at a certain zoom level?
I am using this example on how to load the code
mapboxgl.accessToken = 'MY TOKEN';
// Create a new map.
const map = new mapboxgl.Map({
container: 'map',
// Choose from Mapbox's core styles, or make your own style with Mapbox Studio
style: 'mapbox://styles/mapbox/streets-v12',
center: [-100.04, 38.907],
zoom: 3
});
map.on('load', () => {
// Add a source for the state polygons.
map.addSource('states', {
'type': 'geojson',
'data': 'https://raw.githubusercontent.com/Laurent-Smeets-GSS-Account/geojsons/main/geojsons_files/Districts_261_simplified.json'
});
// Add a layer showing the state polygons.
map.addLayer({
'id': 'states-layer',
'type': 'fill',
'source': 'states',
'paint': {
'fill-color': 'rgba(200, 100, 240, 0.4)',
'fill-outline-color': 'rgba(200, 100, 240, 1)'
}
});
// When a click event occurs on a feature in the states layer,
// open a popup at the location of the click, with description
// HTML from the click event's properties.
map.on('click', 'states-layer', (e) => {
new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setHTML(e.features[0].properties.Name)
.addTo(map);
});
// Change the cursor to a pointer when
// the mouse is over the states layer.
map.on('mouseenter', 'states-layer', () => {
map.getCanvas().style.cursor = 'pointer';
});
// Change the cursor back to a pointer
// when it leaves the states layer.
map.on('mouseleave', 'states-layer', () => {
map.getCanvas().style.cursor = '';
});
});

You can combine both sets of features into one GeoJSON FeatureCollection, just be sure to add some property that you can filter on, like:
...
{
type: 'Feature',
geometry: {...},
properties: {
type: 'district'
}
}
...
When you load the data, add one source, and two layers. Each layer should have a filter attribute so that only the features of a certain type show in that layer. Make sure one has its visibility set to none when the map first loads.
map.addLayer({
...,
layout: {
visibility: 'none'
},
filter: ['==', 'type', 'district']
});
map.addLayer({
...,
filter: ['==', 'type', 'pcode']
});
Then you can follow the same example you posted, and toggle the visibility on zoom.

Related

How to use a Personalized Map Style with Here API

I would like to customize the map style and found the Map Style Editor.
Therefore, I would like to build on the normal.day.grey map scheme and just tweak a few styles. The Map Style Editor provides the normal.day scheme as yaml.
Is there a possibility to access the normal.day.grey scheme as yaml so I can load it into the editor and start from there?
What would I do with the result? As far as I understand from the docs there is a predefined set of schemes and styles which can be combinated together. How would I use my custom style in there?
Please distinguish between vector map tiles and raster
In the documentation is described about raster Map Tile API - this is prerendered images (with some style) of map. You can't combine them in map view. Except only if some map image tile are partially transparent e.g. 'truck only' or 'traffic flow'. Then you can add two or more layers on the map.
Vector tiles (https://developer.here.com/documentation/vector-tiles-api/dev_guide/index.html):
Yes you can customize the vector map style utilize the Map Style Editor
vector style 'normal.day.grey' doesn't exist but you can start with this example on https://demo.support.here.com/examples/v3.1/changing_the_map_style - select there 'Reduced day' and download it.
In this example you can find dark style: https://jsfiddle.net/zmeatyxv/1/
Also you can mix a raster tiles and vector tiles adding layers in JS API:
http://jsfiddle.net/uycv9m8x/ - terrain map at the bottom and vector at the top, see code below:
/**
* The function add the "change" event listener to the map's style
* and modifies colors of the map features within that listener.
* #param {H.Map} map A HERE Map instance within the application
*/
function changeFeatureStyle(map){
// get the vector provider from the vector layer
var provider = map.getLayers().get(1).getProvider(); //get provider from vector layer
// get the style object for the vector layer
var vStyle = provider.getStyle();
var changeListener = (evt) => {
if (vStyle.getState() === H.map.Style.State.READY) {
vStyle.removeEventListener('change', changeListener);
// query the sub-section of the style configuration
// the call removes the subsection from the original configuration
var vConfig = vStyle.extractConfig([
'earth',
'landuse.wood',
'landuse.forest',
'landuse.park',
'landuse.builtup',
'landuse.national_park',
'landuse.nature_reserve',
'landuse.green-areas',
'landuse.other',
'water.small_water',
'water.deep_water',
'water.river'
]);
}
};
vStyle.addEventListener('change', changeListener);
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: window.apikey
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map
var map = new H.Map(document.getElementById('map'),
defaultLayers.raster.terrain.xbase/*set terain xbase as base layer*/, {
center: {lat: 47.60586, lng: 14.27161},
zoom: 9,
pixelRatio: window.devicePixelRatio || 1
});
map.addLayer(defaultLayers.vector.normal.map);//add vector layer on the top
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => map.getViewPort().resize());
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Now use the map as required...
changeFeatureStyle(map);
http://jsfiddle.net/80jtLv16/1/ - raster mobile labels at the bottom and vector tile at the top, see code below:
function setStyle(map){
// get the vector provider from the vector layer
var provider = map.getLayers().get(1).getProvider(); //get provider from vector layer
// Create the style object from the YAML configuration.
// First argument is the style path and the second is the base URL to use for
// resolving relative URLs in the style like textures, fonts.
// all referenced resources relative to the base path https://js.api.here.com/v3/3.1/styles/omv.
var style = new H.map.Style('https://heremaps.github.io/maps-api-for-javascript-examples/change-style-at-load/data/dark.yaml',
'https://js.api.here.com/v3/3.1/styles/omv/');
// set the style on the existing layer
provider.setStyle(style);
}
/**
* The function add the "change" event listener to the map's style
* and modifies colors of the map features within that listener.
* #param {H.Map} map A HERE Map instance within the application
*/
function changeFeatureStyle(map){
// get the vector provider from the vector layer
var provider = map.getLayers().get(1).getProvider(); //get provider from vector layer
// get the style object for the vector layer
var vStyle = provider.getStyle();
var changeListener = (evt) => {
if (vStyle.getState() === H.map.Style.State.READY) {
vStyle.removeEventListener('change', changeListener);
// query the sub-section of the style configuration
// the call removes the subsection from the original configuration
var vConfig = vStyle.extractConfig([
'earth',
'continent_label',
'road_labels',
'places',
'buildings.address-labels',
'roads.shields',
//'landuse.wood',
//'landuse.forest',
//'landuse.park',
'landuse.builtup',
'landuse.national_park',
'landuse.nature_reserve',
'landuse.green-areas',
'landuse.other',
'water.small_water',
'water.deep_water',
'water.river'
]);
}
};
vStyle.addEventListener('change', changeListener);
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: window.apikey
});
var defaultLayers = platform.createDefaultLayers();
var mTileServ = platform.getMapTileService({'type': 'base'});
console.log("mTileServ:", mTileServ);
var mobileLayer = mTileServ.createTileLayer('labeltile', 'normal.day.mobile', 512, 'png8', {lg: 'eng', lg2: 'eng'});
//Step 2: initialize a map
var map = new H.Map(document.getElementById('map'),
mobileLayer/*set mobile layer as base layer*/, {
center: {lat: 47.60586, lng: 14.27161},
zoom: 9,
pixelRatio: window.devicePixelRatio || 1
});
map.addLayer(defaultLayers.vector.normal.map);//add vector layer on the top
map.getLayers().add(mobileLayer); //set base layer on top - it depends what you want to achieve
//map.getLayers().add(defaultLayers.vector.normal.map); //here example how to reshuffle the layers
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => map.getViewPort().resize());
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Now use the map as required...
setStyle(map);
changeFeatureStyle(map);

Google map marker cluster... grouping customize by a value in markers

I want to create a cluster with a specific value stored in the marker.
Is this possible?
enter image description here
You can override the image path of the marker cluster like this
let markers = [marker1, marker2, marker3]; // list of markers with the specific value
markerClusterOptions = {
styles: [
{
height: 53,
width: 53,
url: YOUR_ICON_PATH
}
]
};
let markerCluster = new MarkerClusterer(map, markers, markerClusterOptions);
NB: styles is a list and you can have more than one style depending for exemple the height and width.

My own defined colors for graphs in Kintone

I'd like to set my own defined colors for graphs that appear in Kintone.
I've found out for pie charts, you can upload the below CSS code to the App to have some areas of the pie to become a color of your choice.
.highcharts-series-group .highcharts-series path:nth-of-type(even){
fill:pink;
}
What I'd really like to do though, is apply the same thing to the Line charts in kintone.
I've tried the below CSS:
.highcharts-tracker path {
fill: red;
}
This only changes the points plotted on the graph, but not the lines in between the points.
How can I identify the lines in this graph so that I can end up with lines of the color of my choice??
Updated 6/24/18
Like you mentioned, the code that I showed you displays only on the record detail page. However, if you just make the process to run on the record list event "app.record.index.show", you can show the graph on the top of the record list page.
Also, it will be better to use kintone.app.getHeaderSpaceElement() to append a graph on the record list page.
The following page is an example of how to append something on the record list page using the kintone.app.getHeaderSpaceElement():
kintone developer network - kintone x OpenStreetMap
https://developer.kintone.io/hc/en-us/articles/115003669514
The following page is about the record list header element:
kintone developer network - Get Record List Header Element
https://developer.kintone.io/hc/en-us/articles/213148937-Get-Record-List#getHeaderSpaceElement
=================================================
Original Reply
It's better off not editing the DOM because it might not work after any kintone updates. I recommend creating a custom graph using Chart.js, a javscript library. The following page helps you how to do so.
Example Code
(function() {
"use strict";
// Events for adding and editing records
var eventsCreateShow = ['app.record.create.show', 'app.record.edit.show',
'app.record.index.create.show', 'app.record.index.edit.show'];
kintone.events.on(eventsCreateShow, function(event) {
// Hide the "Chart" Group field
kintone.app.record.setFieldShown('Chart', false);
});
// Display the chart on the record details page (PC and mobile)
var eventsDetailShow = ['app.record.detail.show', 'mobile.app.record.detail.show'];
kintone.events.on(eventsDetailShow, function(event) {
var record = event.record;
var data = {
labels: ["Language Arts", "Math", "Science", "Social Studies", "P.E."],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(0,140,232,.4)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
data: [
record['language_arts']['value'],
record['math']['value'],
record['science']['value'],
record['social_studies']['value'],
record['pe']['value']
]
}
]
};
// Set Chart.js options
var options = {
scaleShowLine: true,
angleShowLineOut: true,
scaleShowLabels: true,
scaleBeginAtZero: true,
angleLineColor: "rgba(0,0,0,.1)",
angleLineWidth: 1,
pointLabelFontFamily: "'Arial'",
pointLabelFontStyle: "normal",
pointLabelFontSize: 16,
pointLabelFontColor: "#666",
pointDot: true,
pointDotRadius: 5,
pointDotStrokeWidth: 1,
pointHitDetectionRadius: 20,
datasetStroke: true,
datasetStrokeWidth: 3,
datasetFill: true,
responsive: true
};
var elRadar;
var elCanvas = document.createElement('canvas');
elCanvas.id = 'canvas';
// Display radar chart onto the Blank space
// Edit display size depending on PC or mobile
if (event.type === 'mobile.app.record.detail.show') {
elRadar = kintone.mobile.app.getHeaderSpaceElement();
elCanvas.style.position = 'relative';
elCanvas.style.top = '10px';
elCanvas.style.left = '10px';
elCanvas.height = '300';
elCanvas.width = '300';
} else {
elRadar = kintone.app.record.getSpaceElement('Radar');
elCanvas.height = '400';
elCanvas.width = '400';
}
elRadar.appendChild(elCanvas);
var myChart = new Chart(elCanvas.getContext("2d")).Radar(data, options);
});
})();
Ref:kintone developer network - Display radar charts with chart.js
https://developer.kintone.io/hc/en-us/articles/115006413388-Display-radar-charts-with-chart-js
I hope this helps

Openlayers Feature.Vector only uses default style

I'm changing from markers to vector layer and I can't make my site to use any sort of non-default icon, whatever I put in externalGraphic style attribute doesnt have effect on map. I just see orange circles. To be exact, no matter what I put in Openlayers.Style to style my point features, I get default look of icons.
It should be easy, but I try for days and can't make it work, so I came here for help. When warstwa_ikon was markers layer everything was fine, but I need extra functionality.
Thats my styling code:
var StylIkony = new OpenLayers.Style({
externalGraphic : '${symbol}',
graphicWidth : 15,
graphicHeight : 15,
cursor : 'pointer'
});
var StylWarstwyIkon = new OpenLayers.StyleMap ({
default: StylIkony,
delete: StylIkony,
select: StylIkony,
temporary: StylIkony
});
warstwa_ikon = new OpenLayers.Layer.Vector("Ikony Lokali",{ eventListeners: { "featureselected": WywolajRamke }});
warstwa_ikon.StyleMap = StylWarstwyIkon;
map.addLayer(warstwa_ikon);
Thats already executed code from generating Features:
WspolrzedneIkony = new OpenLayers.Geometry.Point(2279231, 7127620);
Ikona = new OpenLayers.Feature.Vector(WspolrzedneIkony,
{ "symbol": "../GRAFIKI/IkonyLokali/10.png", "idLokalu": 1 });
warstwa_ikon.addFeatures([Ikona]);
WspolrzedneIkony = new OpenLayers.Geometry.Point(2279245, 7127630);
Ikona = newOpenLayers.Feature.Vector(WspolrzedneIkony,
{ "symbol": "../GRAFIKI/IkonyLokali/6.png", "idLokalu": 2 });
warstwa_ikon.addFeatures([Ikona]);
Thats DOM of my vector layers (warstwa_ikon) StyleMap:
http://s24.postimg.org/hwfjakg0l/stylemap.png
Thats DOM of my vector layer first Feature, which should be styled:
http://s9.postimg.org/oxlocyku7/feature.png
Sorry, I can't include normal images yet. I should add that this is not a problem with accessing icon image file, I can't get layer to use any sort of images, even from internet links.
Declares StyleMap on layer creation as:
warstwa_ikon = new OpenLayers.Layer.Vector("Ikony Lokali", {
styleMap: StylWarstwyIkon,
eventListeners: ...
});
and removes:
warstwa_ikon.StyleMap = StylWarstwyIkon;

OpenLayers: display remote kml

I'm trying to let OpenLayers display a KML file that was retrieved from a server.
For some reason this does not work.
Similar questions have been asked, but I could not find a working example.
What I did was improve one of the examples in the OpenLayers distribution: kml-track.js
I improved it with what I found. This is what it looks like. I feel like I'm missing something obvious.
Any pointers are welcome
var map ;
function init() {
var mercator = new OpenLayers.Projection("EPSG:900913");
var geographic = new OpenLayers.Projection("EPSG:4326");
//note that I have host equal to location// //Math.Random will stop caching//
var mykmlurl = 'http://myserver/kml-track.kml';
map = new OpenLayers.Map({
div: "map",
projection: mercator,
layers: [
new OpenLayers.Layer.OSM(),
//Defiine your KML layer//
new OpenLayers.Layer.Vector("This Is My KML Layer", {
//Set your projection and strategies//
projection: geographic,
strategies: [new OpenLayers.Strategy.Fixed()],
//set the protocol with a url//
protocol: new OpenLayers.Protocol.HTTP({
//set the url to your variable//
url: mykmlurl,
//format this layer as KML//
format: new OpenLayers.Format.KML({
//maxDepth is how deep it will follow network links//
maxDepth: 1,
//extract styles from the KML Layer//
extractStyles: true,
//extract attributes from the KML Layer//
extractAttributes: true
})
}),
styleMap: new OpenLayers.StyleMap({
"default": new OpenLayers.Style({
graphicName: "circle",
pointRadius: 2,
fillOpacity: 0.5,
fillColor: "#ffcc66",
strokeColor: "#666633",
strokeWidth: 1
})
})
})
],
center: new OpenLayers.LonLat(-93.2735, 44.8349).transform(geographic, mercator),
zoom: 8
});
//function called// //timer// //layer to refresh//
window.setInterval(UpdateKmlLayer, 5000, MyKmlLayer);
}
function UpdateKmlLayer(layer) {
//setting loaded to false unloads the layer//
layer.loaded = false;
//setting visibility to true forces a reload of the layer//
layer.setVisibility(true);
//the refresh will force it to get the new KML data//
layer.refresh({ force: true, params: { 'key': Math.random()} });
}
This is an example of how to display a KML layer in OpenLayers which might help you:
http://openlayers.org/dev/examples/kml-layer.html
Are you getting any errors when opening your page - or does it run ok but nothing appear? If you're not getting any errors then it might indicate an issue with how your projections are set up (i.e. your features might not appear where you expect them to)

Resources