Leaflet - map layers not loading - leaflet

I am trying to create a choropleth that shades states depending on the rate of cases in 2010. I am getting the error: Uncaught TypeError: Cannot read property 'features' of null at Object.t.choropleth.n.exports [as choropleth]. Is this a problem with reading and extracting the data from the geojson?
var myMap = L.map('map', {
center: [39.8283, -98.5795],
zoom: 11
});
APIKEY = "pk.eyJ1Ijoic2NvdHRtY2FsaXN0ZXIxMyIsImEiOiJjamlhdWd2bzMxYjU1M3Ztcm54N2kxaDQ2In0.mGtR6lttrtiEpIqHVEIAtQ"
L.tileLayer("https://api.mapbox.com/styles/v1/mapbox/outdoors-v10/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic2NvdHRtY2FsaXN0ZXIxMyIsImEiOiJjamlhdWd2bzMxYjU1M3Ztcm54N2kxaDQ2In0.mGtR6lttrtiEpIqHVEIAtQ").addTo(myMap)
var GEOLINK = "state_data_modified.geojson";
var geojson_0;
d3.json(GEOLINK, function(data){
geojson_0=L.choropleth(data, {
valueProperty: "Rate_2010",
scale: ['white', 'red'],
steps: 5,
mode: "q",
style:{
color:'#fff',
weight: 1,
fillOpacity: .8
},
onEachFeature: function(feature, layer){
layer.bindPopup(feature.properties.State + "<br>Number of cases:<br>" + feature.properties.Cases_2010)
}
}).addTo(myMap);
var legend = L.control({ position: "bottomright" });
legend.onAdd = function() {
var div = L.DomUtil.create("div", "info legend");
var limits = geojson.options.limits;
var colors = geojson.options.colors;
var labels = [];
// Add min & max
var legendInfo = "<h1>Cases and Rates</h1>" +
"<div class=\"labels\">" +
"<div class=\"min\">" + limits[0] + "</div>" +
"<div class=\"max\">" + limits[limits.length - 1] + "</div>" +
"</div>";
div.innerHTML = legendInfo;
limits.forEach(function(limit, index) {
labels.push("<li style=\"background-color: " + colors[index] + "\"></li>");
});
div.innerHTML += "<ul>" + labels.join("") + "</ul>";
return div;
};
legend.addTo(myMap);
});
body {
padding: 0;
margin: 0;
}
#map,
body,
html {
height: 100%;
}
.leaflet-popup-content {
text-align: center;
}
/* CSS from the Leaflet-Choropleth documentation */
.legend {
padding: 6px 8px;
font: 12px Arial, Helvetica, sans-serif;
font-weight: bold;
color: #555;
background: #fff;
background: rgba(255, 255, 255, 0.8);
border-radius: 5px;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
}
.legend ul {
padding: 0;
margin: 0;
clear: both;
list-style-type: none;
}
.legend li {
display: inline-block;
width: 30px;
height: 22px;
}
.legend .min {
float: left;
padding-bottom: 5px;
}
.legend .max {
float: right;
}
h1 {
text-align: center;
}
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Test Choropleth</title>
<!-- Leaflet CSS & JS-->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.2/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.0.2/dist/leaflet.js"></script>
<!-- d3 JavaScript -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<!-- Leaflet-Choropleth JavaScript -->
<script type="text/javascript" src="choropleth.js"></script>
<!-- Our CSS -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- The div where we will inject our map -->
<div id="map"></div>
<script type="text/javascript" src="test_choro.js"></script>
</body>
</html>
picture of tilelayer and console

For me the error seem pretty clear.
You are loading your geojson from local storage: file:///Users...
This is not possible. You have to make it accessible from an url if you have a server (apache, nginx) or use github to get a raw file url.
You can also use this function:
$.getJSON("your_path/to/state_data.json", function(json) {
console.log(json);
});

Related

How to get Leaflet Easy Button (plugin) buttons to display on map?

I am new to Leaflet and JavaScript. I am trying to create a web map that will have 3-4 buttons that when clicked will zoom the user to the given location. Ex: Disney World (28.385384005128767, -81.56313371302178), Black Pool Pleasure Beach (53.937909193096296, -3.0415772052368952).
So far, I have been trying code from a tutorial, but cannot get the buttons to show on my map. What am I doing wrong?
.full {
padding: 0;
margin: 0;
}
.full html, body, #map {
height: 100%;
width: 100vw;
}
.center {
text-align: center;
}
html, body, #map {
height: 100%;
width: 100vw;
}
#map{ width: 100%; height: 100%; }
iframe{
align-content: center;
width: 98%; height: 97%;
}
.leaflet-bar button,
.leaflet-bar button:hover {
background-color: #fff;
border: none;
border-bottom: 1px solid #ccc;
width: 26px;
height: 26px;
line-height: 26px;
display: block;
text-align: center;
text-decoration: none;
color: black;
}
.leaflet-bar button {
background-position: 50% 50%;
background-repeat: no-repeat;
overflow: hidden;
display: block;
}
.leaflet-bar button:hover {
background-color: #f4f4f4;
}
.leaflet-bar button:first-of-type {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.leaflet-bar button:last-of-type {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-bottom: none;
}
.leaflet-bar.disabled,
.leaflet-bar button.disabled {
cursor: default;
pointer-events: none;
opacity: .4;
}
.easy-button-button .button-state{
display: block;
width: 100%;
height: 100%;
position: relative;
}
.leaflet-touch .leaflet-bar button {
width: 30px;
height: 30px;
line-height: 30px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Map</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.0.3/dist/leaflet.js"></script>
<link rel="stylesheet" href="Leaflet.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet-easybutton#2/src/easy-button.css">
<script src="https://cdn.jsdelivr.net/npm/leaflet-easybutton#2/src/easy-button.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body id ="full" class= "full">
<div id = "text">
</div>
<div id="map"></div>
<script>
var map = L.map('map',{ center: [42.353770, -71.10360608], zoom: 16, keyboard: true});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap' }).addTo(map);
var Esri_WorldImagery = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
}).addTo(map);
var OSM = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap' }).addTo(map);
var mapChoices = {
"Satellite": Esri_WorldImagery,
"OSM": OSM
}
L.control.layers(mapChoices).addTo(map);
</script>
<script>
var map = L.map('map', {scrollWheelZoom: false}).setView([37.8, -96], 4);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(zoomTo);
L.easyButton( 'fa-gbp', function(){
map.setView([55, -2], 4);
}).addTo(map);
L.easyButton( 'fa-jpy', function(){
map.setView([38, 139], 4);
}).addTo(map);
L.easyButton( 'fa-usd', function(){
map.setView([37.8, -96], 3);
}).addTo(map);
</script>
</body>
</html>
Simply do not re-instantiate your map and do not re-assign your map variable.
You can merge your 2 <script> tags together, it should become more obvious to you what the issue is.
Your 2nd map instantiation should throw an error in your browser Devtools console (if you are not using it, make sure to learn how to open it)
After that the rest of your script is ignored.

How to make a marker with a custom image draggable in MapboxGL?

There's an example of how to make a point draggable (which has a layer) and there's an example of how to setup a marker with a custom image, but how would I make that custom image draggable on the map when it doesn't have a layer associated with it?!
i came up with this from some another example i found, and mixed the two. It worked for what i wanted... I remember seeing this while looking for answers (a few times) so i came back to share.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Add custom icons with Markers</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.51.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
#marker6060 {
background-image: url('https://placekitten.com/g/60/60/');
background-size: cover;
width: 60px;
height: 60px;
border-radius: 50%;
cursor: pointer;
}
#marker5050 {
background-image: url('https://placekitten.com/g/50/50/');
background-size: cover;
width: 50px;
height: 50px;
border-radius: 50%;
cursor: pointer;
}
#marker4040 {
background-image: url('https://placekitten.com/g/40/40/');
background-size: cover;
width: 40px;
height: 40px;
border-radius: 50%;
cursor: pointer;
}
</style>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'YOURS, NOT MINE.';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-65.017, -16.457],
zoom: 5
});
var element6060 = document.createElement('div');
element6060.id = 'marker6060';
var marker6060 = new mapboxgl.Marker({
element: element6060,
draggable: true,
color: '#000000'
})
.setLngLat([-66.324462890625, -16.024695711685304])
.addTo(map);
element6060.addEventListener('click', function() {
var message = 'Kitty 6060';
window.alert(message);
});
var element5050 = document.createElement('div');
element5050.id = 'marker5050';
var marker5050 = new mapboxgl.Marker({
element: element5050,
draggable: true,
color: '#000000'
})
.setLngLat([-61.2158203125, -15.97189158092897])
.addTo(map);
element5050.addEventListener('click', function() {
var message = 'Kitty 5050';
window.alert(message);
});
var element4040 = document.createElement('div');
element4040.id = 'marker4040';
var marker4040 = new mapboxgl.Marker({
element: element4040,
draggable: true,
color: '#000000'
})
.setLngLat([-63.29223632812499, -18.28151823530889])
.addTo(map);
element4040.addEventListener('click', function() {
var message = 'Kitty 4040';
window.alert(message);
});
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Add custom icons with Markers No Layer, Draggable</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.51.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
#marker6060 {
background-image: url('https://placekitten.com/g/60/60/');
background-size: cover;
width: 60px;
height: 60px;
border-radius: 50%;
cursor: pointer;
}
#marker5050 {
background-image: url('https://placekitten.com/g/50/50/');
background-size: cover;
width: 50px;
height: 50px;
border-radius: 50%;
cursor: pointer;
}
#marker4040 {
background-image: url('https://placekitten.com/g/40/40/');
background-size: cover;
width: 40px;
height: 40px;
border-radius: 50%;
cursor: pointer;
}
</style>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'YOURS, NOT MINE.';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-65.017, -16.457],
zoom: 5
});
var element6060 = document.createElement('div');
element6060.id = 'marker6060';
var marker6060 = new mapboxgl.Marker({
element: element6060,
draggable: true
})
.setLngLat([-66.324462890625, -16.024695711685304])
.addTo(map);
element6060.addEventListener('click', function() {
var message = 'Kitty 6060';
window.alert(message);
});
var element5050 = document.createElement('div');
element5050.id = 'marker5050';
var marker5050 = new mapboxgl.Marker({
element: element5050,
draggable: true
})
.setLngLat([-61.2158203125, -15.97189158092897])
.addTo(map);
element5050.addEventListener('click', function() {
var message = 'Kitty 5050';
window.alert(message);
});
var element4040 = document.createElement('div');
element4040.id = 'marker4040';
var marker4040 = new mapboxgl.Marker({
element: element4040,
draggable: true
})
.setLngLat([-63.29223632812499, -18.28151823530889])
.addTo(map);
element4040.addEventListener('click', function() {
var message = 'Kitty 4040';
window.alert(message);
});
</script>
</body>
</html>
</script>
</body>
</html>

CartoDB multiple layer toggle

I'm trying to make one map where you can toggle between three different layers, and keep the same legend visible for all. I'm currently following this documentation:
http://docs.cartodb.com/tutorials/toggle_map_view.html
My map in CartoDB has three separate layers (w/ three datasets for the years 2013, 2014 and 2015).
I'm trying to make a toggle map like the one in the documentation. Here's what I go so far:
<html>
<head>
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.11/themes/css/cartodb.css" />
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.11/cartodb.js"></script>
<style>
html, body {width:100%; height:100%; padding: 0; margin: 0;}
#map { width: 100%; height:100%; background: black;}
#menu { position: absolute; top: 5px; right: 10px; width: 400px; height:60px; background: transparent; z-index:10;}
#menu a {
margin: 15px 10px 0 0;
float: right;
vertical-align: baseline;
width: 70px;
padding: 10px;
text-align: center;
font: bold 11px "Helvetica",Arial;
line-height: normal;
color: #555;
border-radius: 4px;
border: 1px solid #777777;
background: #ffffff;
text-decoration: none;
cursor: pointer;
}
#menu a.selected,
#menu a:hover {
color: #F84F40;
}
</style>
<script>
var map;
function init(){
// initiate leaflet map
map = new L.Map('map', {
center: [20,-20],
zoom: 3
})
L.tileLayer('https://dnv9my2eseobd.cloudfront.net/v3/cartodb.map-4xtxp73f/{z}/{x}/{y}.png', {
attribution: 'Mapbox Terms & Feedback'
}).addTo(map);
var layerUrl = 'http://heathermartino.cartodb.com/api/v2/viz/415f8ed2-d493-11e4-b129-0e018d66dc29/viz.json';
var sublayers = [];
cartodb.createLayer(map, layerUrl)
.addTo(map)
.on('done', function(layer) {
// change the query for the first layer
var subLayerOptions = {
sql: "SELECT * FROM gdp_2014",
cartocss: "#gdp_2014{marker-fill: #F84F40; marker-width: 8; marker-line-color: white; marker-line-width: 2; marker-clip: false; marker-gdp_2015ow-overlap: true;}"
}
var sublayer = layer.getSubLayer(0);
sublayer.set(subLayerOptions);
sublayers.push(sublayer);
}).on('error', function() {
//log the error
});
//we define the queries that will be performed when we click on the buttons, by modifying the SQL of our layer
var LayerActions = {
GDP_2015: function(){
sublayers[0].setSQL("SELECT * FROM gdp_2015");
return true;
},
GDP_2014: function(){
sublayers[0].setSQL("SELECT * FROM gdp_2014");
return true;
},
GDP_2013: function() {
sublayers[0].set({
sql: "SELECT * FROM gdp_2013 WHERE cartodb_georef_status = true",
//as it is said, you can also add some CartoCSS code to make your points look like you want for the different queries
// cartocss: "#ne_10m_populated_places_simple{ marker-fill: black; }"
});
return true;
}
}
$('.button').click(function() {
$('.button').removeClass('selected');
$(this).addClass('selected');
//this gets the id of the different buttons and cgdp_2015s to LayerActions which responds according to the selected id
LayerActions[$(this).attr('id')]();
});
L.tileLayer('https://dnv9my2eseobd.cloudfront.net/v3/cartodb.map-4xtxp73f/{z}/{x}/{y}.png', {
attribution: 'Mapbox Terms & Feedback'
}).addTo(map);
}
</script>
</head>
<body onload="init()">
<div id='map'></div>
<div id='menu'>
2013
2014
2015
</div>
</body>
</html>
Right now when you click on the different buttons for 2013, 2014 and 2015, nothing happens. For reference, my map in carto is http://cdb.io/1Bzm2tD. Any ideas? Thanks in advance!
You have the layers. No need to run SQL again. This should work.
<html>
<head>
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.11/themes/css/cartodb.css" />
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.11/cartodb.js"></script>
<style>
html,
body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
#map {
width: 100%;
height: 100%;
background: black;
}
#menu {
position: absolute;
top: 5px;
right: 10px;
width: 400px;
height: 60px;
background: transparent;
z-index: 10;
}
#menu a {
margin: 15px 10px 0 0;
float: right;
vertical-align: baseline;
width: 70px;
padding: 10px;
text-align: center;
font: bold 11px "Helvetica", Arial;
line-height: normal;
color: #555;
border-radius: 4px;
border: 1px solid #777777;
background: #ffffff;
text-decoration: none;
cursor: pointer;
}
#menu a.selected,
#menu a:hover {
color: #F84F40;
}
.cartodb-layer-selector-box,
.cartodb-searchbox,
.cartodb-share {
display: none !important;
}
</style>
<script>
var layer;
function init() {
var url = 'http://heathermartino.cartodb.com/api/v2/viz/415f8ed2-d493-11e4-b129-0e018d66dc29/viz.json';
var visualizacion = cartodb.createVis("map", url)
.done(function(vis, layers) {
layer = layers[1];
});
}
function showLayer(layerToShow) {
//turn off all layers
layer.getSubLayers().forEach(function(i) {
i.hide()
});
switch (layerToShow.id) {
case "gdp_2013":
layer.getSubLayer(0).show();
break;
case "gdp_2014":
layer.getSubLayer(1).show();
break;
case "gdp_2015":
layer.getSubLayer(2).show();
break;
}
return true;
}
</script>
</head>
<body onload="init()">
<div id='map'></div>
<div id='menu'>
2013
2014
2015
</div>
</body>
</html>
I have created something similar - see if this helps. The trick for me was getting the sublayers separated with a for loop, then creating the buttons to act on each.
function loadPosition(position) {
lati = position.coords.latitude;
longi = position.coords.longitude;
map = L.map('map', {zoomControl: false}).setView([lati, longi], 15);
L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {maxZoom: 19,}).addTo(map);
L.control.scale({position: 'bottomright'}).addTo(map);
/*CARTODB LAYERS*/
var layerSource = {
user_name: 'YOUR USER NAME',
type: 'cartodb',
cartodb_logo: false,
sublayers: [{
sql: "SELECT * FROM winston_survey_tool WHERE point_class LIKE 'Orientation point'",
cartocss: '#winston_survey_tool{marker-fill:#D94C38;marker-opacity:1;line-color:#FFF;line-width:1;line-opacity:1;marker-allow-overlap:true; [zoom >= 15] {marker-width: 15} [zoom >= 19] {marker-width: 20}}'
},
{
sql: "SELECT * FROM winston_survey_tool WHERE point_class LIKE 'Survey point'",
cartocss: '#winston_survey_tool{marker-fill:#E0D03D;marker-opacity:1;line-color:#FFF;line-width:1;line-opacity:1;marker-allow-overlap:true; [zoom >= 15] {marker-width: 15} [zoom >= 19] {marker-width: 20}}'
}]
};
// STORE SUBLAYERS
var sublayers = [];
// ADD LAYER TO MAP
cartodb.createLayer(map,layerSource)
.addTo(map)
.done(function(layer) {
// SEPARATE THE SUBLAYERS
for (i = 0; i < layer.getSubLayerCount(); i++) {
sublayers[i] = layer.getSubLayer(i);
sublayers[i].hide();
};
// BUTTONS
$('#orientationCheck').click(function () {
orientationValue = $("#orientationCheck").val();
var query = "SELECT * FROM winston_survey_tool WHERE date LIKE'%";
yearSelectVal = $("#yearSelect").val();
query = query + yearSelectVal + "' AND point_class LIKE 'Orientation point'";
sublayers[0] = sublayers[0].setSQL(query);
if(orientationValue=="ON"){
sublayers[0].hide();
$('#orientationCheck').val("OFF");
$("#orientationCheck").addClass("off");
}
else{
sublayers[0].show();
$('#orientationCheck').val("ON");
$("#orientationCheck").removeClass("off");
};
});
$('#surveyCheck').click(function () {
surveyValue = $("#surveyCheck").val();
var query = "SELECT * FROM winston_survey_tool WHERE date LIKE'%";
yearSelectVal = $("#yearSelect").val();
query = query + yearSelectVal + "' AND point_class LIKE 'Survey point'";
sublayers[1] = sublayers[1].setSQL(query);
if(surveyValue=="ON"){
sublayers[1].hide();
$('#surveyCheck').val("OFF");
$("#surveyCheck").addClass("off");
}
else{
sublayers[1].show();
$('#surveyCheck').val("ON");
$("#surveyCheck").removeClass("off");
};
});
});

Leaflet API GeoJSON Error

I am trying to load a GeoJSON file for an interactive map of West Virginia Counties but I am getting an error saying Uncaught ReferenceError: wvData is not defined on line 140. Can someone help me in figuring out how to resolve this? I am attaching my full code.
<html>
<head>
<title>Leaflet Interactive GeoJSON</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<style>
#map {
width: 100%;
height: 100%;
}
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.info h4 {
margin: 0 0 5px;
color: #777;
}
.legend {
text-align: left;
line-height: 18px;
color: #555;
}
.legend i {
width: 18px;
height: 18px;
float: left;
margin-right: 8px;
opacity: 0.7;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script type="text/javascript" src="CountySelection.js"></script>
<script type="text/javascript">
var map = L.map('map').setView([37.8, -96], 4);
L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
maxZoom: 16,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'examples.map-20v6611k'
}).addTo(map);
// control that shows state info on hover
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function (props) {
this._div.innerHTML = '<h4>US Population Density</h4>' + (props ?
'<b>' + props.NAME + '</b><br />' + props.POP2010 + ' people / mi<sup>2</sup>'
: 'Hover over a state');
};
info.addTo(map);
// get color depending on population density value
function getColor(d) {
return d > 1000 ? '#800026' :
d > 500 ? '#BD0026' :
d > 200 ? '#E31A1C' :
d > 100 ? '#FC4E2A' :
d > 50 ? '#FD8D3C' :
d > 20 ? '#FEB24C' :
d > 10 ? '#FED976' :
'#FFEDA0';
}
function style(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7,
fillColor: getColor(feature.properties.POP2010)
};
}
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 5,
color: '#666',
dashArray: '',
fillOpacity: 0.7
});
if (!L.Browser.ie && !L.Browser.opera) {
layer.bringToFront();
}
info.update(layer.feature.properties);
}
var geojson;
function resetHighlight(e) {
geojson.resetStyle(e.target);
info.update();
}
function zoomToFeature(e) {
map.fitBounds(e.target.getBounds());
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
} <!-- ADDED: Line 140 in the source code -->
geojson = L.geoJson(wvData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
map.attributionControl.addAttribution('Population data © US Census Bureau');
var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend'),
grades = [0, 10, 20, 50, 100, 200, 500, 1000],
labels = [],
from, to;
for (var i = 0; i < grades.length; i++) {
from = grades[i];
to = grades[i + 1];
labels.push(
'<i style="background:' + getColor(from + 1) + '"></i> ' +
from + (to ? '–' + to : '+'));
}
div.innerHTML = labels.join('<br>');
return div;
};
legend.addTo(map);
</script>
</body>
</html>
In the line
geojson = L.geoJson(wvData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
you haven't yet defined wvData anywhere, and looks like you haven't loaded your geojson file yet either. If you're data is defined in a separate geojson file, you'll need to load it via an ajax request, or checkout the leaflet-omnivore plugin.
Lyzi Diamond published some blog posts about loading geojson with leaflet. It helped me a lot: http://lyzidiamond.com/posts/external-geojson-and-leaflet-the-other-way/

Reset normal Viewer visualization after using Oculus plugin

I'm using the Oculus plugin with Cesium and I have no problem passing from "Viewer visualization" to "oculus visualization", the point is I'm not able to come back to the "Viewer visualization". How can I reset the scene, and eliminate postprocessing and the frustum offesetting introduced by the oculus plugin?
Thanks in advance.
here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>try</title>
<script src="lib/Cesium/Cesium.js"></script>
<script src="src/canvas-copy.js"></script>
<script src="src/cesium-oculus.js"></script>
<script src="lib/vr.js/vr.js"></script>
<script src="lib/jquery-1.11.1.js"></script>
<style>
#import url(lib/Cesium/Widgets/widgets.css);
body,html {
height: 100%;
}
body {
padding: 0;
border: 0;
margin: 0;
overflow: hidden;
}
#cesiumContainer {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
margin: 0;
overflow: hidden;
padding: 0;
font-family: sans-serif;
}
#stereo div {
pointer-events: none;
height: 100%;
width: 50%;
border: 0px solid red;
margin-left: 0px;
float: left;
}
.eyeLeft {
display: 'block';
float: left;
width: 100%;
height: 100%;
border: 0px solid red;
}
.eyeRight {
display: 'none';
float: left;
width: 50%;
height: 100%;
border: 0px solid red;
}
.fullSize {
display: block;
position: relative;
top: 0;
left: 0;
border: none;
width: 100%;
height: 100%;
}
.myButton{
position: absolute;
left: 10px;
border: 1px solid #edffff;
}
#oculus{
top: 8%;
}
#viewer{
top: 12%;
}
</style>
</head>
<body>
<div style="width: 100%; height: 100%">
<div id="cesiumContainerLeft" class="eyeLeft"></div>
<div id="cesiumContainerRight" class="eyeRight"></div>
</div>
<button id="oculus" type="button" class="cesium-button myButton" title="oculus">oculus</button>
<button id="viewer" type="button" class="cesium-button myButton" title="viewer">viewer</button>
<!-- library -->
<script src="src/cesium-oculus.js"></script>
<script src="src/canvas-copy.js"></script>
<!-- app -->
<script>
//-------------------------------INITIAL SETTINGS--------------------
//create the viewer in the left div
var viewer = new Cesium.Viewer('cesiumContainerLeft');
viewer.scene.debugShowFramesPerSecond = true;
var canvasL = viewer.canvas;
canvasL.className = "fullSize";
//create the right canvas in the right div
var canvasR = document.createElement('canvas');
canvasR.className = "fullSize";
document.getElementById('cesiumContainerRight').appendChild(canvasR);
$('#oculus').bind('click', { param1: viewer}, oculusRules);
$('#viewer').bind('click', { param1: viewer}, backToViewer);
//--------------------OCULUS VIEW-------------------------------
function oculusRules(event){
$('.eyeRight').css({display: 'block'});
$('.eyeLeft').css({width: '50%'});
var viewer = event.data.param1;
var canvasCopy = new CanvasCopy(canvasR, false);
var cesiumOculus = new CesiumOculus(run);
function run() {
var scene = viewer.scene;
scene.camera.frustum.fovy = Cesium.Math.toRadians(90.0);
var camera = scene.camera;
var eyeSeparation = 2.0;
var tick = function() {
// Render right eye
cesiumOculus.setSceneParams(scene, 'right');
scene.initializeFrame();
scene.render();
canvasCopy.copy(canvasL);
// Render left eye
var originalCamera = scene.camera.clone();
CesiumOculus.slaveCameraUpdate(originalCamera, scene.camera, -eyeSeparation);
cesiumOculus.setSceneParams(scene, 'left');
scene.render();
// Restore state
CesiumOculus.slaveCameraUpdate(originalCamera, scene.camera, 0.0);
Cesium.requestAnimationFrame(tick);
};
tick();
var onResizeScene = function(canvas, scene) {
var supersample = 1.0;
var width = canvas.clientWidth * supersample;
var height = canvas.clientHeight * supersample;
if (canvas.width === width && canvas.height === height) {
return;
}
canvas.width = width;
canvas.height = height;
scene.camera.frustum.aspectRatio = width / height;
};
var onResize = function() {
onResizeScene(canvasL, scene);
onResizeScene(canvasR, scene);
};
window.setTimeout(onResize, 60);
window.addEventListener('resize', onResize, false);
}
}
function backToViewer(event){
$('.eyeRight').css({display: 'none'});
$('.eyeLeft').css({width: '100%'});
var viewer = event.data.param1;
}
</script>
</body>
</html>
We'll soon be adding toggling to the example code to demonstrate this. In the meantime you can view the PR here...
https://github.com/NICTA/cesium-oculus-plugin/pull/5