How to fix marker in center of leaflet map after user will drag the map? - leaflet

I am using a custom map on my node add form. My marker is set to my current location using lat and log. Now I want, whenever a user will drag or move map, marker should be in center (fixed). I tried lot of things like:
$cordovaGeolocation.getCurrentPosition(options).then(function(position) {
$scope.latlong = position.coords.latitude + "," + position.coords.longitude;
$rootScope.lati= position.coords.latitude ;
$rootScope.long = position.coords.longitude;
$scope.map.center = {
lat: position.coords.latitude,
lng: position.coords.longitude,
zoom: 20
};
$scope.map.markers.now = {
lat: position.coords.latitude,
lng: position.coords.longitude,
message: "Usted esta aqui!",
draggable: false,
focus: true
};
if ($rootScope.locationresults == undefined) {
Util.getAddressOf(position.coords.latitude, position.coords.longitude).then(function(location) {
$rootScope.locationresults = location[0].formatted_address;
console.log(location);
}, function(error) {
console.error(error);
});
}
$scope.$on("leafletDirectiveMap.move", function(event, args) {
$scope.map.markers.now.setLatLng([0,0]).update();
//$scope.map.markers.now.lat = $scope.map.center.lat;
//$scope.map.markers.now.lng = $scope.map.center.lng;
console.info(JSON.stringify($scope.map.markers.now));
});
$scope.$on("leafletDirectiveMap.drag", function(event, args){
console.log(JSON.stringify($scope.map.center));
//$scope.map.markers.now.setLatLng(0,0);
$scope.map.markers.now.lat = $scope.map.center.lat;
$scope.map.markers.now.lng = $scope.map.center.lng;
});
$scope.$on("leafletDirectiveMarker.dragend", function(event, args) {
console.log("moviendo");
$rootScope.lati= args.model.lat ;
$rootScope.long = args.model.lng;
Util.getAddressOf(args.model.lat, args.model.lng).then(function(location) {
$rootScope.locationresults = location[0].formatted_address;
$scope.latlong = args.model.lat + "," + args.model.lng;
console.log(location);
}, function(error) {
console.error(error);
});
});
}, function(error) {
console.log(error);
});

You could place a fake marker, placing a div with background image on top of the map and placing it with absolute position and pointing always to the center of the map.
Example:
.map-container{
position: relative;
width: 300px;
height: 400px;
}
.map-marker-centered{
background-image: url('https://img.icons8.com/color/48/000000/marker--v1.png') no-repeat;
width: 50px;
height: 60px;
position: absolute;
z-index: 20;
left: calc(50% - 25px);
top: calc(50% - 60px);
transition: all 0.4s ease;
}
<div class="map-container">
<div class="map-marker-centered"></div>
<div class="map"></div>
</div>
Result:

You can place a "fake" marker composed from a background image placed always at the center of the map. You can also detect when map moves and get the coordinates to where the marker points to. Run the snippet:
var mymap = L.map('mapid').setView([51.505, -0.09], 13)
// add the OpenStreetMap tiles
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{ subdomains: ['a', 'b', 'c'] })
.addTo(mymap)
mymap.on("moveend", function () {
console.log(mymap.getCenter().toString());
});
.map {
height: 280px;
z-index: 1;
}
.map-container {
position: relative;
width: 300px;
height: 300px;
}
.map-marker-centered {
background-image: url("https://img.icons8.com/color/48/000000/marker--v1.png");
width: 50px;
height: 48px;
position: absolute;
z-index: 2;
left: calc(50% - 25px);
top: calc(50% - 50px);
transition: all 0.4s ease;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"></script>
<div class="map-container">
<div class="map-marker-centered"></div>
<div id="mapid" class="map"></div>
</div>

Related

mapbox moveend trigger on click only

Ive build a map with custom markers and popups just like in this mapbox-tutorial. Besides I have a custom menu with links to fly to those locations and open the associated popups with moveend-event. This works fine so far.
Now I also have a link which zooms out again to fit all markers in viewport. But this also triggers the moveend-event if it gets clicked.
To understand what I mean: See fiddle and click "Washington" then "SF" then "Show all". I dont understand why moveend triggers with "Show all".
Heres a fiddle
HMTL
<div id="map"></div>
<div id="menu">
<span class="link" data-lat="-77.032" data-lng="38.913" data-id="#marker0">Washington</span>
<span class="link" data-lat="-122.414" data-lng="37.776" data-id="#marker1">San Francisco</span>
<span class="showall">Show all</span>
</div>
JS
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-100, 37.8],
zoom: 0
});
var bounds = new mapboxgl.LngLatBounds();
var geojson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [-77.032, 38.913]
},
properties: {
title: 'Mapbox',
description: 'Washington, D.C.'
}
},
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [-122.414, 37.776]
},
properties: {
title: 'Mapbox',
description: 'San Francisco, California'
}
}
]
};
geojson.features.forEach(function(marker, index) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'marker';
el.id = 'marker' + index;
// make a marker for each feature and add to the map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.setPopup(new mapboxgl.Popup({
offset: 25
}) // add popups
.setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
.addTo(map);
bounds.extend(marker.geometry.coordinates);
});
function fitmarkers() {
map.fitBounds(bounds, {
padding: 120,
speed: 1.6
});
}
fitmarkers();
function triggermarker(id) {
map.on('moveend', function() {
$(id).trigger('click');
});
}
function fadeoutpopup() {
if ($('.mapboxgl-popup').length) {
$('.mapboxgl-popup').fadeOut(300, function() {
$(this).remove();
});
};
}
$('.link').click(function() {
$('span').removeClass('active');
$(this).addClass("active");
fadeoutpopup();
var markerid = $(this).data('id');
map.flyTo({
center: [$(this).data('lat'), $(this).data('lng')],
zoom: 11,
speed: 3
});
triggermarker(markerid);
});
$('.showall').click(function(f) {
fitmarkers();
fadeoutpopup();
});
What browser are you using? Why would triggering a moveEnd be a problem? In case you already are moving, this movement has to end, so that the new movement can start (zoom out to show all markers)
When checking your fiddle, it did only work for me after changing the padding to a smaller value than 120:
function fitmarkers(){
map.fitBounds(bounds, {padding: 10, speed: 1.6});
}
Please see the working code below:
(Please be aware, that you have shared your Mapbox access token. I have removed it from below code, but others could use it to generate cost for you)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Display a map</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
#menu {
position:absolute;
top:0;
padding:20px 40px;
color:#FFF;
background-color:rgba(0,0,0,0.9);
}
#menu span {
margin:0 20px 0 0;
cursor:pointer
}
.link.active {
pointer-events:none;
color:orange
}
.marker {
background-image: url('https://docs.mapbox.com/help/demos/custom-markers-gl-js/mapbox-icon.png');
background-size: cover;
width: 50px;
height: 50px;
border-radius: 50%;
cursor: pointer;
}
.mapboxgl-popup {
max-width: 200px;
}
.mapboxgl-popup-content {
text-align: center;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="menu">
<span class="link" data-lat="-77.032" data-lng="38.913" data-id="#marker0">Washington</span>
<span class="link" data-lat="-122.414" data-lng="37.776" data-id="#marker1">San Francisco</span>
<span class="showall">Show all</span>
</div>
<script>
mapboxgl.accessToken = 'YOUR ACCESS TOKEN';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-100, 37.8],
zoom: 0
});
var bounds = new mapboxgl.LngLatBounds();
var geojson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [-77.032, 38.913]
},
properties: {
title: 'Mapbox',
description: 'Washington, D.C.'
}
},
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [-122.414, 37.776]
},
properties: {
title: 'Mapbox',
description: 'San Francisco, California'
}
}]
};
geojson.features.forEach(function(marker, index) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'marker';
el.id = 'marker'+index;
// make a marker for each feature and add to the map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
.setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
.addTo(map);
bounds.extend(marker.geometry.coordinates);
});
function fitmarkers(){
map.fitBounds(bounds, {padding: 10, speed: 1.6});
}
fitmarkers();
function triggermarker(id){
map.on('moveend', function(){
$(id).trigger('click');
});
}
function fadeoutpopup() {
if ($('.mapboxgl-popup').length) {
$('.mapboxgl-popup').fadeOut(300, function() { $(this).remove(); });
};
}
$('.link').click(function() {
$('span').removeClass('active');
$(this).addClass("active");
fadeoutpopup();
var markerid = $(this).data('id');
map.flyTo({
center: [$(this).data('lat'),$(this).data('lng')],
zoom: 11,
speed: 3
});
triggermarker(markerid);
});
$('span.showall').click(function(f) {
fitmarkers();
fadeoutpopup();
});
</script>
</body>
</html>

Google Marker GeoChart, create a list of existing markers

Similar to how the Pie Chart has a list of all of the properties in the chart that you can hover:
https://developers.google.com/chart/interactive/docs/gallery/piechart
Is this possible to do in any way with a markers GeoChart? Everything is working fine except that I would really like to have a list of all the cities on my map and to be able to hover on the entries of that list and have the right marker "react" to that. I haven't found anything that seems to make that possible at all.
first, use the following chart option...
tooltip: {
trigger: 'both'
}
this will cause the tooltip to show both when the user hovers and selects the chart.
then on your table / list, when the user hovers a row,
use chart method --> setSelection
this will cause the tooltip to appear.
chart.setSelection([{row: sender.target.parentNode.rowIndex - 1}]);
then clear the selection when the user leaves the table row.
chart.setSelection([]);
see following working snippet...
google.charts.load('current', {
packages: ['geochart', 'table'],
mapsApiKey: 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Canada', 500],
['France', 600],
['RU', 700]
]);
var containerChart = document.getElementById('chart');
var containerTable = document.getElementById('table');
var chart = new google.visualization.GeoChart(containerChart);
var table = new google.visualization.Table(containerTable);
google.visualization.events.addListener(table, 'ready', function () {
chart.draw(data, {
tooltip: {
trigger: 'both'
}
});
$(containerTable).find('tbody > tr > td').on('mouseenter', markerShow);
$(containerTable).find('tbody > tr > td').on('mouseleave', markerHide);
});
table.draw(data);
function markerShow(sender) {
chart.setSelection([{row: sender.target.parentNode.rowIndex - 1}]);
}
function markerHide(sender) {
chart.setSelection([]);
}
});
html, body {
height: 100%;
margin: 0px 0px 0px 0px;
overflow: hidden;
padding: 0px 0px 0px 0px;
}
#chart {
height: 100%;
}
.flex-row {
display: flex;
flex-direction: row;
height: 100%;
}
.flex-grow {
flex-basis: 0;
flex-grow: 1;
flex-shrink: 1;
}
.flex-static {
flex-grow: 0;
flex-shrink: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="flex-row">
<div class="flex-grow">
<div id="chart"></div>
</div>
<div class="flex-static">
<div id="table"></div>
</div>
</div>

Google place Api, autocomplete and infowindow

following the example on the google developpers website, I would like to have an infowindow open on click within the results of a search (instead of just the tile on hover)
There are a few similar questions but I did't find an answer that does just this.
Can somebody tell me how to fix it please ?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
.controls {
margin-top: 16px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
<title>Places search box</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
function initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
// [END region_getplaces]
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#target {
width: 345px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map-canvas"></div>
</body>
</html>
Thanks.
For some reason, I can't make a jsfiddle with this (maybe it's a domain permission issue) and I can't upload an image since i'm new here
Try putting this into a jsfiddle referencing https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places in the External Resources.
After an address/place is selected from the searchbox, the marker and infoWindow render with the infoWindow open and populated.
<div id="map_canvas"></div>
<div id="locationField">
<input id="autocomplete" name="autocomplete" type="text" placeholder="Location Search" onFocus="geolocate()" />
</div>
function initialize() {
var placeSearch;
var mapOptions = {
center: new google.maps.LatLng(41.877461, -87.638085),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
disableDefaultUI: true,
streetViewControl: false,
panControl: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */
(
document.getElementById('autocomplete'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(12); // Why 17? Because it looks good.
}
marker.setIcon( /** #type {google.maps.Icon} */ ({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(25, 34),
scaledSize: new google.maps.Size(50, 50)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' + place.formatted_address);
infowindow.open(map, marker);
});
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
autocomplete.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
});
}
}
}
initialize();
html, body, #map_canvas {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#autocomplete {
height: 60px;
width: 100%;
border: 2px solid #fff;
color: #1c1c1c;
font-size: 15px;
text-align: center;
background-color: #fff;
font-family: Roboto;
font-weight: 300;
text-overflow: ellipsis;
}
#autocomplete:focus {
border-color: #4d90fe;
}

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");
};
});
});

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