set marker visibility from geoJson source - geojson

I'm using a geojson that contains cities in italy, where I have "data" to read; data is stored in the properties fields. I can add even more data, for example we are thinking about adding the density of people for each city, to make cities more or less relevant, to be translated in which city is shown before on the maps.
The geojson:
{
type: "geojson",
data: {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [11.433, 46.883],
},
properties: {
title: "Vipiteno",
/* etc */
},
},
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [11.326, 46.46],
},
properties: {
title: "Bolzano",
/* etc */
},
},
],
},
}
On my page I add the geojson to the map by using this function:
map.on("load", function () {
// Add an image to use as a custom marker
map.loadImage("img", function (error, image) {
if (error) throw error;
map.addImage("custom-marker", image);
// Add a GeoJSON source with 2 points
map.addSource("points", geoJson);
map.addLayer({
id: "points",
type: "symbol",
source: "points",
layout: {
"icon-image": "custom-marker",
// get the title name from the source's "title" property
"text-field": ["get", "title"],
"text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
"text-offset": [0, 1.25],
"text-anchor": "top",
},
});
});
});
So how can I control which markers are shown at first load, and then showing more more points when the user zooms in?
Right now just a few are rendered at starting zoom level, but there is no control on which, and small cities are rendered before capitals (for example).
How can I override this?

You can override this by setting the zoom / adding a zoom expression for dynamic visibility changes. The below Mapbox example does something similar. By using a dynamic zoom expression the cirle layer opacity is gradually changed. You could do the same for your layer. Thereby you can control which layer is visible at which zoom with which specific opacity. Please see this example:
https://docs.mapbox.com/help/tutorials/mapbox-gl-js-expressions/#add-a-zoom-expression
(To run, exchange "YOUR ACCESS TOKEN")
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Minneapolis Landmarks</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css' rel='stylesheet' />
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'YOUR ACCESS TOKEN';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/light-v10', // stylesheet location
center: [-93.261, 44.971], // starting position [lng, lat]
zoom: 10.5 // starting zoom
});
map.on('load', function() {
map.addLayer({
id: 'historical-places',
type: 'circle',
source: {
type: 'vector',
url: 'mapbox://your-tileset-id-here'
},
'source-layer': 'your-source-layer-here',
paint: {
'circle-radius': [
'interpolate', ['linear'], ['zoom'],
10, ['/', ['-', 2017, ['number', ['get', 'Constructi'], 2017]], 30],
13, ['/', ['-', 2017, ['number', ['get', 'Constructi'], 2017]], 10],
],
'circle-opacity': 0.8,
'circle-color': 'rgb(171, 72, 33)'
}
});
});
</script>
</body>
</html>

Related

Snazzy Maps in Rails Application

I set up a nice map in my rails application. Everything is working fine but I cannot style the map with SnazzyMaps.
Here is my map.js file:
import GMaps from 'gmaps/gmaps.js';
const mapElement = document.getElementById('map');
if (mapElement) { // don't try to build a map if there's no div#map to inject in
const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
const markers = JSON.parse(mapElement.dataset.markers);
const mapMarkers = map.addMarkers(markers);
mapMarkers.forEach((marker, index) => {
marker.addListener('click', () => {
// map.setCenter(markers[index]);
markers[index].infoWindow.open(map, marker);
})
});
if (markers.length === 0) {
map.setZoom(2);
} else if (markers.length === 1) {
map.setCenter(markers[0].lat, markers[0].lng);
map.setZoom(14);
} else {
map.fitLatLngBounds(markers);
}
}
import { autocomplete } from '../components/autocomplete';
// [...]
autocomplete();
On SnazzyMaps they give the following example. My question is, where shall I insert which part of this code in my own file. Been trying it for a while now but cannot make it work. Here is SnazzyMaps example:
<!DOCTYPE html>
<html>
<head>
<title>Snazzy Maps Super Simple Example</title>
<style type="text/css">
/* Set a size for our map container, the Google Map will take up 100% of this container */
#map {
width: 750px;
height: 500px;
}
</style>
<!--
You need to include this script tag on any page that has a Google Map.
The following script tag will work when opening this example locally on your computer.
But if you use this on a localhost server or a live website you will need to include an API key.
Sign up for one here (it's free for small usage):
https://developers.google.com/maps/documentation/javascript/tutorial#api_key
After you sign up, use the following script tag with YOUR_GOOGLE_API_KEY replaced with your actual key.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API_KEY"></script>
-->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
function init() {
// Basic options for a simple Google Map
// For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 11,
// The latitude and longitude to center the map (always required)
center: new google.maps.LatLng(40.6700, -73.9400), // New York
// How you would like to style the map.
// This is where you would paste any style found on Snazzy Maps.
styles: [{"featureType":"all","elementType":"geometry.fill","stylers":[{"weight":"2.00"}]},{"featureType":"all","elementType":"geometry.stroke","stylers":[{"color":"#9c9c9c"}]},{"featureType":"all","elementType":"labels.text","stylers":[{"visibility":"on"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"landscape","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"color":"#eeeeee"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#7b7b7b"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#46bcec"},{"visibility":"on"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"color":"#c8d7d4"}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"color":"#070707"}]},{"featureType":"water","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]}]
};
// Get the HTML DOM element that will contain your map
// We are using a div with id="map" seen below in the <body>
var mapElement = document.getElementById('map');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
// Let's also add a marker while we're at it
var marker = new google.maps.Marker({
position: new google.maps.LatLng(40.6700, -73.9400),
map: map,
title: 'Snazzy!'
});
}
</script>
</head>
<body>
<h1>Snazzy Maps Super Simple Example</h1>
<h2>WY</h2>
<!-- The element that will contain our Google Map. This is used in both the Javascript and CSS above. -->
<div id="map"></div>
</body>
</html>
To set the style using Gmaps library, you need to define the styles and then set it to the current map as below:
const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
var styles = [
{
stylers: [
{ hue: "#00ffe6" },
{ saturation: -20 }
]
}, {
featureType: "road",
elementType: "geometry",
stylers: [
{ lightness: 100 },
{ visibility: "simplified" }
]
}, {
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
map.addStyle({
styledMapName:"Styled Map",
styles: styles,
mapTypeId: "map_style"
});
map.setStyle("map_style");
Reference:
https://github.com/hpneo/gmaps/blob/master/examples/styled_maps.html

highmaps stopped updating after move to .NET Core

I have a working website using the standard Visual Studio 2017. It is composed of a C# backend with a single API used to request data to be displayed in HighMaps based on the settings the user chooses from the jQuery UI. Since I don't love my Windows machine nearly as much as my Mac, I thought I would try using .Net Core 2.0 - and thus eliminate the need for my Windows laptop. Everything went extremely well (Kudos to Microsoft), but for some reason the jQuery code that calls the API, the data returned is not being pushed into the map like it should.
Here is the jQuery code that runs - the alert() does display the JSON data, but it never is reflected in the map. I can post HTML or CSS if needed, but for now I have included the head and script sections.
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Great Locations</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/maps/highmaps.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/maps/modules/data.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/mapdata/countries/us/us-all-all.js"></script>
</head>
And here is the jQuery Code:
<script type="text/javascript">
var climateSteps = [
"Tropical",
"Semi-Arid",
"Desert",
"Humid",
"Mediterranean",
"Wet All Seasons",
"Wet Summer",
"Winter Snow",
"Polar"];
var climateRange = "C08";
$(function () {
$("#climate-slider .slider").slider({
range: true,
min: 0,
max: 8,
values: [0, 8],
slide: function (event, ui) {
climateRange = "C" + ui.values[0].toString() + ui.values[1].toString();
if (ui.values[0] == ui.values[1]) {
/* if user selected a single value (not a range), adjust text to fit */
$(this).parent().children(".slider-range").text(climateSteps[ui.values[0]]);
}
else {
$(this).parent().children(".slider-range").text(climateSteps[ui.values[0]] + " to " + climateSteps[ui.values[1]]);
}
}
})
});
$.noConflict();
tableResult = '[{"code":"us-al-001","name":"Autauga County, AL","value":1}, {"code":"us-il-019","name":"Champaign County, IL","value":3}]';
(function ($) {
function GetCounties(userSelections) {
jQuery.support.cors = true;
$.ajax({
url: "http://localhost:5000/api/products/" + userSelections,
type: "GET",
dataType: "json",
success: function (d) {
data = JSON.stringify(d);
alert("API data received: " + data)
tableResult = data;
$("#map-container").highcharts().series[0].update({
data: JSON.parse(d)
});
},
error: function (d) {
alert("API found error: " + JSON.stringify(d));
}
});
}
jQuery(".button-submit").bind("click", {
}, function (e) {
GetCounties(climateRange);
});
data = JSON.parse(tableResult);
var countiesMap = Highcharts.geojson(Highcharts.maps["countries/us/us-all-all"]);
var lines = Highcharts.geojson(Highcharts.maps["countries/us/us-all-all"], "mapline");
// add state acronym for tooltip
Highcharts.each(countiesMap, function (mapPoint) {
var state = mapPoint.properties["hc-key"].substring(3, 5);
mapPoint.name = mapPoint.name + ", " + state.toUpperCase();
});
var options = {
chart: {
borderWidth: 1,
marginRight: 50 // for the legend
},
exporting: {
enabled: false
},
title: {
text: "My Great Locations"
},
legend: {
layout: "vertical",
align: "right",
floating: true,
valueDecimals: 0,
valueSuffix: "",
backgroundColor: "white",
symbolRadius: 0,
symbolHeight: 0
},
mapNavigation: {
enabled: false
},
colorAxis: {
dataClasses: [{
from: 1,
to: 1,
color: "#000099",
name: "Perfect!"
}, {
from: 2,
to: 2,
color: "#009999",
name: "Very Nice!"
}, {
from: 3,
to: 3,
color: "#00994c",
name: "Good Fit"
}]
},
tooltip: {
headerFormat: "",
formatter: function () {
str = "Error";
if (this.point.value == 1) {
str = "Perfect!";
}
if (this.point.value == 2) {
str = "Very Nice!";
}
if (this.point.value == 3) {
str = "Good Fit";
}
return this.point.name + ": <b>" + str + "</b>";
}
},
plotOptions: {
mapline: {
showInLegend: false,
enableMouseTracking: false
}
},
series: [{
mapData: countiesMap,
data: data,
joinBy: ["hc-key", "code"],
borderWidth: 1,
states: {
hover: {
color: "#331900"
}
}
}, {
type: "mapline",
name: "State borders",
data: [lines[0]],
color: "black"
}]
};
// Instanciate the map
$("#map-container").highcharts("Map", options);
All that appears in the map are the two counties that I hardcoded (to show that the map is working fine). I'm wondering if there is some package I need to add into NuGet or SDK Dependencies, but so much is working that I don't know what is missing. And I've not figured out how to show the console in Mac Visual Studio, so if any clues are going there, I haven't seen them.
Great thanks to the Highcharts support team - the ultimate answer to this problem is that the Mac Visual Studio .Net Core framework for some reason acts different than the Windows platform running the classic Visual Studio. Here is the answer that worked for me:
I needed to use this with Mac Visual Studio with .Net Core - no JSON.parse(d) required:
$("#map-container").highcharts().series[0].update({
data: d
});
Instead of this, which works for Windows full-blown Visual Studio (community edition):
$("#map-container").highcharts().series[0].update({
data: JSON.parse(d)
});

polygon around polyline with radius?

I have the problem with drawing polygon around polyline.
I have coordinates of every polyline's point and I want to get coordinates of polygon around this polyline.
I use MapBox's map.
Any ideas? I didn't find solutions.
Something, that seems like this.
I need to get coordinates for drawing polygon around line.
I found solution, guys! That was really diffucult :D
According to last hint about Turf :)
I found pod "SwiftTurf"
var coordsPointer = UnsafeMutablePointer<CLLocationCoordinate2D>.allocate(capacity: Int(polyline.pointCount))
polyline.getCoordinates(coordsPointer, range: NSMakeRange(0, Int(polyline.pointCount)))
// save coords
var lineCoords: [CLLocationCoordinate2D] = []
for i in 0..<polyline.pointCount {
lineCoords.append(coordsPointer[Int(i)])
}
let lineString:LineString = LineString(geometry: lineCoords)
let bufferLineString = SwiftTurf.buffer(lineString, distance: width, units: .Meters)
let outer = bufferLineString!.geometry![0]
let interiors = bufferLineString?.geometry![1..<bufferLineString!.geometry.count].map({ coords in
return MGLPolygon(coordinates: coords, count: UInt(coords.count))
})
// This polygon is solution
self.currentBufferPolygon = MGLPolygon(coordinates: outer, count: UInt(outer.count), interiorPolygons: interiors)
mapView.addAnnotation(self.currentBufferPolygon!)
U can find more info on github in the pod's repo :) Good luck!
If you're looking to draw a polygon around a polyline in the browser, I suggest using turf.js. Turf's buffer method should work nicely for this exact case.
Here's an example on a Mapbox GL JS map
var line = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [
[-122.40447521209718,
37.79367718768535
],
[-122.40803718566895,
37.79171022624846
],
[-122.40769386291502,
37.79096412372944
],
[-122.40662097930908,
37.789641468930114
],
[-122.40941047668457,
37.789675383451495
],
[-122.40992546081543,
37.78875968591083
],
[-122.40962505340575,
37.78791180770003
]
]
}
};
mapboxgl.accessToken = 'pk.eyJ1IjoibWFwc2FtIiwiYSI6ImNqNzI4ODR4djBkZmczMnJzZjg3eXZhcDgifQ.5xM2OR_RvuO6YvirBVeiOg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
zoom: 15,
center: [-122.4067, 37.7899]
});
map.on('load', function() {
map.addLayer({
"id": "route",
"type": "line",
"source": {
"type": "geojson",
"data": line
}
});
var polygon = turf.buffer(line, 50, 'meters');
map.addLayer({
"id": "poly",
"type": "fill",
"source": {
"type": "geojson",
"data": polygon
},
"layout": {},
"paint": {
"fill-color": '#d9d838',
"fill-opacity": 0.3
}
});
});
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.39.1/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.39.1/mapbox-gl.css' rel='stylesheet' />
<script src='https://npmcdn.com/#turf/turf/turf.min.js'></script>
</head>
<body>
<div id='map'></div>
</body>
</html>

Graph in popup and separate Div in Leaflet

I wonder if anyone can tell me what is wrong in my code please? I want to be able to select a polygon and show a graph in a popup using leaflet and highchart. I have managed to create the graph in the popup, but the line is missing on it, and I also get a separate div showing the same chart (and the line) at the bottom of my web page which I don't want. Can anyone tell me how to get the line to show on the chart in the popup and to remove the separate chart? Here is my code.enter code here
<!DOCTYPE html>
<html>
<head>
<title>Quick Start - Leaflet</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--include leaflet CSS file-->
<link rel="stylesheet" href="css/leaflet.css" />
<link rel="markers" type="images/marker-icon" href="images/marker-icon.png" />
<!--include Leaflet Javascript file-->
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="js/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script src='http://unpkg.com/leaflet#1.0.2/dist/leaflet.js'></script>
<script src="js/esri-leaflet.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
</head>
<body>
<!--Put a div element with a certain id where you want your map to be: -->
<div id="map" style="width: 1000px; height: 800px;"></div>
<div id="chartcontainer" class="highchart" style="width: 500px; height: 200px;"></div>
<!-- First we’ll initialize the map and set its view to our chosen geographical coordinates and a zoom level:-->
<script>
var mymap = L.map('map', {
zoomControl:true, maxZoom:28, minZoom:1
}).fitBounds([[51.0269253989,-1.34762355597],[51.1990603009,-0.951310026203]]);
L.esri.basemapLayer('Imagery').addTo(mymap);
//loads geoserver layer as WMS
var field_boundaries = L.tileLayer.wms("http://localhost:1997/geoserver/RSAC/wms", {
layers: 'RSAC:results_clipped_with_growth_small_new',
format: 'image/png',
transparent: true,
version: '1.1.0',
attribution: "myattribution"
});
//loads the geojson layer
var owsrootUrl = 'http://localhost:1997/geoserver/RSAC/wms';
var defaultParameters = {
service : 'WFS',
version : '2.0',
request : 'GetFeature',
typeName : 'RSAC:results_clipped_with_growth_small_new',
outputFormat : 'json',
format_options : 'callback:getJson',
SrsName : 'EPSG:4326'
};
var parameters = L.Util.extend(defaultParameters);
var URL = owsrootUrl + L.Util.getParamString(parameters);
var ajax = $.ajax({
url : URL,
dataType : 'json',
jsonpCallback : 'getJson',
success : function (response) {
L.geoJson(response, {
onEachFeature: function (feature, url) {
url.on('click', function(e){
var chartplotoptions ={
chart: {
type: 'line'
},
title: {
text: 'Growth'
},
xAxis: {
allowDecimals: true,
categories: ['20151114', '20151126', '20151208', '20151220', '20160113', '20160125', '20160206', '20160218', '20160301', '20160313', '20160325', '20160406', '20160418', '20160430', '20160512', '20160524', '20160605', '20160629', '20160723', '20160804', '20160816'],
labels: {
formatter: function () {
return this.value;
}
}
},
yAxis: {
startOnTick: false,
minPadding: 0.05,
title: {
text: 'Crop Growth',
},
labels: {
formatter: function () {
return this.value;
}
}
},
tooltip: {
pointFormat: '{series.name}{point.y}'
},
plotOptions: {
area: {
pointStart: -20,
threshold: 10,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: false
}
}
}
}
},
series: [{
name: 'Growth',
data: [parseFloat(feature.properties.Date_20151114),parseFloat(feature.properties.Date_20151126),parseFloat(feature.properties.Date_20151208), parseFloat(feature.properties.Date_20151220), parseFloat(feature.properties.Date_20160113), parseFloat(feature.properties.Date_20150125), parseFloat(feature.properties.Date_20160206), parseFloat(feature.properties.Date_20160218), parseFloat(feature.properties.Date_20160301), parseFloat(feature.properties.Date_20160313), parseFloat(feature.properties.Date_20160325), parseFloat(feature.properties.Date_20160406), parseFloat(feature.properties.Date_20160418), parseFloat(feature.properties.Date_20160430), parseFloat(feature.properties.Date_20160512), parseFloat(feature.properties.Date_20160524), parseFloat(feature.properties.Date_20160605), parseFloat(feature.properties.Date_20160629), parseFloat(feature.properties.Date_20160723), parseFloat(feature.properties.Date_20160804), parseFloat(feature.properties.Date_20160816)]
},
]
};
$('#chartcontainer').highcharts(chartplotoptions);
url.bindPopup($('#chartcontainer').html());
url.openPopup();
});
}
}).addTo(mymap);
}
});
</script>
</body>
</html>
You don't need the div element in your HTML markup. You can create one on the fly in your onEachFeature function and add it to the popup. Also, you need to initialize your highchart after the popup has opened, not before. In code with comments:
new L.GeoJSON(feature, {
onEachFeature: function (feature, layer) {
// Create div with class name highchart
var div = L.DomUtil.create('div', 'highchart');
// Bind popup to layer with div as content
layer.bindPopup(div);
// Handle event when popup opens
layer.on('popupopen', function (e) {
console.log(e.target); // layer object
console.log(e.target.feature); // layer's feature object
console.log(e.popup); // popup object
console.log(e.popup.getContent()); // the div
// Now do the highcharts stuff
Highcharts.chart(e.popup.getContent(), { /**/ });
});
}
});
And don't forget to set the div's dimensions with CSS:
.highchart {
width: 500px;
height: 200px;
}

How to open highcharts in new window? [duplicate]

I use highcharts to display a chart in my page.
It works fine, but some times data in graph is too "condensed" so I should find a way to see the graph in a greater size.
I read several posts over internet on this subject:
- in general they suggest to use highslide, but i don't want to, as my page is already overlaoded by scripts
-somebody tries to pop up the content in a popup, it could fit to me but I didn't succeed
- the only quasi-working example which fits to me seems to be the following:
(inside the options object I add this properties).
exporting: {
buttons: {
popUpBtn: {
symbol: 'square',
_titleKey: 'FullScreenButtonTitle',
x: -60,
symbolSize:18,
symbolFill: '#B5C9DF',
hoverSymbolFill: '#779ABF',
onclick: function () {
var win=window.open('','','location=0,titlebar=0,status=0,width=780,height=350');
win.focus();
var divtag = win.document.createElement("div");
divtag.id = "div1";
win.document.body.appendChild(divtag);
win.document.write('<script type="text/javascript" src="script/highcharts/js/highcharts.js"></script>\
<script type="text/javascript" src="script/highcharts/js/modules/exporting.js"></script>');
this.options.renderTo=divtag;
var chart = new Highcharts.Chart(this.options);
win.document.close();
}
},
exportButton: {
enabled: true
},
printButton: {
enabled: true
}
}
}
However it is not working, as the div tag is not inserted and all i get is this
<html>
<head>
<script type="text/javascript" src="script/highcharts/js/highcharts.js"> </script>
<script type="text/javascript" src="script/highcharts/js/modules/exporting.js"></script>
</head></html>
I can't understand the error.
I know it should be something simple but I can't get out alone.
--EDIT ---
I finally understood which could be a working strategy: create a "chartpopup.html" page, and passing it the parameters needed to build the copy of the graph I visualize.
So now I have:
index.html:
chartOptions = {
series: [
{
name: 'example',
data: [83.6, 78.8, 98.5, 93.4, 106.0]
}]
//// CUT SOME CODE
exporting: {
buttons: {
popUpBtn: {
enabled:true,
symbol: 'square',
_titleKey: 'FullScreenButtonTitle',
x: -60,
symbolSize:18,
symbolFill: '#B5C9DF',
hoverSymbolFill: '#779ABF',
onclick: function () {
look this!--------> generalPurposeGlobalVar = this;
var win=window.open('./chartpopup.html','Full Size Chart','location=0,titlebar=0,status=0,width=780,height=650');
}
},
exportButton: {
enabled: true
},
printButton: {
enabled: true
}
}
}
};
this.highChart=new Highcharts.Chart(this.chartOptions);
and chartpopup.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chart full Size</title>
<script type="text/javascript" src="script/jquery-1.7.1-min.js"></script>
<script type="text/javascript" src="script/highcharts/js/highcharts.js"></script>
<script type="text/javascript" src="script/highcharts/js/modules/exporting.js"> </script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 650; margin: 0 auto"></div>
<script>
var chart;
$(document).ready(function() {
var mychart=window.opener.generalPurposeGlobalVar;
mychart.options.chart.renderTo= 'container';
chart = new Highcharts.Chart(mychart.options);
});
</script>
</body>
</html>
This two pages are actually working ONLY with the default graph. If I modify and re-render the graph, I'm not able to reproduce it on the popup page!
The code I use to modify the graph is basically this:
this.chartOptions.series=[{name:field.split('_').join('\n')}];
this.highChart.destroy();
this.highChart=new Highcharts.Chart(this.chartOptions);
this.highChart.xAxis[0].setCategories(_.isEmpty(mygroups) ? [] : mygroups);
this.highChart.series[0].setData([]);
this.highChart.setTitle({text: this.highChart.title.text},{text:(field.split('_').join(' ')), });
this.highChart.redraw();//
[...]
self.highChart.series[0].addPoint(result);//it's a point I calculated before
Here is an Highcharts exemple working with an "oldschool" popup :
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>highcharts foobar</title>
</head>
<body>
Open Chart Popup
<script>
function open_chart_popup() {
window.open('popup.html', 'chart popup title', 'width=1680px height=1050px');
}
</script>
</body>
</html>
popup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>highcharts foobar</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
<script>
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldClimate.com',
x: -20
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y +'°C';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}, {
name: 'New York',
data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
}, {
name: 'Berlin',
data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
}, {
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]
});
});
</script>
</body>
</html>
If this solution doesn't fit to you, could you tell us which JavaScript libraries you use (this example relies on jQuery). As the documentation says, highcharts requires either jQuery, Mootools or Prototype : http://www.highcharts.com/documentation/how-to-use
If you are able to use jQuery, you can replace that popup by using some cooler effects like those ones : http://jqueryui.com/demos/dialog/
Despite of that, if you want assistance for your script, could you consider making a jsfiddle, i'm not able to reproduce your error.
EDIT :
Okay, so you have all the stuff to deal with that.
I see two options :
You send the user input series JSON data to your server by an AJAX request. Then your server send you back a view or a bunch of html/js containing your highchart with the user datas. Back to the client, you do wathever you want with that (like triggering a popup containing the graph). I'm not too comfortable with backbone but i'm sure you can generate a template and render it back (this may help http://japhr.blogspot.fr/2011/08/getting-started-with-backbonejs-view.html)
The other solution would be to directly set your template (containing the graph) to the view but hidding him by default. Then, when the series are correctly setted by the user, you simply display the template (in a popup for example). This solution avoid a server call, so I would suggest that.
EDIT 2 :
So, I've made a jsFiddle showing a basic example on how to update a chart based on a user input : http://jsfiddle.net/MxtkM/
The example updates the last value of all the series on the graph, here is how :
$('#december_value').bind('keyup', function() {
var user_input_value = parseFloat($(this).val()); // cast to float
for (var s in chart.series) { // loop through the series
var old_data = chart.series[s].data;
var new_data = [];
for (var d in old_data ) { // loop through data objects
new_data.push(old_data[d].config); // config property contains the y value
}
new_data[new_data.length - 1] = user_input_value; // update the last value
chart.series[s].setData(new_data); // use setData method to refresh the datas of the serie
}
});
This example use the method setData by providing a new data array.
If this doesn't fit your needs, there is an another method to refresh your graph in whitch you rerender all the graph by doing var chart = new Highcharts.Chart(options);. (This is explained in the links above).
This two links are also a good read :
Reload chart data via JSON with Highcharts
http://www.highcharts.com/documentation/how-to-use (part 3 and 4)
Now you shoud be able to do whatever you want with your graph based on a user input.
After wandering around and asking questions, I found out that the best way to do it is to make fullscreen the div that contains the chart.
It's a very simple solution but it works.
This post is very helpful How do I make a div full screen?
A function like the following should do the trick on a "#graph" div:
function fullscr() {
$('#graph').css({
width: $(window).width(),
height: $(window).height()
});
}
Hope this help.
The Best solution will be HTML5 Fullscreen API for fullscreen
function fullScreen(){
var elem = document.getElementById("highchart_div_id");
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
}
However, this piece of code only works in New Generation Browsers and I have hands on working output from Google chrome and Mozilla Firefox
Good Day

Resources