display data from featureLayer in one displayLevel - javascript

i have a problem with displaying informations on an Basemap in two of tree displayLevels.
I Have a program that is inspired from this esri sample:https://developers.arcgis.com/javascript/jssamples/data_gas_prices.html
After this i have build my own zoomLevels or display Levels because i only need three.
My Problem is that i want to have only in two of three zoomLevels text in my featureLayer and i have no Idea how to do this. The only Example i found in the Internet was this Sample form Esri: https://developers.arcgis.com/javascript/jssamples/map_switch_layer_on_zoom.html
But they work with ArcGISTiledMapServiceLayer and i'm not.
So please can anybody tell me a solution for this Problem?
Here is the code:
define([
"dojo/_base/declare",
"dojo/_base/array",
"esri/map",
"esri/graphic",
"esri/lang",
"esri/geometry/Extent",
"esri/symbols/SimpleLineSymbol",
"esri/symbols/SimpleFillSymbol",
"esri/renderers/SimpleRenderer",
"esri/renderers/ClassBreaksRenderer",
"esri/symbols/Font",
"esri/symbols/TextSymbol",
"esri/layers/FeatureLayer",
"esri/dijit/Legend",
"esri/dijit/OverviewMap",
"esri/InfoTemplate",
"esri/request",
"modules/mapTip",
"dijit/TooltipDialog",
"dijit/popup",
"dojo/json",
"dojo/store/JsonRest",
"dojo/_base/array",
"dojo/parser",
"dojo/_base/connect",
"dojo/_base/Color",
"dojo/number",
"dojo/dom",
"dojo/dom-construct",
"dojo/dom-style",
"dijit/form/Button",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dijit/layout/AccordionContainer",
"dojo/domReady!"
], function(
declare,array, Map, Graphic, esriLang, Extent, SimpleLineSymbol, SimpleFillSymbol, SimpleRenderer,
ClassBreaksRenderer, Font, TextSymbol,FeatureLayer, Legend, OverviewMap, InfoTemplate, esriRequest,Tip,
TooltipDialog, dijitPopup,JSON, JsonRest, arr, parser, conn, Color, number, dom, domConstruct, domStyle, Button) {
return declare (null, {
init: function (){
var lods = [
//{"level" : 1, "resolution" : 78271.5169639999, "scale" : 295828763.795777},
//{"level" : 2, "resolution" : 39135.7584820001, "scale" : 147914381.897889},
//{"level" : 3, "resolution" : 19567.8792409999, "scale" : 73957190.948944},
//{"level" : 4, "resolution" : 9783.93962049996, "scale" : 36978595.474472},
//{"level" : 5, "resolution" : 4891.96981024998, "scale" : 18489297.737236},
//{"level" : 6, "resolution" : 2445.98490512499, "scale" : 9244648.868618},
{"level" : 7, "resolution" : 1222.99245256249, "scale" : 4622324.434309},
//{"level" : 8, "resolution" : 611.49622628138, "scale" : 2311162.217155},
//{"level" : 9, "resolution" : 305.748113140558, "scale" : 1155581.108577},
{"level" : 10, "resolution" : 152.874056570411, "scale" : 577790.554289},
//{"level" : 11, "resolution" : 76.4370282850732, "scale" : 288895.277144},
{"level" : 12, "resolution" : 38.2185141425366, "scale" : 144447.638572},
//{"level" : 13, "resolution" : 19.1092570712683, "scale" : 72223.819286},
//{"level": 14, "resolution": 9.55462853563415, "scale": 36111.909643},
//{"level": 15, "resolution": 4.77731426794937, "scale": 18055.954822},
//{"level": 16, "resolution": 2.38865713397468, "scale": 9027.977411},
//{"level": 17, "resolution": 1.19432856685505, "scale": 4513.988705}
];
var fl = new FeatureLayer("someServer/arcgis/rest/services/someProject/FeatureServer/1", {
mode: FeatureLayer.MODE_SNAPSHOT,
displayLevels:[0,1],
outFields:["*"],
//infoTemplate: template,
visible: true,
value: "OBJECTID",
});
window.map = new Map("map", {
basemap:"topo",
center: [48.04, 28.50],
zoom: 0,
lods: lods,
});
var overviewMapDijit = new OverviewMap({
map: window.map,
visible: true
});
overviewMapDijit.startup();
var updateEnd = fl.on("update-end", function() {
updateEnd.remove();
updateRenderer();
updateLables();
});
window.map.addLayers([fl]);
function updateRenderer(){
fl.setRenderer(new SimpleRenderer(null));
var kachelnamen = new JsonRest({
target: "someTargetURL",
idAttribute: "WA",
headers: { "X-Requested-With": "" },
});
kachelnamen.query(null).then(drawFeatureLayer, kachelnamenError);
console.debug(kachelnamen);
console.info(kachelnamen);
}
////////////////////////////////////////////////
function updateLables(){
var font = new Font("11px", Font.STYLE_NORMAL, Font.VARIANT_NORMAL, Font.WEIGHT_BOLDER);
arr.forEach(fl.graphics, function(graphic){
var centerPoint;
switch (graphic.geometry.type) {
case "point":
centerPoint = graphic.geometry;
break;
case "extent":
centerPoint = graphic.getCenter();
default:
centerPoint = graphic._extent.getCenter();
}
var textSymbol = new TextSymbol(graphic.attributes.NAME,font, new Color([0, 0, 0]));
var labelPointGraphic = new Graphic(centerPoint, textSymbol);
window.map.graphics.add(labelPointGraphic);
});
}
///////////////////////////////////////////////////////////
function drawFeatureLayer(data) {
// data comes back as text from apify...parse it
// loop through gas price data, find min/max and populate an object
// to keep track of the price of regular in each state
window.statekachelnamen = {};
var gasMin = Infinity;
var gasMax = -Infinity;
arr.forEach(data, function(g) {
var price = parseFloat(g.STAT_CALC);
statekachelnamen[g.WA] = price;
if ( price < gasMin ) {
gasMin = price;
}
if ( price > gasMax ) {
gasMax = price;
}
});
// format max gas price with two decimal places
gasMax = formatDollars(gasMax);
// add an attribute to each attribute so gas price is displayed
// on mouse over below the legend
arr.forEach(fl.graphics, function(g) {
//var displayValue = statekachelnamen[g.attributes.WA_NAME].toFixed(2);
var displayValue;
if (g.attributes.WA_NAME in statekachelnamen){
displayValue = statekachelnamen[g.attributes.WA_NAME].toFixed(2);
}
else{
displayValue = 0;
}
g.attributes.STAT_CALC = displayValue;
});
// create a class breaks renderer
var breaks = calcBreaks(gasMin, gasMax, 4);
//gasMax = formatDollars(gasMax);
// console.log("gas price breaks: ", breaks);
var sfs = SimpleFillSymbol;
var sls = SimpleLineSymbol;
var outline = sls("solid", new Color("#444"), 1);
var br = new ClassBreaksRenderer(null, findGasPrice);
br.setMaxInclusive(true);
br.addBreak(breaks[0], breaks[1], new sfs("solid", outline, new Color([255, 255, 178, 0.75])));
br.addBreak(breaks[1], breaks[2], new sfs("solid", outline, new Color([254, 204, 92, 0.75])));
br.addBreak(breaks[2], breaks[3], new sfs("solid", outline, new Color([253, 141, 60, 0.75])));
br.addBreak(breaks[3], gasMax, new sfs("solid", outline, new Color([227, 26, 28, 0.75])));
fl.setRenderer(br);
fl.redraw();
var legend2 = new Legend({
map: window.map,
layerInfos: [{ "layer": fl, "title": "WA Statistic" }]
},"legendDiv2");
legend2.startup();
// remove the loading div
//domConstruct.destroy("loading");
}
// function used by the class breaks renderer to get the
// value used to symbolize each state
function findGasPrice(graphic) {
var state = graphic.attributes.WA_NAME;
return statekachelnamen[state];
console.info(state);
}
function calcBreaks(min, max, numberOfClasses) {
var range = (max - min) / numberOfClasses;
var breakValues = [];
for ( var i = 0; i < numberOfClasses; i++ ) {
breakValues[i] = formatDollars(min + ( range * i ));
}
// console.log("break values: ", breakValues)
return breakValues;
}
var myButton = new Button({
label: "Update Renderer!",
onClick: function(){
updateRenderer();
}
}, "progButtonNode");
function formatDollars(num) {
return num.toFixed(2);
//return number.format(num, { "places": 2 });
}
function kachelnamenError(e) {
console.log("error getting gas price data: ", e);
}
}
});
});
![here the text is correct][1]
![here the text is correct too ][2]
![I don't want to display text here][3]

OK I found a solution for my Problem.
Here is it
window.map.addLayers([fl]);
var updateEnd = fl.on("update-end", function() {
updateEnd.remove();
updateRenderer();
updateLables();
//show or hide the SWA text when the map's extent changes
window.map.on("extent-change", function(evt) {
var currentScale = map.getScale();
console.log('maponScale: ' + currentScale);
if (currentScale.toString() == "4622324.434309"){
window.map.graphics.hide();
}
else{
window.map.graphics.show();
}
});
});

Related

mapbox geojson description for popup showing 'undefined'

I have the following code but when I click on a point to open a popup it returns 'undefined' and I cannot seem to work out why.
I'm pulling the description field from the geoJSON external source which I have control over but for some reason it just does not want to populate the description HTML in my array. I took the example for the popup from the mapbox website so I know it works there. I have checked, rechecked and triple checked but I think I cannot see the tree for the forest lol.
Could someone maybe help me please? thanks.
<script>
// ajax loading gif
$(document).ready(function () {
setTimeout(function () {
$("#ajax-loader").removeClass("is-active");
}, 6000);
});
// vars
var initialOpacity = 0.2;
var opacity = initialOpacity;
// mapbox api
mapboxgl.accessToken = "hidden_api_key";
var map = new mapboxgl.Map({
container: "map", // container ID
style: "mapbox://styles/mapbox/dark-v10",
center: [-2.582861, 53.5154517],
zoom: 5,
maxZoom: 16,
minZoom: 0,
});
map.on("load", function () {
// get hotspot locations
map.addSource("hotspot_locations", {
type: "geojson",
data: "https://netmaker.io/dashboard/public_actions.php?a=ajax_helium_miners_location",
cluster: false,
clusterMaxZoom: 10, // max zoom to cluster points on
clusterRadius: 50, // radius of each cluster when clustering points (defaults to 50)
});
// add 300m circle around each hotspot
map.addLayer({
id: "circle500",
type: "circle",
source: "hotspot_locations",
paint: {
"circle-radius": {
stops: [
[0, 1],
[16, 600],
],
base: 2,
},
"circle-color": "green",
"circle-opacity": 0.1,
"circle-stroke-width": 0,
"circle-stroke-color": "white",
},
});
// add hotspot location
map.addLayer({
id: "hotspots-layer",
type: "circle",
source: "hotspot_locations",
paint: {
"circle-radius": 2,
"circle-stroke-width": 2,
// "circle-color": "#36d293",
"circle-color": "white",
"circle-stroke-color": [
"match",
["get", "status"],
"online",
"#36d293",
"offline",
"#d23636",
"orange", // other
],
// "circle-stroke-color": '#36d293',
},
});
});
// ajax call hotspots location by name
var customData;
$.ajax({
async: false,
type: "GET",
global: false,
dataType: "json",
url: "https://netmaker.io/dashboard/public_actions.php?a=ajax_helium_miners_location_customdata",
success: function (data) {
customData = data;
},
});
// custom data using hotspot name
function forwardGeocoder(query) {
var matchingFeatures = [];
for (var i = 0; i < customData.features.length; i++) {
var feature = customData.features[i];
if (feature.properties.title.toLowerCase().search(query.toLowerCase()) !== -1) {
// feature["place_name"] = '<img src="https://netmaker.io/dashboard/images/helium_logo.svg" alt="" width="15px"> ' + feature.properties.title;
feature["place_name"] = feature.properties.title;
feature["center"] = feature.geometry.coordinates;
feature["place_type"] = ["hotspot"];
matchingFeatures.push(feature);
}
}
return matchingFeatures;
}
// add the control to the map.
map.addControl(
new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
localGeocoder: forwardGeocoder,
zoom: 14,
placeholder: "Search: address or hotspot name",
mapboxgl: mapboxgl,
})
);
map.on("click", "hotspots-layer", function (e) {
var coordinates = e.features[0].geometry.coordinates.slice();
var description = e.features[0].properties.description;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new mapboxgl.Popup().setLngLat(coordinates).setHTML(description).addTo(map);
});
map.on("mouseenter", "hotspots-layer", function () {
map.getCanvas().style.cursor = "pointer";
});
map.on("mouseleave", "hotspots-layer", function () {
map.getCanvas().style.cursor = "";
});
</script>
You're recieving an undefined because e.features[0].properties.description doesn't exist in the "hotspots-layer" data.
"features": [
{
"type": "Feature",
"properties": {
"status": "online"
},
"geometry": {
"type": "Point",
"coordinates": [
"119.73479929772",
"30.240836896893",
0
]
}
},
The only "description" in this case that you can return is the e.features[0].properties.status as seen here:
map.on("click", "hotspots-layer", function (e) {
var coordinates = e.features[0].geometry.coordinates.slice();
var description = e.features[0].properties.status;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
console.log(description)
new mapboxgl.Popup().setLngLat(coordinates).setHTML(description).addTo(map);
});
This code snippet will allow the click event to show you the status when you interact with the hotspot location.

appcelerator : webview to show graph using HighCharts

I am developing an application which sends data to a webview and it uses highcharts to draw graph . The problem I am facing is I am using same graph to display different data series , so when I am calling the graph for 10th time , it firsts shows the y axis labels of all the previous 9 graphs , then the graph is loaded with labels of 10th graph . Any help .
<html>
<head>
<script src="./jquery.min.jsl"></script>
<script src="./highcharts.jsl"></script>
<script src="./exporting.jsl"></script>
<meta name="viewport" content="user-scalable=no">
<script>
function renderGraph(graphdata) {
var graphObj = JSON.parse(graphdata);
var chart = null;
Highcharts.setOptions({
lang : {
numericSymbols : ["K", "M", "G", "T", "P", "E"]
}
});
var change = {
0 : '$0K',
2 : '$2K',
4 : '$4K',
6 : '$6K',
8 : '$8K'
};
var xAxisLegends = graphObj.bottomLegends;
var seriesData = graphObj.seriesData;
var xAxisLegends = graphObj.bottomLegends;
//['Q2, 16', 'Q3, 16', 'Q4, 16', 'Q1, 17'];
var columnColors = ["#69C3DB", "#3a8a9f"];
var seriesData = graphObj.seriesData;
/*[{
name : 'Budget',
showInLegend : false,
data : [2, 4, 6, 8]
}, {
name : 'Utilisation',
showInLegend : false,
data : [1, 2, 3, 4]
}];*/
// variables which have diff values according to OS
var chartProperties = {};
// properties to assign to Charts's object
var graphHeight = 0;
// height of chart
var graphWidth = 0;
//Width of the column
var pointWidth;
// Separating the graph dimensions & styling properties as per OS name & version
if (graphObj.osname == "iphone") {
chartProperties = {
type : 'column',
renderTo : 'container'
};
xAxisProp = {
gridLineWidth : 0,
categories : xAxisLegends,
crosshair : true
};
yAxisProp = {
min : 0,
gridLineWidth : 0,
tickAmount : 5,
title : {
text : ' '
},
labels : {
formatter : function() {
var value = this.axis.defaultLabelFormatter.call(this);
return '$' + value;
}
}
};
pointWidth = 5;
} else if (graphObj.osname == "android") {
chartProperties = {
type : 'column',
plotBackgroundColor : null,
plotBackgroundImage : null,
plotBorderWidth : 0,
plotShadow : false,
height : 450,
marginTop : 100,
marginLeft : 120
},
xAxisProp = {
categories : xAxisLegends,
width : 800,
tickmarkPlacement : 'on',
labels : {
y : 40,
style : {
color : '#333333',
fontSize : '25',
fontFamily : 'Metropolis-Light',
opacity : '.6'
},
}
};
yAxisProp = {
gridLineWidth : 0,
min : 0,
tickAmount : 5,
offset : 60,
title : {
text : ''
},
labels : {
align : 'left',
style : {
color : '#333333',
fontSize : '28',
fontFamily : 'Metropolis-Light',
opacity : '.5'
},
formatter : function() {
var value = this.axis.defaultLabelFormatter.call(this);
return '$' + value;
}
},
};
pointWidth = 10;
if (parseInt(graphObj.osversion) >= 500 && parseInt(graphObj.osversion) <= 600) {
graphHeight = 600;
} else {
graphHeight = 630;
}
}
chart =
Highcharts.chart('container', {
chart : chartProperties,
credits : {
enabled : false
},
tooltip : {
enabled : false
},
exporting : {
enabled : false
},
title : {
text : ''
},
xAxis : xAxisProp,
yAxis : yAxisProp,
plotOptions : {
column : {
pointPadding : 0.2,
borderWidth : 0,
groupPadding : 0.38,
pointWidth : pointWidth
}
},
colors : columnColors,
series : seriesData
});
}
</script>
</head>
<body>
<div id="container" style="height: 100%; width: 100%; position : center;"></div>
</body>
Here is the function inside the controller which calls the graph using evalJS.
$.webViewPerformanceGraph.url = "/html/Performance.html";
$.webViewPerformanceGraph.addEventListener('load', function() {
$.webViewPerformanceGraph.evalJS("renderGraph('" + JSON.stringify(params) + "');");

Pikaday.js : Uncaught RangeError: Maximum call stack size exceeded

I created a simple app which have table and chart with date filters. There's 4 choices. Today, Yesterday, This Month, and Last Month, and one Submit button. It's working perfectly when page load. The table show list all of model and the chart show data what I want expected, perfect.
When I choosed a choice (for example : This Month) and click submit for first time, table and chart is refreshing, perfect.
But when I choosed for second time, It's give me error, and page is freeze
pikaday.js:70 Uncaught RangeError: Maximum call stack size exceeded.
Here's my part code
chartView.on("form:filter", function(data){
var criterion = data
filteredData.filter(criterion)
data1 = filteredData.filter(criterion)
chartView.trigger("view:render");
})
Here's full part code
programming.module("Program.Chart",function(Chart, programming, Backbone, Marionette, $, _){
Chart.Controller = {
getData : function(){
var data1 = programming.request("data:entities");
if(data1 !== undefined){
var filteredData = programming.Program.FilteredCollection({
collection : data1,
filterFunction : function(criterion){
return function(data){
var dateModel = moment(data.get("tanggal"),'DD/MM/YYYY');
var startDate = moment(criterion.date1,'DD/MM/YYYY')
var endDate = moment(criterion.date2,'DD/MM/YYYY')
if(dateModel.isSameOrAfter(startDate)){
if(dateModel.isSameOrBefore(endDate)){
return data
}
}
}
}
})
chartView = new Chart.chartV({
collection: filteredData
})
chartView.on("form:filter", function(data){
var criterion = data
filteredData.filter(criterion)
data1 = filteredData.filter(criterion)
chartView.trigger("view:render");
})
chartView.on("view:render", function(){
//DatePicker
var format = "DD/MM/YYYY"
var date1 = new Pikaday({
field : $("#date1",this.el)[0],
format : format
})
$("#date1",this.el)[0].value = moment().add('days').format(format)
var date2 = new Pikaday({
field : $("#date2",this.el)[0],
format : format
})
$("#date2",this.el)[0].value = moment().add('days').format(format)
var selectdate = $('#publicdate',this.el)[0];
selectdate.addEventListener("change",function(){
var value = selectdate.value;
var date1 = $('#date1',this.el)[0];
var date2 = $('#date2',this.el)[0];
if(value==="today"){
date1.value = moment().add('days').format(format)
date2.value = moment().add('days').format(format)
$(date1).attr('disabled',true);
$(date2).attr('disabled',true);
} else if(value==="yesterday"){
date1.value = moment().add(-1,'days').format(format)
date2.value = moment().add(-1,'days').format(format)
$(date1).attr('disabled',true);
$(date2).attr('disabled',true);
} else if(value==="thismonth"){
date1.value = moment().add('month').startOf('month').format(format)
date2.value = moment().add('month').endOf('month').format(format)
$(date1).removeAttr('disabled',true);
$(date2).removeAttr('disabled',true);
} else if(value==="lastmonth"){
date1.value = moment().add(-1,'month').startOf('month').format('DD/MM/YYYY')
date2.value = moment().add(-1,'month').endOf('month').format('DD/MM/YYYY')
$(date1).attr('disabled',true);
$(date2).attr('disabled',true);
}
})
//Chartist JS
var labels = data1.models.map(function(model){
return model.get("tanggal");
})
var tshirtv = [];
var casev = [];
var tanggal = [];
var series = data1.models.map(function(model,index){
tanggal[index] = model.get("tanggal");
if(model.get("produk")==="T-Shirt"){
tshirtv[index] = model.get("jumlah");
casev[index] ="0";
} else if(model.get("produk")==="Case"){
casev[index] = model.get("jumlah");
tshirtv[index] ="0";
}
})
tshirtv = tshirtv.filter(()=>true)
casev = casev.filter(()=>true)
var series = [
{
name : "T-shirt",
data : tshirtv
},
{
name : "Case",
data : casev
}
]
//Line Chart
var data = {
labels : labels,
series : series
}
var option = {
showArea : true,
lineSmooth : false,
showPoint : true,
chartPadding : {
bottom:60,
top:60,
},
axisX : {
showGrid:false,
},
axisY : {
onlyInteger : true,
},
plugins : [
Chartist.plugins.ctAxisTitle({
axisX: {
axisClass: 'ct-axis-title',
offset: {
x: 0,
y: 50
},
textAnchor: 'middle'
},
axisY: {
axisTitle: 'Jumlah Penjualan',
axisClass: 'ct-axis-title',
offset: {
x: 0,
y: 0
},
textAnchor: 'middle',
flipTitle: false
}
}),
Chartist.plugins.ctPointLabels({
textAnchor : "middle"
}),
Chartist.plugins.legend()
]
}
//Donut Chart
var data2 = {
labels : ['T-Shirt', 'Case'],
series : [12,23]
}
var option2 = {
chartPadding : {
top : 0,
},
labelInterpolationFnc : function(value,series){
return value + ": " +data2.series[series].value
},
donut:true,
donutWidth : 60,
plugins : [
Chartist.plugins.legend()
]
}
new Chartist.Line($('.statistic',this.el)[0],data,option)
//new Chartist.Pie($('.statistic2',this.el)[0],data2,option2)
})
programming.wrapper.show(chartView)
} else {
chartView = new Chart.notfound()
programming.wrapper.show(chartView)
}
}
}
})

Three.js - include mesh data in code

I have this Three.js code with JSON loader loading mesh from file /models/mountain.json:
var Three = new function () {
this.scene = new THREE.Scene()
this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000)
this.camera.position.set(20, 52, 20);
this.camera.rotation.order = 'YXZ';
this.camera.rotation.y = -Math.PI / 4;
this.camera.rotation.x = Math.atan(-1 / Math.sqrt(2));
this.camera.scale.addScalar(1);
this.renderer = new THREE.WebGLRenderer()
this.renderer.setSize(window.innerWidth, window.innerHeight);
var ground = new THREE.Mesh(
new THREE.PlaneBufferGeometry(436, 624),
new THREE.MeshLambertMaterial({color: '#808080'}));
ground.rotation.x = -Math.PI / 2; //-90 degrees around the x axis
this.scene.add(ground);
var light = new THREE.PointLight(0xFFFFDD);
light.position.set(-1000, 1000, 1000);
this.scene.add(light);
var loader = new THREE.JSONLoader();
this.loadMountain = function (x, y) {
loader.load('/models/mountain.json', Three.getGeomHandler('#808080', x, y, 1))
}
this.loadFields = function () {
for (var i=0;i<4000;i++) {
Three.loadMountain(x, y)
}
}
this.getGeomHandler = function (color, x, y, scale) {
return function (geometry) {
var mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({color: color}));
mesh.scale.set(scale, scale, scale);
mesh.position.set(x, 0, y);
Three.scene.add(mesh);
};
}
this.init = function () {
$('body').append(Three.renderer.domElement);
Three.loadFields()
Three.render();
}
this.render = function () {
requestAnimationFrame(Three.render);
Three.renderer.render(Three.scene, Three.camera);
};
}
$(document).ready(function () {
Three.init();
});
and this is /models/mountain.json content:
{
"metadata": {
"formatVersion" : 3.1,
"generatedBy" : "Blender 2.7 Exporter",
"vertices" : 39,
"faces" : 62,
"normals" : 36,
"colors" : 0,
"uvs" : [],
"materials" : 1,
"morphTargets" : 0,
"bones" : 0
},
"scale" : 1.000000,
"vertices" : [2.47941e-07,-1.13504e-07,-2.59668,-2.41031,-6.2081e-08,-1.42025,-2.2107,4.55942e-08,1.04307,2.16045,1.84802,0.183901,-0.427399,1.11956e-07,2.56126,1.23588,9.98242e-08,2.28371,2.50387,4.55942e-08,1.04307,2.58781,9.37308e-09,0.214431,2.17385,-0.0483214,-1.42025,1.40026,-0.0483214,-1.74566,1.50645e-07,2.13114,-1.9421,-0.6306,2.13114,-1.52968,-1.04238,2.48498,-1.06715,-1.23632,3,-0.856474,-1.5574,2.62306,-0.476759,-1.68478,2.74775,0.160378,-1.20001,3,0.780135,-1.14654,3,1.41015,-0.31966,3,1.91562,0.31966,2.48498,1.46763,0.92434,3,1.70803,0.754272,2.73835,0.751422,1.90443,2.61032,0.780134,1.52632,2.76301,0.160377,1.78144,2.69402,-0.47676,1.9564,3,-1.06223,0.807846,2.13114,-1.68984,1.32727,3.09213,-1.10549,1.13568,1.38919,-1.21096,1.98255,0.969716,-1.07503,0.529022,2.81989,0.43993,0.969891,3.32801,-1.43745,-0.39848,2.2361,-1.12285,-1.00579,1.31316,2.27174,-0.789081,1.31316,2.34614,0.888122,0.684588,2.17543,0.568656,2.07869,1.615,2.13863,1.49103,1.32889,2.52981,0.924307,0.978923],
"faces" : [34,0,11,10,0,0,1,2,34,1,13,12,0,3,4,5,34,0,12,11,0,0,5,1,34,0,1,12,0,0,3,5,34,38,3,37,0,6,7,8,34,9,31,28,0,9,10,11,34,0,10,26,0,0,2,12,34,9,26,31,0,9,12,10,34,9,0,26,0,9,0,12,35,18,17,33,34,0,13,14,15,16,35,37,3,23,22,0,8,7,17,18,34,29,27,25,0,19,20,21,34,28,31,27,0,11,10,20,34,29,28,27,0,19,11,20,34,12,19,20,0,5,22,23,34,5,6,20,0,24,25,23,34,6,38,37,0,25,6,8,34,37,22,21,0,8,18,26,34,30,27,31,0,26,20,10,34,6,37,20,0,25,8,23,34,30,31,32,0,26,10,27,34,37,21,20,0,8,26,23,34,30,32,26,0,26,27,12,34,21,30,20,0,26,26,23,34,11,12,20,0,1,5,23,34,26,10,11,0,12,2,1,34,30,11,20,0,26,1,23,34,30,26,11,0,26,12,1,34,20,35,5,0,23,28,24,34,20,19,36,0,23,22,28,34,20,36,35,0,23,28,28,35,6,7,3,38,0,25,29,7,6,34,7,23,3,0,29,17,7,34,29,25,24,0,19,21,30,34,7,24,23,0,29,30,17,34,7,8,29,0,29,31,19,34,7,29,24,0,29,19,30,34,18,36,19,0,13,28,22,34,4,5,35,0,32,24,28,34,18,35,36,0,13,28,28,34,18,34,4,0,13,16,32,34,18,4,35,0,13,32,28,35,13,14,15,16,0,4,33,33,34,34,30,25,27,0,26,21,20,34,23,24,25,0,17,30,21,34,21,22,23,0,26,18,17,34,30,21,25,0,26,26,21,34,21,23,25,0,26,17,21,35,8,9,28,29,0,31,9,11,19,34,26,32,31,0,12,27,10,34,2,16,15,0,35,34,33,34,14,13,1,0,33,4,3,34,14,2,15,0,33,35,33,34,14,1,2,0,33,3,35,34,2,17,16,0,35,14,34,34,4,34,33,0,32,16,15,34,2,33,17,0,35,15,14,34,2,4,33,0,35,32,15,34,16,12,13,0,34,5,4,34,18,19,12,0,13,22,5,34,16,17,18,0,34,14,13,34,16,18,12,0,34,13,5],
"uvs" : [],
"normals" : [0.094028,0.298624,-0.949705,-0.162755,0.939238,-0.302133,0.228248,0.832942,-0.504044,-0.822016,0.351848,-0.447707,-0.253456,0.911466,-0.323923,-0.004059,0.913785,-0.40614,0.788598,0.576983,0.21247,0.952086,0.29432,-0.082797,0.625996,0.719138,0.301553,0.474441,0.29017,-0.83105,0.255501,0.796655,-0.547746,0.441328,0.166265,-0.881802,0.221656,0.483047,-0.847041,0.192999,0.761406,0.618824,-0.352977,0.778008,0.5197,-0.653584,0.252663,0.713401,-0.29136,0.293313,0.91052,0.688314,0.722556,0.063967,0.612629,0.761834,0.210364,0.718711,0.280313,-0.63625,0.370495,0.893033,-0.255287,0.629627,0.578692,-0.518326,0.229896,0.680258,0.695944,-0.064241,0.589251,0.805353,0.205145,0.606586,0.768059,0.734519,0.631458,0.24839,0.211341,0.910367,0.355693,-0.135533,0.925748,-0.352916,-0.03061,0.231269,0.972381,0.975982,0.184362,-0.11594,0.694266,0.717338,0.058412,0.712027,0.350871,-0.608173,-0.201483,0.259865,0.944365,-0.820185,0.572069,-0.001556,-0.322733,0.944334,0.063509,-0.922117,0.223151,0.315958],
"skinIndices" : [],
"skinWeights" : [],
"morphTargets" : [],
"bones" : [],
"animations" : [],
"colors" : [],
"materials" : [
{
"DbgColor": 15658734,
"DbgIndex": 0,
"DbgName": "default",
"vertexColors": false
}
]
}
Is it possible to use this content in code as a variable and add it to scane?
Here is the pattern to follow if you want to load a model by parsing a JSON data structure.
Modify your mountain.json file and give your data structure a name.
var mountain = {
"metadata": {
"formatVersion" : 3.1,
"generatedBy" : "Blender 2.7 Exporter",
... etc ...
}
Include the following code in your source:
<script src="mountain.js"></script>
Now you can load your model like so:
var loader = new THREE.JSONLoader();
var model = loader.parse( mountain );
mesh = new THREE.Mesh( model.geometry, model.materials[ 0 ] );
scene.add( mesh );
three.js r.70

Creating Markers from my JSON file

I am creating a map with markers from a json file, my issue is that I am unable to get the markers to show on the map. I can link a basic json file, but when I try with an array file I get no markers. My code is:
<script src="js/mapping.js"></script>
<script type="text/javascript">
(function () {
window.onload = function () {
// Creating a new map
var map = new google.maps.Map(document.getElementById("map"), {
center : new google.maps.LatLng(51.50746, -0.127594),
zoom : 8,
mapTypeId : google.maps.MapTypeId.ROADMAP
});
// Creating a global infoBox object that will be reused by all markers
infoBubble = new InfoBubble({
minWidth: 300,
maxWidth: 400,
minHeight: 300,
maxHeight: 400,
arrowSize: 50,
arrowPosition: 50,
arrowStyle: 2,
borderRadius: 0,
shadowStyle: 1,
}); // end Creating a global infoBox object
// Creating a global infoBox object tabs
infoBubble.addTab('Details');
infoBubble.addTab('Info');
// end Creating a global infoBox object tabs
// Custom Markers
var markers = {};
var categoryIcons = {
1 : "images/liver_marker1.png",
2 : "images/liver_marker2.png",
3 : "images/liver_marker3.png",
4 : "images/liver_marker4.png",
5 : "images/liver_marker.png",
6 : "images/liver_marker6.png",
7 : "images/liver_marker.png"
} // end Custom Markers
// Looping through the JSON data
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position : latLng,
map : map,
title : data.title,
icon : categoryIcons[data.category]
});
// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
(function (marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, 'click', function(e) {
//infoBubble.setContent('<b>'+data.description+'</b>'+'<br>'+data.name);
infoBubble.updateTab(0, 'Details', data.deviceOwnerName);
infoBubble.updateTab(1, 'Info', data.name);
infoBubble.open(map, marker);
map.panTo(loc);
}); // end Attaching a click event to the current marker
})(marker, data); // end Creating a closure
} // end Looping through the JSON data
}
})();
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And my json array file is:
{
"Device" : [{
"DeviceId" : "e889",
"DeviceRef" : "Te889",
"DeviceName" : null,
"DeviceText" : "Operated by SE",
"DeviceLocation" : {
"Latitude" : "51.484804",
"Longitude" : "-0.103226",
"Address" : {
"SubBuildingName" : null,
"BuildingName" : null,
"BuildingNumber" : null,
"Thoroughfare" : null,
"Street" : "Volcan Road North",
"DoubleDependantLocality" : null,
"DependantLocality" : null,
"PostTown" : "Norwich",
"PostCode" : "NR6 6AQ",
"Country" : "gb"
},
"LocationShortDescription" : null,
"LocationLongDescription" : null
},
"Connector" : [{
"ConnectorId" : "JEV01",
"ConnectorType" : "JEVS G 105 (CHAdeMO)",
"RatedOutputkW" : "50.00",
"RatedOutputVoltage" : null,
"RatedOutputCurrent" : null,
"ChargeMethod" : "DC",
"ChargeMode" : "1",
"ChargePointStatus" : "In service",
"TetheredCable" : "0",
"Information" : null
}
],
"Controller" : {
"OrganisationName" : "SE",
"Website" : null,
"TelephoneNo" : null,
"ContactName" : null
},
"DeviceOwner" : {
"OrganisationName" : "Unknown",
"Website" : null,
"TelephoneNo" : null,
"ContactName" : null
},
"DeviceAccess" : {
"RegularOpenings" : [{
"Days" : "Monday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Tuesday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Wednesday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Thursday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Friday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Saturday",
"Hours" : {
"From" : "08:30",
"To" : "05:00"
}
}
],
"Open24Hours" : true
},
"PaymentRequiredFlag" : false,
"SubscriptionRequiredFlag" : true,
"Accessible24Hours" : false,
"PhysicalRestrictionFlag" : false,
"PhysicalRestrictionText" : null,
"OnStreetFlag" : false,
"Bearing" : null
}
]}
I am trying to link to the Latitude and Longitude, but I am also looking to display the DeviceId.
Any help would be appreciated.
R
Latitude and Longitude are nested members within your JSON file. You cannot access them without first delving into the DeviceLocation member. I recommend you read this article (http://www.w3schools.com/json/) to understand how JSON works.

Categories

Resources