create var from local geojson file mapbox/leaflet - javascript

I want to create a var myGeojson in an html file that uses the data in a separate locally stored .geojson or .js file. I can do this by creating a var in the .geojson file, which can be used in the html file. However I need to use multiple large unaltered geojson files, Is there a way to create the var in the html but store the data in the geojson?
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
<script src='data/example.geojson'></script>
</head>
<body>
<div id='map'></div>
<script>
L.mapbox.accessToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
L.mapbox.map('map', 'examples.map-xxxxxxxx')
.setView([37.8, -96], 4)
.featureLayer.setGeoJSON(myGeojson);
</script>
</body>
</html>
data/example.geojson
var myGeojson =
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [125.6, 10.1]
},
"properties": {
"name": "Dinagat Islands"
}
}

What about using the XHR functionality already included in L.mapbox.featureLayer?
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.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>
L.mapbox.accessToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var map = L.mapbox.map('map', 'examples.map-xxxxxxxx').setView([37.8, -96], 4);
var layer1 = L.mapbox.featureLayer('data.geo.json').addTo(map);
// You could add as much layers as you want
// var layer2 = L.mapbox.featureLayer('moredata.geo.json').addTo(map);
// Or you could load new data into an existing layer:
//layer1.loadURL('newdata.geo.json');
</script>
</body>
</html>
data.geo.json:
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [125.6, 10.1]
},
"properties": {
"name": "Dinagat Islands"
}
}
Here's a working example on Plunker: http://plnkr.co/edit/jAkQ7v9XVIDCDnQQzpWK?p=preview
But as said in the comments, if you're really adament on taking an extra (in my eyes unnecessary) step then you can use a XHR library of choice and fetch the file and assign it to a variable (using jQuery's $.getJSON here):
// Empty featureLayer
var featureLayer = L.mapbox.featureLayer().addTo(map);
// Variable for your data
var geojsonData;
// Fetch the file
$.getJSON('data.geo.json', function (results) {
// Assign the results to the geojsonData variable
geojsonData = results;
// Assign the data to the layer
featureLayer.setGeoJSON(geojsonData);
});
Here's a working example on Plunker: http://plnkr.co/edit/ayYgF5fi1MKgTRBg3YAt?p=preview
But i don't see why you want to pull in another dependency like jQuery if featureLayer itself has the complete XHR functionality you need. But ok :)

Related

Leaflet map not displaying external GeoJSON data

Leaflet Map not Visible ....
What I am trying to do is creating a map and add external GeoJSON file I already created through QGIS app using SPH file from http://naturalearthdata.com
somehow my map is not visible there i also tried to use mapbox and google API key with leaflet library and sill having same issue
anyone knows the solution ??
I couldn't add my GeoJSON file in here because it's a huge file
Here is my HTML file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="biewport" content="width=device-width, initial-scale=1" />
<title>GeoJSON</title>
<!-- leflet links -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.3.3/dist/leaflet.js"></script>
</head>
<body>
<div id="map"></div>
<!-- <script src="CA_Bulletin_118_Groundwater_Basins.geojson"></script> -->
<script src="test.geojson"></script>
<!-- script file -->
<script src="js/script.js"></script>
</body>
</html>
My script.js file:
//creating a new map
var map = new L.Map('map').setView([51.505, -0.09], 13);
//create a new Geojason layer and set it up to basins var ....
// var test;
var test = L.tileLayer('basins');
var basinslayer = L.geoJson(basins).addTo(map);
And here is my CSS file:
/*General CSS */
html, body, #map {
height: 100%;
width: 100%;
font-family: sans-serif;
}
#map {
width: 50%;
height: 50%;
}
I'm also importing a geojson file to generate the points on my map. I used the $.getJSON from jquery to import the geojson file, load the data, and create the points.
If you want to try this method, you have to add jQuery in the head of your html, like this (also found here for the latest cdn):
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
My $.getJSON looks like this:
var getjson = $.getJSON("map-v2.geojson",function(data){
var bev = L.geoJson(data,{
pointToLayer: function(feature,latlng){
var marker = L.marker(latlng);
marker.bindPopup('<p align=center>' + '<strong>Title: </strong>' + feature.properties.Title + '<strong>Date: </strong>' + feature.properties.Date + '<br/>' + '<strong>Creator: </strong>' + feature.properties.Creator);
return marker;
}
});
bev.addTo(map);
});
First, I set a variable that calls $.getJSON, which takes a few arguments, the first one is the name of the geoJSON file in quotes, and the second is function(data) which acts to say we are going to use the data found in this file. The second line I assign my variable bev to invoke the L.geoJson function, passing the argument data (which will use the data from the geoJSON file). Then I point to a new layer using pointToLayer and assigning it the value of the function(feature,latlng). feature allows me to name certain properties from my geoJSON file to display in the popups, latlng extracts the coordinates from the geoJSON file to generate the locations for the markers(latlng is mandatory). I then assign another variable called marker, and here's where you generate your markers on your map, simply by using L.marker(latlng). After that, the marker.bindPopup binds all the content I want to display on popups from the properties data I have in each of my points in the geoJson file. Here's an example of my geoJSON:
{
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-122.714055,
38.440429
]
},
"properties": {
"Title": "Santa Rosa. Sonoma County. California. 1885.",
"Date": "1885",
"Creator": "W.W. Elliot & Co., lithographer."
}
},
I then return the marker, add the variable bev to the map, and there they are!
*I'm not an expert on JavaScript or Leaflet, so if my wording is off, I will gladly make edits to make it clearer.

canvasjs live updating data from database

I am new to web based visualization tool I used chartjs before but I did not find any solution for chartjs so, I transferred to canvasjs.Now I'm done creating the chart and it is successfully shown, thus I want to make it moving without refreshing because the data from the database is constantly moving. Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
window.onload = function () {
$.getJSON("json.php", function(result){
var dps= [];
//Insert Array Assignment function here
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
}
//Insert Chart-making function here
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled:true,
panEnabled:true,
animationEnabled:true,
title:{
text: "myChart from mySQL database"
},
axisX:{
title: "TimeStamp"
},
axisY:{
title: "myDataPoints",
minimum: 0
},
data: [{
type: "spline",
dataPoints:
dps
}]
});
chart.render();
});
}
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
now, I would like to ask for help out there What do I need to keep this chart moving...??
If you want the lines to move, you need to remove dataPoints from the beginning of the array. You can do so using shift function in JS.
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
dps.shift();
}
This would do the trick for you.

Changing src attribute in video tag with json data

I'm trying to make a video player with HTML and JavaScript that will play a series of videos, one after another, until all 6 have been played. The URLs for the videos are stored in an array and map in a .json file called clips.json.
The data in the file is below:
[
{
"id":"ashklasd132asddfgdf",
"name": "War on Drugs continues",
"description":"Losses continue in agressive raid on local property",
"content-url": "http://buffalogrove.sat.iit.edu/Kitty.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/dogs_friends-t2.jpg"
},
{
"id":"asdasd132asddf667jf",
"name": "Parlimentary Proceedings",
"description":"World Leaders meet to determine the latest policies on climate change relief",
"content-url": "http://buffalogrove.sat.iit.edu/Clouds%2038%20Timelapse.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/colorful_clouds-t2.jpg"
},
{
"id":"123dfg6132asddfgdz",
"name": "Weather for March 22nd 2015",
"description":"Join Jeremy Brown for today's weather",
"content-url": "http://buffalogrove.sat.iit.edu/Clouds-Time_lapse_22.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/hidden_lagoon-t2.jpg"
},
{
"id":"pzxc87asdkjl44h7h",
"name": "Taking a walk on the wide-side",
"description":"Cook Counties latest conservation efforts led to a new discovery",
"content-url": "http://buffalogrove.sat.iit.edu/Flower_4.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/nature_scenes_3-t2.jpg"
},
{
"id":"mkiaasdsjdh7asd8889",
"name": "Musical Stunner",
"description":"Local musician proves nay-sayers wrong by providing ample range",
"content-url": "http://buffalogrove.sat.iit.edu/Piano_keys.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/turkey_karadeniz_region-t2.jpg"
},
{
"id":"zklsjdpoiqwehbhfyvfy6h",
"name": "H-Diddy Represent",
"description":"The newest Album from H-Diddy",
"content-url": "http://buffalogrove.sat.iit.edu/Pigeon.mp4",
"thumb-url":"http://buffalogrove.sat.iit.edu/thumb/nanxiang_ancient_town_shanghai_china-t2.jpg"
},
]
I'm having trouble changing the src attribute after the video from the URL is finished. After the video plays the first video, it stops, and doesn't go on to the 2nd one. I don't know if it's because I'm calling the JSON data wrong with my AJAX get request or something else, but if someone could help me solve this issue, I'd greatly appreciate it.
My HTML code with embedded JavaScript is below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>IIT News</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<style>
.starter-template {
padding: 40px 15px;
text-align: center;
}
</style>
<script type="text/javascript" src="/myJS.js" language="javascript"> </script>
</head>
<body onload="loadFunction()">
<div class="container">
<div class="hook">
<video onended="playNext()" width="640" height="480" id="myVideo" controls autoplay>
<!--<source src="parsedData[0].['content-url'][conUrlCount]" type="video/mp4"></source>-->
<source src="http://buffalogrove.sat.iit.edu/Kitty.mp4" type="video/mp4"></source>
</video>
</div><!-- /.hook -->
</div><!-- /.container-->
</body>
</html>
myJS.js is below
var conUrlCount = 0;
var myVideo = document.getElementById("myVideo");
//parsedData should be declared outside the function scope since we want it to be accessible from outside
var parsedData;
var callback = function (text) {
//parsedData = JSON.stringify(JSON.parse(text));
parsedData = JSON.parse(text);
conUrlCount = 0;
//after load play the first video
playNext();
};
//when page is loaded, data in json file is parsed and returned
function loadFunction() {
//returning json data
ajax.get("clips.json", callback);
};
function playNext() {
if (!parsedData) {
return
}
var myVideo = document.getElementById("myVideo");
myVideo.src = parsedData[conUrlCount]['content-url'];
myVideo.play();
conUrlCount++;
};
One problem is the json object is a local variable to the callback method, make it a global one
<video onended="playNext()" width="640" height="480" id="myVideo" controls
autoplay>
then
var conUrlCount = 0;
var myVideo = document.getElementById("myVideo");
//parsedData should be declared outside the function scope since we want it to be accessible from outside
var parsedData;
var callback = function (text) {
parsedData = JSON.parse(text);
conUrlCount = 0;
//after load play the first video
playNext();
};
//when page is loaded, data in json file is parsed and returned
function loadFunction() {
//returning json data
ajax.get("clips.json", callback);
};
function playNext() {
if (!parsedData) {
return
}
var myVideo = document.getElementById("myVideo");
myVideo.src = parsedData[conUrlCount]['content-url'];
myVideo.play();
conUrlCount++;
}
Demo: Fiddle

Trouble with Google charts getting this.J[a].c is undefined

I'm VERY new to google charts and I cant seem to find the problem in my code:
My php file returns:
{"cols":[{"id":"","label":"Time","type":"string"},{"id":"","label":"Max","type":"number"},{"id":"","label":"Average","type":"number"}],"rows":[[{"c":[{"v":"2013-11-19
14:38:00"},{"v":2576},{"v":2144}]},{"c":[{"v":"2013-11-19
14:39:00"},{"v":1960},{"v":1682}]},{"c":[{"v":"2013-11-19
14:40:00"},{"v":1789},{"v":1565}]},{"c":[{"v":"2013-11-19
14:41:00"},{"v":1995},{"v":1654}]},{"c":[{"v":"2013-11-19
14:42:00"},{"v":14647},{"v":11638}]},{"c":[{"v":"2013-11-19
14:43:00"},{"v":7512},{"v":5202}]},{"c":[{"v":"2013-11-19
14:44:00"},{"v":2056},{"v":1681}]},{"c":[{"v":"2013-11-19
14:45:00"},{"v":1874},{"v":1524}]},{"c":[{"v":"2013-11-19
14:46:00"},{"v":1706},{"v":1385}]},{"c":[{"v":"2013-11-19
14:47:00"},{"v":2244},{"v":1667}]},{"c":[{"v":"2013-11-19
14:48:00"},{"v":16198},{"v":13145}]},{"c":[{"v":"2013-11-19
14:49:00"},{"v":17549},{"v":13886}]},{"c":[{"v":"2013-11-19
14:50:00"},{"v":1824},{"v":1513}]},{"c":[{"v":"2013-11-19
14:51:00"},{"v":2299},{"v":1762}]},{"c":[{"v":"2013-11-19
14:52:00"},{"v":20273},{"v":13167}]},{"c":[{"v":"2013-11-19
14:53:00"},{"v":3024},{"v":2231}]},{"c":[{"v":"2013-11-19
14:54:00"},{"v":14386},{"v":10450}]},{"c":[{"v":"2013-11-19
14:55:00"},{"v":16368},{"v":13741}]},{"c":[{"v":"2013-11-19
14:56:00"},{"v":4528},{"v":2717}]},{"c":[{"v":"2013-11-19
14:57:00"},{"v":3655},{"v":2601}]},{"c":[{"v":"2013-11-19
14:58:00"},{"v":3456},{"v":2624}]},{"c":[{"v":"2013-11-19
14:59:00"},{"v":4818},{"v":2917}]}]]}
I would like to draw a graph that plots time on x and then two lines with MAX and AVERAGE values.
I believe the issue Lies somewhere in my HTML/JAVASCRIPT code.
<html>
<head>
<title>Dashboard</title><meta name=keywords /><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script type="text/javascript" src="https://www.google.com/jsapi"></script><meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<!---->
<style type="text/css">
body { background-color: #ffffff; padding-left: 1%; padding-bottom: 100px; }
footer{font-size:small;position:fixed;right:5px;bottom:5px;}
</style>
<style>h1 {color:white; font-size:24pt; text-align:center;font-family:arial,sans-serif }.menu {color:white; font-size:12pt; text-align:center;font-family:arial,sans-serif; font-weight:bold }table2 {background:black }p {color:black; font-size:12pt; text-align:justify;font-family:arial,sans-serif }p.foot {color:white; font-size:9pt; text-align:center;font-family:arial,sans-serif; font-weight:bold }a:link, a:visited, a:active {color:white}
</style>
</head>
<body>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load("visualization", "1", {"packages":["corechart"]});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url: "get_sql_data.php",
dataType: "json",
success: function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById("chart_div"));
chart.draw(data, {width: 400, height: 240});
}
});
}
</script>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div><table width=100% bgcolor=black cellpaddin g=0 border=0>
</body>
It seems that your json data are in bad format. cols are ok:
{
"cols":
[
{
"id":"", "label":"Time",
"type":"string"
},
rows have one extra pair [ ... ] which should be removed:
"rows":
[
[
{
"c":[
{"v":"2013-11-19 14:38:00"},
{"v":2576},
{"v":2144}
]
},
To get
"rows":
[
{
"c":[
{"v":"2013-11-19 14:38:00"},
{"v":2576},
{"v":2144}
]
},
See also Google line chart visualization with JSON blob.

Showing each step geocode of directions

Google Maps API can build a Direction from a source to a destination. In the following Google's example, each step are published into the HTML code: http://code.google.com/apis/maps/documentation/examples/directions-simple.html
I would like to get the Geocoding of each step of this direction, and store them in a array. I believe it's possible, but I don't see how to process.
Many Thanks for any answer.
Regards
Yes, you can get the individual steps from GDirections very easily.
First you have to make sure to pass the getSteps: true option when you call the GDirections.load() method. Then you can simply iterate through GDirections.getRoute(i).getStep(j), as in the following example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Simple Directions Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map" style="width: 550px; height: 400px"></div>
<script type="text/javascript">
var map = new GMap2(document.getElementById("map"));
var directions = new GDirections(map);
directions.load('from: London, UK to: Glasgow, UK', { getSteps: true });
GEvent.addListener(directions, "load", function() {
if (directions.getNumRoutes() > 0) {
for (var i = 0; i < directions.getRoute(0).getNumSteps(); i++) {
directions.getRoute(0).getStep(i).getLatLng().lat();
directions.getRoute(0).getStep(i).getLatLng().lng();
directions.getRoute(0).getStep(i).getDescriptionHtml();
directions.getRoute(0).getStep(i).getPolylineIndex();
directions.getRoute(0).getStep(i).getDistance().meters;
directions.getRoute(0).getStep(i).getDuration().seconds;
}
}
});
</script>
</body>
</html>
Further reading and reference:
GDirections
GRoute
GStep

Categories

Resources