change color programmatically for FusionTablesLayer - javascript

I'm reading an array of polygons onto a Google Map using kml in a fusion table. I have an array of 4 colors, and I'd like to programmatically color the polygons one of those 4 colors, depending on the values in another array.
Somehow, the map only colors 4 polygons at a time, even when I specify that there are only 4 styles. How can I color all 130 polygons?
Here is my code:
function setInitialStyles() {
layer = new google.maps.FusionTablesLayer({
map : map,
query : {
select : "geometry",
from : "1gwSN6n_00uZ7YuAP7g4FiUiilybqDRlRmWJrpvA"
}
});
var options = {
styles : [
{
polygonOptions:
{
fillColor: "#ffffff",
strokeColor: "#bcbcbc",
fillOpacity: ".75"
}
}
]
};
var styles = [];
var style1 = candColor[0];
var style2 = candColor[1];
var style3 = candColor[2];
var style4 = candColor[3];
for (var i=0;i<countyCodes.length; i++) {
var c = countyCodes[i];
var whereClause = "'COUSUBFP' = " + c;
var myStyle;
if (countyColors[i] == "#0D58A6" ) { myStyle = style1; }
if (countyColors[i] == "#981400" ) { myStyle = style2; }
if (countyColors[i] == "#E3D132" ) { myStyle = style3; }
if (countyColors[i] == "#007F37" ) { myStyle = style4; }
options.styles.push({
where: whereClause,
polygonOptions: {
fillColor: myStyle
}
});
}
layer.setOptions(options);
}

You can't. Currently FusionTablesLayer is limited to one styled layer, which may have up to five applied styles. See the documentation about the limitation of FusionTablesLayer.
You can define general styling rules (like WHERE clauses) that are applied to all of your polygons. But again: you can only define 5 such rules.
layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1gwSN6n_00uZ7YuAP7g4FiUiilybqDRlRmWJrpvA'
},
styles: [{
polygonOptions: {
fillColor: "#ffffff",
strokeColor: "#bcbcbc",
fillOpacity: ".75"
}
}, {
where: "population < 1000",
polygonOptions: {
fillColor: "#0000FF"
}
}, {
where: "population > 10000",
polygonOptions: {
fillOpacity: 1.0
}
}]
});
layer.setMap(map);

Your array of styles can only be 5 elements long as I mentioned in the last question you asked on this
This approach (using the Fusion Tables API v1, currently matching on name, not COUSUBFP, as your original table didn't include that column) might work for you, but it is rendering the polygons as native Google Maps API v3 objects, so there may be performance issues.

Related

Creating Radar Map on Google Maps JavaScript API

I have a response data from a Radar Layer API like this:
{
"Date": "2020-04-18T04:00:05+03:00",
"Source": 2,
"Kml": [
{
"Polygons": [
{
"Polygon": [
{ "Cordinates": [25.8409, 51.6199] },
{ "Cordinates": [25.8341541, 51.619873] },
{ "Cordinates": [25.834177, 51.61238] },
{ "Cordinates": [25.8308582, 51.5936356] },
{ "Cordinates": [25.8275185, 51.5823822] }
....
....
]
}
],
"Color": "#47C247"
},
{
"Polygons": [
{
"Polygon": [
{ "Cordinates": [26.1740189, 50.5239372] },
{ "Cordinates": [26.1841354, 50.5238838] },
{ "Cordinates": [26.1909122, 50.53136] },
{ "Cordinates": [26.1977215, 50.5463562] }
....
....
]
}
],
"Color": "#47C247"
},
...
...
I want to create a Radar map using this data.
I tried to create polygons using each data and created a set interval function to loop through each polygon for 250ms so that it acts as an animation.
setInterval(() => {
deleteAllShape();
// console.log(data);
data.Kml.map((polygons) => {
const shape = polygons.Polygons.map((polygon) => {
const newMapData = [];
polygon.Polygon.map((obj) => {
const path = { lat: obj.Cordinates[0], lng:
obj.Cordinates[1] };
newMapData.push(path);
});
poly = new google.maps.Polygon({
paths: newMapData,
strokeColor: polygons.Color,
strokeOpacity: 0.8,
strokeWeight: 0,
fillColor: polygons.Color,
fillOpacity: 0.35,
draggable: false,
editable: false,
});
poly.setMap(map);
allPolygons.push(poly);
});
});
},250)
function deleteAllShape() {
poly = null;
for (let i = 0; i < allPolygons.length; i++) {
allPolygons[i].setMap(null);
}
}
This is working to an extend. But the problem is the map and the browser slows down and hangs up after creating some polygons.
When I researched on several radar maps (eg: windy.com) :-
I found that they are rendering images on the map. My question is how to create images using above data and create a radar map?
This may not answer your question, as I'm unclear what you're trying to do with images instead of polygons. However, it might speed things up.
Currently you loop over allPolygons every 250ms, preventing all previous polygons from appearing on the map.
Then you draw a new polygon, and add it into allPolygons, so it gets removed on the next iteration in 250ms. That's all fine.
However, as the number of polygons increase, you'll be increasing the size of that for loop each time:
for (let i = 0; i < allPolygons.length; i++) {
So it'll get progressively slower as you draw more polygons. You don't say how many polygons you're adding, but I'd guess it's a lot.
Instead, all you need to do is hide the most recently created polygon. All the previous ones in allPolygons will already have been hidden, so you don't need to call setMap(null) on every polygon, as it's just the most recent one that's not already set to null.
Maybe something like:
function deleteAllShape() {
allPolygons[allPolygons.length - 1].setMap(null);
}
Alternatively, just this, if you don't need allPolygons for anything else, save you having to store them in that array.
poly.setMap(null);
Also, instead of creating poly then calling poly.setMap(map);, just do
poly = new google.maps.Polygon({
paths: newMapData,
strokeColor: polygons.Color,
strokeOpacity: 0.8,
strokeWeight: 0,
fillColor: polygons.Color,
fillOpacity: 0.35,
draggable: false,
editable: false,
map
});

Javascript force insert string into JS object (JSON) leaflet vectortiles

I am using leaflet mapping library
for styling purposes this code works for the data_oh.parcel layer if I hardcode the layer name like this
var vectorTileOptions = {
interactive: true,
vectorTileLayerStyles: {
'data_oh.parcel': {
fillColor: "yellow",
fill: true,
color: "red"
}
}
};
However as I am going to be adding multiple layers I need to add that layer name as a variable so I have something like this
var layers={parcels: ["#Parcels","http://localhost:7800/data_oh.parcel/{z}/{x}/{y}.pbf",'#ffe4c4','data_oh.parcel'],
footpring: ["#Footprints","http://localhost:7800/data_oh.footprint/{z}/{x}/{y}.pbf",'#8b8878','data_oh.footprint']
};
var idArray = [];
var layerArray = [];
function legend_click(id, layer_api, color_layer,layer_name) {
$(id).click(function () {
var layer_add;
var i = idArray.indexOf(id);
if (i < 0) {
layer_add = L.vectorGrid.protobuf(layer_api, {
interactive: true,
rendererFactory: L.svg.tile,
vectorTileLayerStyles: {
layer_name: {
fillColor: "yellow",fill: true, color: "red"
}
}
})
layerArray.push(layer_add);
idArray.push(id);
}
else {
layer_add = layerArray[i];
};
if ($(id).prop('checked') == true) {
layer_add.addTo(map);
}
else if ($(id).prop('checked') == false) {
map.removeLayer(layer_add);
}
})
};
for (var key in layers){
legend_click(layers[key][0],layers[key][1],layers[key][2],layers[key][3])
};
In the legend_click function the 4th input is for that layer name but the color is not changing on the map, this means the 4th input is not being recognized correctly in the vectorTileLayerStyles portion of the code. Again if I hardcode the values it works but passing through on a variable holding a string it does not.
You can use computed property names inside legend_click:
vectorTileLayerStyles: {
[`${layer_name}`]: {
fillColor: "yellow",fill: true, color: "red"
}
}
so if that did not work this should work:
vectorTileLayerStyles: Object.fromEntries([[layer_name,{fillColor: "yellow", fill: true, color: "red"}]])

Code efficiency using VectorGrid in Leaflet

I have about 7 000 polygons in a GeoJSON file using VectorGrid, all is fine using one layer but I need to split this layer into 10 LayerGroups (10 regions with their own polygons). How can this be done without rewriting the code 10 times? That seems to be lots of waste, there must be a smarter way and I can't figure it out. This is the code Im testing with, the highlight has to be working with all 11 layers...
var all_regions = new L.layerGroup();
var region_1 = new L.layerGroup();
var region_2 = new L.layerGroup();
var region_3 = new L.layerGroup();
/* snip */
var region_10 = new L.layerGroup();
var highlight_polygon;
var clearHighlight = function () {
if (highlight_polygon) {
vectorGrid.resetFeatureStyle(highlight_polygon);
}
highlight_polygon = null;
};
var vectorTileOptions_allRegions = {
rendererFactory: L.canvas.tile,
maxNativeZoom: 13,
zIndex: 6,
vectorTileLayerStyles: {
sliced: {
weight: 2,
color: "gray",
opacity: 1,
fill: false,
//fillColor: 'white',
//stroke: true,
fillOpacity: 0,
},
},
interactive: true,
getFeatureId: function (f) {
return f.properties.id;
},
};
var vectorTileOptions_region_1 = {
rendererFactory: L.canvas.tile,
maxNativeZoom: 13,
zIndex: 6,
vectorTileLayerStyles: {
sliced: function (properties, zoom) {
var region = properties.region;
if (region === "region one") {
return {
weight: 2,
color: "gray",
opacity: 1,
fill: false,
//fillColor: 'white',
//stroke: true,
fillOpacity: 0,
};
} else {
return {
weight: 0,
opacity: 0,
fill: false,
stroke: false,
fillOpacity: 0,
interactive: false,
};
}
},
},
interactive: true,
getFeatureId: function (f) {
return f.properties.id;
},
};
// Next vectorTileOptions until all 11 of them....
$.getJSON("/data/regions.geojson", function (json) {
//Not sure this is the correct way doing it...
var vectorGrid = L.vectorGrid
.slicer(json, vectorTileOptions_allRegions, vectorTileOptions_region_1)
.on("click", function (e) {
var properties = e.layer.properties;
L.popup()
.setContent(
"<b>Name</b>: " +
properties.region_name +
"<br><b>Date</b>: " +
"<i>" +
properties.date +
"</i>"
)
.setLatLng(e.latlng)
.openOn(map);
clearHighlight();
highlight_polygon = e.layer.properties.id;
vectorGrid.setFeatureStyle(highlight_polygon, {
weight: 3,
color: "gray",
opacity: 1,
fillColor: "#ff9999",
fill: true,
radius: 6,
fillOpacity: 0.3,
});
L.DomEvent.stop(e);
});
var clearHighlight = function () {
if (highlight_polygon) {
vectorGrid.resetFeatureStyle(highlight_polygon);
}
highlight_polygon = null;
map.on("popupclose", clearHighlight);
};
//This will not work....
vectorGrid.addTo(all_regions);
vectorGrid.addTo(region_1);
});
You probably want to do something like...
var regions = []; // An array that will hold instances of VectorGrid
var vectorGridOptions = {
rendererFactory: L.canvas.tile,
maxNativeZoom: 13,
zIndex: 6,
vectorTileLayerStyles: {
sliced: {}, // Empty, because it shall be overwritten later.
},
};
var defaultStyle = {
stroke: true,
weight: 2,
};
var regionStyles = [];
regionStyles[0] = {
weight: 2,
color: "gray",
};
regionStyles[1] = {
weight: 1,
color: "red",
};
/* ...etc, up to regionStyles[9] */
fetch("/data/regions.geojson")
.then(function (response) { return response.json(); })
.then(function (json) {
// For each number between 0 and 9...
for (var i = 0; i <= 9; i++) {
// Assuming that the GeoJSON data holds a FeatureCollection,
// create a copy of said GeoJSON FeatureCollection, but holding only
// the wanted features.
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var filteredGeoJSON = {
type: "FeatureCollection",
features: json.features.filter(function (feature) {
// This assumes that each Feature has a "regionID" property with a
// numeric value between 0 and 9.
return feature.properties.regionID === i;
}),
};
// Build up the options for the i-th VectorGrid by merging stuff together.
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
var fullRegionStyle = Object.assign({}, defaultStyle, regionStyles[i]);
// Overwrite some stuff in vectorGridOptions. Note that this changes the value of
// a piece of vectorGridOptions at each pass of the loop.
vectorGridOptions.vectorTileLayerStyles.sliced = fullRegionStyle;
regions[i] = L.vectorGrid.slicer(filteredGeoJSON, vectorTileOptions);
regions[i].addTo(map);
}
});
The key points here are:
Use a loop to iterate from 1 through 10
Keep things in numbered arrays instead of similarly-named variables
Filter the FeatureCollection, so each VectorGrid works with less data. Drawing invisible polygons/polylines would take as much computing time as drawing visible ones.
Refactor as much as possible, then build up concrete data structures (Object.assign, clone objects if needed)

Google Maps Api: cannot click on clickable polygon behind datalayer

Hi I am using google maps api(JavaScript) to build an interactive world map. It went really well until I ran into this problem. I am using polygons to show to outline of a country. These polygons trigger a modal showing information about the country when clicked on. This worked until I started to use "Data Layer: Earthquake data". Instead of using earthquake data I use sales information of the company I work at. So if a large share of our customers are from the Netherlands then the datalayer assigned to the Netherlands will be very large. The problem is that because of the datalayers the countries are no longer clickable. I can not click "through" the datalayer. Is there a possibility that I can trigger the event behind the datalayer?
This code displays the datalayers:
map.data.loadGeoJson('./data/test.json');
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0
}
})
});
map.data.addListener('mouseover', function(event) {
map.data.overrideStyle(event.feature, {
title: 'Hello, World!'
});
});
map.data.addListener('mouseout', function(event) {
map.data.revertStyle();
});
function eqfeed_callback(data) {
map.data.addGeoJson(data);
}
This code displays the polygons:
function drawMap(data) {
var rows = data['rows'];
for (var i in rows) {
if (rows[i][0] != 'Antarctica') {
var newCoordinates = [];
var geometries = rows[i][1]['geometries'];
if (geometries) {
for (var j in geometries) {
newCoordinates.push(constructNewCoordinates(geometries[j]));
}
} else {
newCoordinates = constructNewCoordinates(rows[i][1]['geometry']);
}
var country = new google.maps.Polygon({
paths: newCoordinates,
strokeColor: 'transparent',
strokeOpacity: 1,
strokeWeight: 0.3,
fillColor: '#cd0000',
fillOpacity: 0,
name: rows[i][0]
});
google.maps.event.addListener(country, 'mouseover', function() {
this.setOptions({
fillOpacity: 0.3
});
});
google.maps.event.addListener(country, 'mouseout', function() {
this.setOptions({
fillOpacity: 0
});
});
google.maps.event.addListener(country, 'click', function() {
var countryName = this.name;
var code = convert(countryName); // Calls a function that converts the name of the country to its official ISO 3166-1 alpha-2 code.
var modal = document.querySelector('.modal');
var instance = M.Modal.init(modal);
instance.open();
});
country.setMap(map);
}
}
If read in the documentation that changing the zIndex won't work because "Markers are always displayed in front of line-strings and polygons."
Is there a way to click on a polygon behind a datalayer?
EDIT
I tried to give the polygon a higher zIndex and I made the datalayer not clickable
map.data.loadGeoJson('./data/test.json');
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0,
clickAble: false,
zIndex: 50
}
})
});
function eqfeed_callback(data) {
map.data.addGeoJson(data);
}
function drawMap(data) {
var rows = data['rows'];
for (var i in rows) {
if (rows[i][0] != 'Antarctica') {
var newCoordinates = [];
var geometries = rows[i][1]['geometries'];
if (geometries) {
for (var j in geometries) {
newCoordinates.push(constructNewCoordinates(geometries[j]));
}
} else {
newCoordinates = constructNewCoordinates(rows[i][1]['geometry']);
}
var country = new google.maps.Polygon({
paths: newCoordinates,
strokeColor: 'transparent',
strokeOpacity: 1,
strokeWeight: 0.3,
fillColor: '#cd0000',
fillOpacity: 0,
name: rows[i][0],
zIndex: 100
});
google.maps.event.addListener(country, 'mouseover', function() {
this.setOptions({
fillOpacity: 0.3
});
});
google.maps.event.addListener(country, 'mouseout', function() {
this.setOptions({
fillOpacity: 0
});
});
google.maps.event.addListener(country, 'click', function() {
var countryName = this.name;
var code = convert(countryName); // Calls a function that converts the name of the country to its official ISO 3166-1 alpha-2 code.
var modal = document.querySelector('.modal');
var instance = M.Modal.init(modal);
instance.open();
});
country.setMap(map);
}
}
//console.log(map);
//test(map)
}
EDIT
Apparently the datalayer wasn't the problem, but the icon was. That is why it didn't work when I did this:
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0,
clickable: false
}
})
});
The correct way to do it is this:
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0
},
clickable: false
})
});
You basically have 2 options here:
Set the zIndex of your Polygons to a higher number than the data layer. Your Polygons will be clickable but obviously will appear above the data layer, which might not be what you want.
Set the clickable property of the data layer to false so that you can click elements that are below. This will work if you don't need to react to clicks on the data layer...
Option 2 example code:
map.data.setStyle({
clickable: false
});
Edit: Full working example below, using option 2. As you can see the Polygon is below the data layer but you can still click it.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: -28,
lng: 137
}
});
var polygon = new google.maps.Polygon({
strokeOpacity: 0,
strokeWeight: 0,
fillColor: '#00FF00',
fillOpacity: .6,
paths: [
new google.maps.LatLng(-26, 139),
new google.maps.LatLng(-23, 130),
new google.maps.LatLng(-35, 130),
new google.maps.LatLng(-26, 139)
],
map: map
});
polygon.addListener('click', function() {
console.log('clicked on polygon');
});
// Load GeoJSON
map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/google.json');
// Set style
map.data.setStyle({
fillColor: '#fff',
fillOpacity: 1,
clickable: false
});
}
#map {
height: 200px;
}
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
<div id="map"></div>
I have found that after, setting the z-order, the maps api does not reliably send clicks to polygon feature in the top layer when there are many polygons.
I had one data layer of regions where each feature is a precinct boundary. When you click on one feature, it loads another data layer on top. The top layer consists of polygons inside the region with a higher z-order, representing house title boundaries within that region.
After the houses are loaded, clicking on a house should send the click to the house polygon, not the region. But this sometimes failed - especially if there are many houses.
To resolve the issue, after clicking on a region feature, I set that feature to be non clickable. Then the clicks always propagate to the correct house feature. You can still click on other features of the lower layer, just not the selected one. This solution should work if your data and presentation follows a similar pattern.
/* private utility is only called by this.hideOnlyMatchingFeaturesFromLayer() */
_overrideStyleOnFeature(feature, layer, key, value, overrideStyle, defaultStyle) {
if (feature.getProperty(key) === value) {
if (this.map) {
layer.overrideStyle(feature, overrideStyle);
}
} else {
if (this.map) {
layer.overrideStyle(feature, defaultStyle);
}
}
}
/* Apply an overrideStyle style to features in a data layer that match key==value
* All non-matching features will have the default style applied.
* Otherwise all features except the matching feature is hidden!
* Examples:
* overrideStyle = { clickable: false,strokeWeight: 3}
* defaultStyle = { clickable: true,strokeWeight: 1}
*/
overrideStyleOnMatchingFeaturesInLayer(layer, key, value, overrideStyle, defaultStyle) {
layer.forEach((feature) => {
if (Array.isArray(feature)) {
feature.forEach((f) => {
_overrideStyleOnFeature(f, layer, key, value, overrideStyle, defaultStyle);
});
} else {
_overrideStyleOnFeature(feature, layer, key, value, overrideStyle, defaultStyle);
}
});
}
/* example usage */
overrideStyleOnMatchingFeaturesInLayer(
theRegionsDataLayer,
'PROP_NAME',
propValue,
{ clickable: false, strokeWeight: 3},
{ clickable: true, strokeWeight: 1}
);

How to pass 2 values to json style in leaflet

I need to pass 2 styles, i currently have:
First style:
function style(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.density)
};
}
The I do:
var classNameMap = <?php echo JSON_encode($classesForCountries); ?>;
geojson = L.geoJson(statesData, {
style: style,
style: function(feature) {
var classes = classNameMap[feature.properties.name];
return {className: classes};
},
onEachFeature: onEachFeature
}).addTo(map);
But that ignores the first style
I tried by passing it as an array:
geojson = L.geoJson(statesData, {
style: [style, function(){
var classes = classNameMap[feature.properties.name];
return {className: classes};
}],
onEachFeature: onEachFeature
}).addTo(map);
But yet, first style is ignored.
leaflet docs if this can help, here
This is the solution:
var classNameMap = <?php echo JSON_encode($classesForCountries); ?>;
function style(feature) {
var classes = classNameMap[feature.properties.name];
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.density),
className: classes
};
}
geojson = L.geoJson(statesData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
Not familiar with leaflet, but looking from js perspective using duplicate key will definitely override its value with the last key entry.
If you are trying append the style1 and style2, since both the functions of style returns an object, you can do so by $.extend.
function style_1(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.density)
};
}
...
style: function(feature) {
// Now the logic is a simple hashmap look-up
var style1 = style_1(feature);
var classes = classNameMap[feature.properties.name];
var finalStyle = $.extend(style1, {className: classes});
return finalStyle;
}
...
You're putting duplicate keys in the object initializer. Don't.
See How to generate a JSON object dynamically with duplicate keys? , Finding duplicate keys in JavaScript object

Categories

Resources