Autocomplete and suggestions of Leaflet Search doesn't work? - javascript

Good morning all,
I need your help with Leaflet search. I can't seem to find where the error is coming from, which is:
My search bar works fine but autocomplete with suggestions doesn't work, I don't know where it came from.
Also, but this is optional, can you help me to optimize the code for it to be fast to load on a web page (you can see that there is async but it's not enough given the amount of data I load).
Thanks for your help, I'll take everything into consideration.
async function init(){
var lat = 51.505;
var lng = -0.09;
var zoomLevel = 3;
/**********************************************************/
/*INIT MAP*/
/**********************************************************/
var mainLayer = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}{r}?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap',
maxZoom: 11,
minZoom: 2,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
zoomControl: false,
accessToken: 'pk.eyJ1IjoiYW1hdXJ5MDg0MDAiLCJhIjoiY2todWZ3dmtsMDR2cjJ0bzIwajc2NjBobyJ9.VXOjqAoE1IQ2DcCVSYlXOg'
});
var map = L.map('mapAgentsCentrimex', {
center: [lat, lng],
zoom: zoomLevel,
layers: [mainLayer]
});
/**********************************************************/
/*SEARCHBOX*/
/**********************************************************/
var data = us_states;
var featuresLayer = new L.GeoJSON(data, {
style: function(feature) {
return {color: feature.properties.color };
},
onEachFeature: function(feature, marker) {
marker.bindPopup('<h4 style="color:'+feature.properties.color+'">'+ feature.properties.name +'</h4>');
}
});
map.addLayer(featuresLayer);
var searchControl = new L.Control.Search({
position: 'topleft',
layer: featuresLayer,
propertyName: 'name',
marker: false,
moveToLocation: function(latlng, title, map) {
//map.fitBounds( latlng.layer.getBounds() );
var zoom = map.getBoundsZoom(latlng.layer.getBounds());
map.setView(latlng, zoom);
}
});
searchControl.on('search:locationfound', function(e) {
console.log('search:locationfound', );
//map.removeLayer(this._markerSearch)
e.layer.setStyle({fillColor: '#3f0', color: '#0f0'});
}).on('search:collapsed', function(e) {
featuresLayer.eachLayer(function(layer) {
featuresLayer.resetStyle(layer);
});
});
map.addControl( searchControl );
/******************************************************************
*********** MARKERS ***********
******************************************************************/
var markers = L.markerClusterGroup();
var iconAirport = L.icon({
iconUrl: 'images/iconPlane.png',
iconSize: [22, 34]
});
$.getJSON("json/airports.geojson", function(data){
airport = $.each(data,function(key,val){
var titleAirport = val.name;
var latAiport = val.lat;
var lngAirport = val.lon;
markers.addLayer(L.marker([latAiport, lngAirport], {icon: iconAirport}).bindPopup('Name:' + titleAirport));
});
});
map.addLayer(markers);
var iconSeaport = L.icon({
iconUrl: 'images/iconBoat.png',
iconSize: [22, 34]
});
var markersSeaport = L.markerClusterGroup();
$.getJSON("json/IFR_LOCATION_PORTS.geojson",function(data){
var incidents = L.geoJson(data, {
pointToLayer: function (feature, latlng){
var marker = L.marker(latlng, {icon:iconSeaport});
marker.bindPopup('Name:' + feature.properties.Name);
return marker;
},
onEachFeature: function (feature, layer){
layer.addTo(markersSeaport);
}
});
map.addLayer(markersSeaport);
});
L.control.layers({
"Carte Pays": mainLayer
}, {
"Aérien": markers,
"Maritime": markersSeaport
}).addTo(map);
map.zoomControl.remove();
L.control.zoom({
position:'bottomright'
}).addTo(map);
/******************************************************************
*********** GEOLOCATION ***********
******************************************************************/
var geolocButton = L.control({position: 'bottomright'});
geolocButton.onAdd = (mapRef) => {
var button = L.DomUtil.create('button', 'geoloc-button');
button.innerHTML = '<span class="icon-location2"></span>';
button.onclick = () => {
mapRef.locate();
button.disabled = true;
mapRef.on('locationfound', (locEvent) => {
var radius = locEvent.accuracy / 2;
var point = locEvent.latlng;
mapRef.setView(point, 8);
button.disabled = false;
L.circle(point, radius).addTo(mapRef).bindPopup('Vous êtes ici sur la carte').openPopup();
});
mapRef.on('locationerror', (err) =>{
button.disabled = false;
});
}
return button;
}
geolocButton.addTo(map);
/******************************************************************
*********** COUNTRIES ***********
******************************************************************/
// Set color of countries
function style(feature) {
return {
fillColor: '#ff5349',
weight: 5,
opacity: 0,
color: '#ff5349',
dashArray: '3',
fillOpacity: 0
};
}
// Set Mouse Hover
async function highlightFeature(e){
var layer = e.target;
layer.setStyle({
fillColor: '#ff5349',
weight: 4,
opacity: 0.8,
color: '#ff5349',
dashArray: '',
fillOpacity: .5
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
}
async function highlightFeatureClick(e){
var layer = e.target;
layer.setStyle({
weight: 5,
color: '#ff5349',
dashArray: '',
fillOpacity: .7
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
info.update(layer.feature.properties);
info.clickPays(layer.feature.properties);
}
// Back color Mouse Out
async function resetHighlight(e) {
geojson.resetStyle(e.target);
}
// Each Feature
async function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: highlightFeatureClick
});
}
// Display data to e.target inside wrapper
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this._div.setAttribute("id", "idBoxList");
L.DomEvent
.addListener(this._div, 'mouseover', function () {
MapShowCommand();
});
this.update();
this.clickPays();
return this._div;
};
info.update = function (props) {
this._div.innerHTML = '<div class="wrapper--popup-agents"><h3 class="title-med">Agents disponibles</h3><div class="buttonListeAgent" id="buttonListeAgentId"><span class="icon-keyboard_arrow_down"></span></div><div class="textfield">Liste des agents disponibles selon le pays sélectionné.</div></div><div class="agents--wrapper"><div class="content"><ul class="listAgents"></ul></div></div>';
};
info.clickPays = function(props){
if (props) {
this._div.classList.add("show");
var el = document.getElementById('idBoxList');
L.DomEvent.disableScrollPropagation(el);
L.DomEvent.disableClickPropagation(el);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var name = props.name;
var base_path = $('#url_base').val();
$.ajax({
url:"/map-agents",
type:'POST',
data:{name:name},
dataType: "JSON",
beforeSend: function () {
$('.listAgents').append('<div class="spinner-border text-info" role="status"></div>');
},
success: function (response) {
$.each(response, function (index) {
if (response[index].transport == 'M') {
var pathIcon = 'http://127.0.0.1:8000/images/icon/picto-centrimex-bateau.png';
}
if (response[index].transport == 'A'){
var pathIcon = 'http://127.0.0.1:8000/images/icon/picto-centrimex-avion.png';
}
if (response[index].transport == 'MA') {
var pathIcon = 'http://127.0.0.1:8000/images/icon/picto-centrimex-maritime-aerien.png';
}
var agents = '<li class="agents"><input type="hidden" class="agentId" name="idAgent" value="'+ response[index].id +'"><div class="leftSide"><h5 class="title">' + response[index].nom_fr_fr + '</h5><div class="name-firm">' + response[index].nameFirm + '<span>, ' + response[index].city + '</span></div></div><div class="rightSide"><img src="' + pathIcon + '" alt="Icon transport"></div></li>';
$('.listAgents').append(agents);
});
},
complete: function () {
$('.spinner-border.text-info').remove();
},
error: function (response){
console.log(response);
}
});
}
else
{
this._div.classList.remove("show");
}
};
info.setPosition('bottomleft');
info.addTo(map);
async function refreshDataAgent(){
$('.wrapper-overlay').html('<div class="wrapper--agent-map"></div>')
}
async function MapShowCommand() {
$('.buttonListeAgent').off().on('click', function(){
if ($('#idBoxList').hasClass("show")) {
$('#idBoxList').removeClass("show");
info.update();
}
});
$('.listAgents li').off().on('click', function(){
var el = document.getElementById('overlayMap');
L.DomEvent.disableScrollPropagation(el);
L.DomEvent.disableClickPropagation(el);
var idAgent = $(this).children('input').val();
var base_path = $('#url_base').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"/map-agents/agents",
type:'POST',
data:{idAgent:idAgent},
dataType: "JSON",
beforeSend: function () {
$('.wrapper-overlay').addClass('active');
$('.wrapper--agent-map').append('<div class="spinner-border text-info" role="status"></div>');
},
success: function (response) {
var transport = '';
switch (response.transport){
case 'MA':
transport = '<li><img src="/images/icon/picto-centrimex-bateau.png"><span>Maritime</span></li><li><img src="/images/icon/picto-centrimex-avion.png"><span>Aérien</span></li>';
break;
case 'M':
transport = '<li><img src="/images/icon/picto-centrimex-bateau.png"><span>Maritime</span></li>';
break;
case 'A':
transport = '<li><img src="/images/icon/picto-centrimex-avion.png"><span>Aérien</span></li>';
break;
default:
transport = '<li><span class="whiteInput">Pas de transport renseigné</span></li>';
}
var wrapperContentAgent = '<div class="closePopUp"><span class="icon-cross"></span></div><div class="topSection"><div class="first"><h3>Compagnie</h3><ul class="compagnieList"></ul></div><div class="two"><h3>Mode de transport</h3><ul class="transportList"></ul></div><div class="three"><h3>Informations</h3><ul class="infosList"></ul></div></div><div class="middleSection"><div class="first"><h3>Référence client</h3><ul class="referenceList"></ul></div><div class="two"><div class="whitespace"></div><ul class="profitList"></ul></div></div><div class="bottomSection"><h3>Commentaire</h3><div class="contentComment"></div></div>';
$('.wrapper--agent-map').append(wrapperContentAgent);
$('.wrapper--agent-map').append('<input type="hidden" value="'+ response.id +'" name="idAgent">')
$('.compagnieList').append('<li>Nom Compagnie : '+ (response.nameFirm ? '<span>'+response.nameFirm+'</span>' : '<span class="whiteInput">Pas de nom de compagnie</span>') +'</li><li>Pays : '+ (response.nom_fr_fr ? '<span>'+response.nom_fr_fr+'</span>' : '<span class="whiteInput">Pas de pays</span>') +'</li><li>Ville : '+ (response.city ? '<span>'+response.city+'</span>' : '<span class="whiteInput">Pas de ville</span>') +'</li><li>Réseau : '+ (response.network ? '<span>'+response.nameNetwork+'</span>' : '<span class="whiteInput">Pas de réseau associé</span>') +'</li>');
$('.transportList').append(transport);
$('.infosList').append('<li>Nom : '+ (response.lastName ? '<span>'+response.lastName+'</span>' : '<span class="whiteInput">Pas de nom</span>') +'</li><li>Prénom : '+ (response.firstName ? '<span>'+response.firstName+'</span>' : '<span class="whiteInput">Pas de prénom</span>') +'</li><li>E-mail : '+ (response.mail ? '<span>'+response.mail+'</span>' : '<span class="whiteInput">Pas de mail</span>') +'</li><li>Téléphone : '+ (response.phone ? '<span>'+response.phone+'</span>' : '<span class="whiteInput">Pas de téléphone</span>') +'</li>');
$('.referenceList').append('<li>Référence compte client : '+ (response.accountCustomer ? '<span>'+response.accountCustomer+'</span>' : '<span class="whiteInput">Pas de référence client</span>') +'</li><li>Référence compte fournisseur : '+ (response.accountProvider ? '<span>'+response.accountProvider+'</span>' : '<span class="whiteInput">Pas de référence fournisseur</span>') +'</li>');
$('.profitList').append('<li>ProfitShare : '+ (response.profitShare ? '<span>'+response.profitShare+'</span>' : '<span class="whiteInput">Pas de profitShare renseigné</span>') +'</li><li>Condition de Paiement : '+ (response.payementCondition ? '<span>'+response.payementCondition+'</span>' : '<span class="whiteInput">Pas de conditionde paiement renseigné</span>') +'</li><li>Réciprocité Business : '+ (response.business ? '<span>'+response.business+'</span>' : '<span class="whiteInput">Pas de réciprocité business renseignée</span>') +'</li>');
$('.contentComment').append((response.comment ? '<p>'+response.comment+'</p>' : '<span class="whiteInput">Pas de commentaire sur cette agent</span>'));
// if (response.supsension != null) {
// $('.bottomSection').append('');
// }
$('.closePopUp').click(function(){
$('.wrapper-overlay').removeClass('active');
refreshDataAgent();
});
},
complete: function () {
$('.spinner-border.text-info').remove();
},
error: function (response){
console.log(response);
}
});
});
}
// Call data inside geoJSON
$.getJSON("json/countries.geojson",function(data){
geojson = L.geoJson(data, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
});
}
/************************************************************************************************/
/* MAP */
/************************************************************************************************/
#mapAgentsCentrimex{
width: 100%;
height: 100vh;
z-index: 1;
}
#buttonScrollMap
{
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
z-index: 2;
background-color: white;
width: 50px;
height: 50px;
border-radius: 50%;
box-shadow: 0px 0px 15px rgba(0,0,0,0.3);
color: #4690be;
font-size: 14px;
font-weight: 600;
}
#buttonScrollMap:before
{
content: '\e90e';
font-family: icomoon;
font-size: 26px;
color: black;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#buttonScrollMap:hover{
text-decoration: none;
}
#mapAgentsCentrimex .info{
background-color: #003366;
color: white;
width: 400px;
float: none;
overflow-y: auto;
max-height: 80vh;
}
#mapAgentsCentrimex .buttonListeAgent {
position: absolute;
top: 10px;
right: 10px;
font-size: 30px;
color: white;
opacity: .8;
z-index: 999;
}
#mapAgentsCentrimex .buttonListeAgent:hover{
opacity: 1;
color: #FAFAFA;
cursor: pointer;
}
#mapAgentsCentrimex .info.active{
height: auto;
}
#mapAgentsCentrimex .wrapper--popup-agents{
padding: 30px;
}
#mapAgentsCentrimex .agents--wrapper{
background-color: white;
}
#mapAgentsCentrimex .agents--wrapper .listAgents .agents {
display: flex;
flex-direction: row;
}
#mapAgentsCentrimex .agents--wrapper .listAgents .agents .leftSide{
width: 60%;
padding-left: 15px;
}
#mapAgentsCentrimex .agents--wrapper .listAgents .agents .rightSide{
width: 40%;
position: relative;
}
#mapAgentsCentrimex .agents--wrapper .listAgents .agents .rightSide img{
width: auto;
height: 50px;
position: absolute;
top: 50%;
right: 3%;
transform: translateY(-50%);
}
#mapAgentsCentrimex ul.listAgents {
margin: 0px;
padding: 0;
list-style: none;
}
#mapAgentsCentrimex li.agents {
width: 100%;
height: auto;
color: black;
padding: 20px;
}
#mapAgentsCentrimex li.agents:hover{
background-color: #FAFAFA;
}
#mapAgentsCentrimex h5.title {
text-transform: uppercase;
font-size: 14px;
font-weight: 700;
letter-spacing: .5px;
color: #4690be;
}
#mapAgentsCentrimex .name-firm {
font-size: small;
font-weight: 600;
text-transform: capitalize;
}
#mapAgentsCentrimex .name-firm span{
font-weight: 300;
text-transform: capitalize;
}
#mapAgentsCentrimex button.geoloc-button.leaflet-control {
box-sizing: border-box;
box-shadow: 0px 0px 20px rgba(0,0,0,.2);
border: none;
padding: 8px;
background-color: white;
border-radius: 2px;
font-size: 17px;
}
.leaflet-touch .leaflet-control-layers, .leaflet-touch .leaflet-bar {
box-sizing: border-box;
box-shadow: 0px 0px 20px rgba(0,0,0,.2) !important;
border: none !important;
padding: 2px;
background-color: white;
border-radius: 2px;
font-size: 17px;
}
#mapAgentsCentrimex .wrapper-overlay{
background-color: rgba(0,0,0,.7);
width: 100%;
height: 100vh;
position: absolute;
top: 0;
left: 0;
z-index: 1001;
display: none;
cursor: initial;
}
#mapAgentsCentrimex .wrapper-overlay.active{
display: block;
}
#mapAgentsCentrimex .wrapper-overlay .wrapper--agent-map{
background-color: white;
width: 85%;
height: 80vh;
min-width: 300px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
box-sizing: border-box;
box-shadow: 0px 0px 20px rgba(0,0,0,.2);
padding: 30px;
}
#mapAgentsCentrimex .wrapper-overlay .closePopUp{
position: absolute;
top: 0px;
right: 0px;
padding: 20px;
}
#mapAgentsCentrimex .wrapper-overlay .closePopUp:hover{
cursor: pointer;
}
#mapAgentsCentrimex .wrapper-overlay .closePopUp .icon-cross{
font-size: 22px;
opacity: .7;
}
#mapAgentsCentrimex .wrapper-overlay h3{
color: #4690be;
font-size: 22px;
font-weight: 700;
letter-spacing: .5px;
line-height: 40px;
margin-bottom: 15px;
}
#mapAgentsCentrimex .wrapper-overlay .whitespace{
height: 40px;
width: 100%;
margin-bottom: 15px;
}
#mapAgentsCentrimex .wrapper-overlay ul{
list-style: none;
margin-left: 0;
padding: 0;
}
#mapAgentsCentrimex .wrapper-overlay ul li{
line-height: 25px;
font-size: 15px;
color: black;
opacity: 0.8;
font-weight: 300;
}
#mapAgentsCentrimex .wrapper-overlay ul li span{
font-weight: 600;
font-size: 16px;
}
#mapAgentsCentrimex .wrapper-overlay p{
color: black;
font-size: 16px;
font-weight: 300;
}
#mapAgentsCentrimex .wrapper-overlay ul li span.whiteInput{
color: #eda60c;
}
#mapAgentsCentrimex .wrapper-overlay ul li img{
width: 50px;
height: 50px;
margin-right: 20px;
}
#mapAgentsCentrimex .wrapper-overlay .topSection, #mapAgentsCentrimex .wrapper-overlay .middleSection{
display: flex;
flex-direction: row;
margin-bottom: 30px;
}
#mapAgentsCentrimex .wrapper-overlay .topSection .first, #mapAgentsCentrimex .wrapper-overlay .topSection .two, #mapAgentsCentrimex .wrapper-overlay .topSection .three{
width: 33%;
padding: 10px;
}
#mapAgentsCentrimex .wrapper-overlay .middleSection .first, #mapAgentsCentrimex .wrapper-overlay .middleSection .two{
width: 50%;
padding: 10px;
}
<section class="glob--map">
<div id="mapAgentsCentrimex">
<div class="wrapper-overlay" id="overlayMap">
<div class="wrapper--agent-map">
</div>
</div>
</div>
<input type="hidden" id="url_base" value="{{ URL::asset('images/centrimex_logo.png') }}" name="">
</section>

Problem of autocomplete & suggestion resolve.
When you add librairies, make sure that you don't include leaflet-search.js & leaflet-search-geocoder.js in the same time. "leaflet-search-geocoder.js" blocked a few functions like Autocomplete.
But if you want to help me with the optimization of my script, the topic is still open

Related

How can I add a custom line into react-moveable?

I want to add 7 custom lines as helper to user.
Like in that picture, I want to add 7 times "div.moveable-line"
Even rotation change, the lines stayed at suitible position => And I want to add them 7 times.
Can we create a line between T1 and B1 (and for the others)?
Or if you have any other solutions, I am open for them as well.
React Moveable - Github
Warpable - StoryBook
Moveable.warpable - Documentation
Here is a demo link
MY COMPONENT
import React from 'react';
import ReactDOM from 'react-dom';
import Moveable from 'react-moveable';
import { ref } from 'framework-utils';
import { Frame } from 'scenejs';
import './styles.css';
class App extends React.Component {
frame = new Frame({
width: '250px',
height: '200px',
left: '0px',
top: '0px',
transform: {
rotate: '0deg',
scaleX: 1,
scaleY: 1,
matrix3d: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
},
});
state = {
target: null,
container: null,
warpable: true,
stateTransform: [],
totalBoxesTop: 0,
totalBoxesFill: 0,
totalBoxesBottom: 0,
isBoxCreated: false,
};
render() {
const { warpable, target } = this.state;
let k = document.querySelector('.moveable-control-box');
console.log(k, ':44');
if (k !== null) {
// k.appendChild(z);
// k.appendChild(d);
k.style.position = 'relative';
k.style.backgroundColor = '#fff';
}
let topLine = document.querySelector(
'.moveable-direction[data-line-index="0"]'
);
if (topLine !== null) {
topLine.classList.add('myTopLine');
let d = document.createElement('div'); // is a node
d.innerHTML = `T${this.state.totalBoxesTop}`;
d.setAttribute('data-box-position-top', `${this.state.totalBoxesTop}`);
d.classList.add('my-box');
if (this.state.totalBoxesTop < 8) {
// When is this.state.totalBoxes === 1 it means 0 boxes appear
topLine.appendChild(d);
this.setState({ totalBoxesTop: this.state.totalBoxesTop + 1 });
}
console.log(topLine, this.state.totalBoxesTop);
}
let bottomLine = document.querySelector(
'.moveable-direction[data-line-index="3"]'
);
if (bottomLine !== null) {
bottomLine.classList.add('myBottomLine');
let d = document.createElement('div'); // is a node
d.innerHTML = `B${this.state.totalBoxesBottom}`;
d.setAttribute(
'data-box-position-bottom',
`${this.state.totalBoxesBottom}`
);
d.classList.add('my-box');
if (this.state.totalBoxesBottom < 8) {
// When is this.state.totalBoxes === 1 it means 0 boxes appear
bottomLine.appendChild(d);
this.setState({ totalBoxesBottom: this.state.totalBoxesBottom + 1 });
}
console.log(bottomLine, this.state.totalBoxesBottom);
}
return (
<div className="page main">
<Moveable
ref={ref(this, 'moveable')}
target={target}
pinchThreshold={20}
container={document.body}
draggable={true}
warpable={warpable}
rotatable={true}
pinchable={true}
origin={false}
throttleDrag={1}
throttleRotate={0.2}
throttleResize={1}
throttleScale={0.01}
onDrag={this.onDrag}
onWarp={this.onWarp}
onDragEnd={this.onEnd}
onScaleEnd={this.onEnd}
onResizeEnd={this.onEnd}
onWarpEnd={this.onEnd}
onRotateEnd={this.onEnd}
onPinchEnd={this.onEnd}
/>
<div className="moveable">hello</div>
<div className="label" ref={ref(this, 'label')} />
</div>
);
}
componentDidMount() {
this.setState({
target: document.querySelector('.moveable'),
});
window.addEventListener('resize', this.onWindowReisze);
}
componentWillUnmount() {
window.removeEventListener('resize', this.onWindowReisze);
}
onWindowReisze = () => {
this.moveable.updateRect();
};
setTransform(target) {
target.style.cssText = this.frame.toCSS();
}
setLabel(clientX, clientY, text) {
this.label.style.cssText = `
display: block; transform: translate(${clientX}px, ${
clientY - 10
}px) translate(-100%, -100%) translateZ(-100px);`;
this.label.innerHTML = text;
}
onDrag = ({ target, clientX, clientY, top, left, isPinch }) => {
this.frame.set('left', `${left}px`);
this.frame.set('top', `${top}px`);
this.setTransform(target);
if (!isPinch) {
this.setLabel(clientX, clientY, `X: ${left}px<br/>Y: ${top}px`);
}
};
onWarp = ({
target,
clientX,
clientY,
delta,
multiply,
currentTarget,
moveable,
datas,
inputEvent,
transform,
dist,
matrix,
}) => {
console.log(target);
target.style.transform = `matrix3d(${matrix.join(',')})`;
this.setState({ stateTransform: `matrix3d(${matrix.join(',')})` });
this.frame.set(
'transform',
'matrix3d',
multiply(this.frame.get('transform', 'matrix3d'), delta)
);
this.setTransform(target);
this.setLabel(clientX, clientY, `X: ${clientX}px<br/>Y: ${clientY}px`);
};
onEnd = () => {
this.label.style.display = 'none';
};
}
export default App;
#import url("https://fonts.googleapis.com/css?family=Open+Sans:300,400,600&display=swap");
.moveable {
position: absolute;
width: 250px;
height: 200px;
margin: 0 auto;
background-color: transparent;
top: 0;
left: 0;
}
.my-new-box{
position: relative;
width: 100%;
height: 100%;
background-color: #73a079;
}
.myTopLine,
.myBottomLine{
background-color: #8b270a!important;
display: flex!important;
position: absolute!important;
justify-content: space-between!important;
align-items: flex-end!important;
}
.my-box {
position: relative;
top: 0;
left: 0;
width: 25px;
height: 25px;
/*flex: 1;*/
/*margin: 0 auto;*/
background-color: rgba(0,222,222,0.3);
/*transform: translate3d(42px, -62px, -135px);*/
}
.my-line{
position: relative;
top: 0;
left: 0;
width: 100px;
height: 150px;
background-color: #3a3aa0;
}
.moveable-control-box {
position: relative!important;
background-color: #8b2c62 !important;
}
.label {
position: fixed;
top: 0;
left: 0;
padding: 5px;
border-radius: 5px;
background: #333;
z-index: 3001;
color: #fff;
font-weight: bold;
font-size: 12px;
display: none;
transform: translate(-100%, -100%);
}
.feature .container .left {
position: relative;
width: 300px;
height: 205px;
display: inline-block;
vertical-align: top;
z-index: 2000;
margin-bottom: 20px;
}
.feature .container .right {
position: relative;
display: inline-block;
vertical-align: top;
flex: 1;
}
.feature .right .description {
text-align: left;
margin: 0px 0px 10px;
}
.feature .right .description strong {
font-weight: 600;
}
.draggable,
.resizable,
.scalable,
.rotatable,
.origin,
.warpable,
.pinchable {
position: absolute;
left: 0;
}
.origin {
transform-origin: 30% 50%;
}
pre {
position: relative;
border: 1px solid #ccc;
box-sizing: border-box;
padding: 10px;
max-width: 500px;
}
code.hljs {
padding: 0;
}
.tab {
padding: 10px 12px;
appearance: none;
-webkit-appearance: none;
background: transparent;
border: 1px solid #ccc;
box-shadow: none;
font-weight: bold;
margin: 0;
cursor: pointer;
outline: none;
}
.tab.selected {
background: #333;
color: #fff;
border: 1px solid #333;
}
.panel {
display: none;
}
.panel.selected {
display: block;
}
.page.footer {
font-weight: 400;
}
.page.footer a {
text-decoration: underline;
}
.page.footer span:first-child:before {
content: "";
}
.page.footer span:before {
content: "/";
}
Make Custom Able for Custom Lines
https://stackblitz.com/edit/react-ts-wmy77k?file=index.tsx

How to get information of a particular WMS layer and display it as a popup using Openlayers3

I am trying display two WMS layers,in which I have succeeded.Next is to get information of a particular WMS layer and display it as a pop up.I am using Openlayers3 with Geoserver.
First layer is 'Village Boundary' which is base layer and the second one is 'OSM Grids'.
These grids are numbered from 1 to 87. When I click on each grid , it should display its attribute information like grid number,map number etc. as a pop up.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="http://localhost:8080/geoserver/openlayers3/ol.css" type="text/css">
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<style>
.ol-zoom {
top: 52px;
}
.ol-toggle-options {
z-index: 1000;
background: rgba(255,255,255,0.4);
border-radius: 4px;
padding: 2px;
position: absolute;
left: 8px;
top: 8px;
}
#updateFilterButton, #resetFilterButton {
height: 22px;
width: 22px;
text-align: center;
text-decoration: none !important;
line-height: 22px;
margin: 1px;
font-family: 'Lucida Grande',Verdana,Geneva,Lucida,Arial,Helvetica,sans-serif;
font-weight: bold !important;
background: rgba(0,60,136,0.5);
color: white !important;
padding: 2px;
}
.ol-toggle-options a {
background: rgba(0,60,136,0.5);
color: white;
display: block;
font-family: 'Lucida Grande',Verdana,Geneva,Lucida,Arial,Helvetica,sans-serif;
font-size: 19px;
font-weight: bold;
height: 22px;
line-height: 11px;
margin: 1px;
padding: 0;
text-align: center;
text-decoration: none;
width: 22px;
border-radius: 2px;
}
.ol-toggle-options a:hover {
color: #fff;
text-decoration: none;
background: rgba(0,60,136,0.7);
}
body {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: small;
}
iframe {
width: 100%;
height: 250px;
border: none;
}
/* Toolbar styles */
#toolbar {
position: relative;
padding-bottom: 0.5em;
}
#toolbar ul {
list-style: none;
padding: 0;
margin: 0;
}
#toolbar ul li {
float: left;
padding-right: 1em;
padding-bottom: 0.5em;
}
#toolbar ul li a {
font-weight: bold;
font-size: smaller;
vertical-align: middle;
color: black;
text-decoration: none;
}
#toolbar ul li a:hover {
text-decoration: underline;
}
#toolbar ul li * {
vertical-align: middle;
}
#map {
clear: both;
position: relative;
width: 600px;
height: 800px;
border: 1px solid black;
bottom:802px;
left:450px;
}
img{
position: relative;
width: 444px;
height: 775px;
top:5px;
}
#legend {
position: relative;
width: 444px;
height: 800px;
border: 1px solid black;
top:0px;
}
#wrapper {
width: 444px;
position: relative;
bottom:802px;
left:450px;
}
#location {
bottom:802px;
left:450px;
}
/* Styles used by the default GetFeatureInfo output, added to make IE happy */
table.featureInfo, table.featureInfo td, table.featureInfo th {
border: 1px solid #ddd;
border-collapse: collapse;
margin: 0;
padding: 0;
font-size: 90%;
padding: .2em .1em;
}
table.featureInfo th {
padding: .2em .2em;
font-weight: bold;
background: #eee;
}
table.featureInfo td {
background: #fff;
}
table.featureInfo tr.odd td {
background: #eee;
}
table.featureInfo caption {
text-align: left;
font-size: 100%;
font-weight: bold;
padding: .2em .2em;
}
</style>
<script src="http://localhost:8080/geoserver/openlayers3/ol.js" type="text/javascript"></script>
<title>OpenLayers map preview</title>
</head>
<body>
<div id="legend">
<img src="Legend.PNG.jpg">
</div>
<div id="map">
<input type="checkbox" value="Village Boundary" checked>Village Boundary<br>
<input type="checkbox" value="OSM Grids">OSM Grids<br>
</div>
<div id="wrapper">
<div id="location"></div>
<div id="scale"></div>
</div>
<script type="text/javascript">
var pureCoverage = false;
// if this is just a coverage or a group of them, disable a few items,
// and default to jpeg format
var format = 'image/png';
var bounds = [472440.0520989996, 911801.0984444692,
768802.9061656371, 1424302.9894040015];
if (pureCoverage) {
document.getElementById('antialiasSelector').disabled = true;
document.getElementById('jpeg').selected = true;
format = "image/jpeg";
}
var supportsFiltering = true;
if (!supportsFiltering) {
document.getElementById('filterType').disabled = true;
document.getElementById('filter').disabled = true;
document.getElementById('updateFilterButton').disabled = true;
document.getElementById('resetFilterButton').disabled = true;
}
var mousePositionControl = new ol.control.MousePosition({
className: 'custom-mouse-position',
target: document.getElementById('location'),
coordinateFormat: ol.coordinate.createStringXY(5),
undefinedHTML: ' '
});
var projection = new ol.proj.Projection({
code: 'EPSG:32643',
units: 'm',
axisOrientation: 'neu',
global: false
});
var villageboundary = new ol.layer.Image({
title:'Village Boundary',
type: 'base',
label:'Village Boundary',
source: new ol.source.ImageWMS({
ratio: 1,
url: 'http://localhost:8080/geoserver/geog585/wms',
params: {'FORMAT': format,
'VERSION': '1.1.1',
"LAYERS": 'geog585:Village_Boundary',
"exceptions": 'application/vnd.ogc.se_inimage',
}
})
});
var osmgrid = new ol.layer.Image({
title:'OSM Grid',
visible: false,
label:'OSM Grid',
source: new ol.source.ImageWMS({
ratio: 1,
url: 'http://localhost:8080/geoserver/geog585/wms',
params: {'FORMAT': format,
'VERSION': '1.1.1',
"LAYERS": 'geog585:OSM_Grid_25000_include_hazard_line',
"exceptions": 'application/vnd.ogc.se_inimage',
}
})
});
//Tile OSM
var tiledOSM = new ol.layer.Tile({
title:'OSM Grids',
visible: false,
label:'OSM Grids',
source: new ol.source.TileWMS({
url: 'http://localhost:8080/geoserver/geog585/wms',
params: {'FORMAT': format,
'VERSION': '1.1.1',
tiled: true,
"LAYERS": 'geog585:OSM_Grid_25000_include_hazard_line',
"exceptions": 'application/vnd.ogc.se_inimage',
tilesOrigin: 472849.4548000004 + "," + 912420.9497999996
}
})
});
//Tile OSM
var map = new ol.Map({
controls: ol.control.defaults({
attribution: false
}).extend([mousePositionControl]),
target: 'map',
layers: [
villageboundary,
tiledOSM
],
view: new ol.View({
projection: projection
})
});
map.getView().on('change:resolution', function(evt) {
var resolution = evt.target.get('resolution');
var units = map.getView().getProjection().getUnits();
var dpi = 25.4 / 0.28;
var mpu = ol.proj.METERS_PER_UNIT[units];
var scale = resolution * mpu * 39.37 * dpi;
if (scale >= 9500 && scale <= 950000) {
scale = Math.round(scale / 1000) + "K";
} else if (scale >= 950000) {
scale = Math.round(scale / 1000000) + "M";
} else {
scale = Math.round(scale);
}
document.getElementById('scale').innerHTML = "Scale = 1 : " + scale;
});
map.getView().fit(bounds, map.getSize());
var changeLayer = function changeLayer(ev) {
var val = $(this).val();
var checked = $(this).is(':checked');
map.getLayers().forEach(function (layer) {
if (layer.get('label') === val) {
layer.setVisible(checked);
}
});
};
$('input').each(function (){ $(this).on('change', changeLayer); });
</script>
</body>
</html>
Can anybody help me with this.
The above requirement worked when I added the below given code snippet.
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
var overlay = new ol.Overlay({
element: container,
autoPan: true,
autoPanAnimation: {
duration: 250
}
});
closer.onclick = function() {
overlay.setPosition(undefined);
closer.blur();
return false;
};
map.addOverlay(overlay);
map.on('singleclick', function(evt) {
var view = map.getView();
var viewResolution = /** #type {number} */ (map.getView().getResolution());
var url = tiledOSM.getSource().getGetFeatureInfoUrl(evt.coordinate, view.getResolution(), view.getProjection(), {
'INFO_FORMAT': 'application/json',
'PIXELRADIUS': 5,
'FEATURE_COUNT': 10
});
if (url) {
var parser = new ol.format.GeoJSON();
$.ajax({
url: url,
crossOrigin: true,
dataType: 'json',
jsonpCallback: 'parseResponse'
}).then(function(response) {
var result = parser.readFeatures(response);
if (result.length) {
var info = [];
for (var i = 0, ii = result.length; i < ii; ++i) {
info.push(result[i].get('Map_No'));
}
content.innerHTML =info.join;
}
});
}
overlay.setPosition(evt.coordinate);
});
Hence,I am marking this as answer.

On Click not updating the output of a function

$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
changeUnits();
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
I am trying to use a button on click event to change the temp display, but it doesn't seem to work like this. The function keeps seeing Celsius no matter what. I tried $(this).html too. The text of the button is actually changing, just the function isn't updating. I tried running the change units function inside the the button click even as well and it still doesn't update.
What am I not understanding about this onclick event and how can I get it to work.
JS Code:
var apiKey = "get your own key from http://openweathermap.org";
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
changeUnits();
});
$(function() {
var loc;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
//weather API call
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
function(weather) {
var currentLocation = weather.name;
var currentConditions = weather.weather[0].description;
var currentTemp = changeUnits(weather.main.temp);
var high = changeUnits(weather.main.temp_max);
var low = changeUnits(weather.main.temp_min);
var currentWind = weather.wind.speed;
var currentWdir = weather.wind.deg;
var sunRise = weather.sys.sunrise;
var sunSet = weather.sys.sunset;
var icon = weather.weather[0].icon;
//set HTML elements for weather info
$('#currentLocation').append(currentLocation);
$('#currentTemp').html(currentTemp);
$('#high-low').html('<span id="high">High: ' + high + '</span><br>'
+ '<span id="low">Low: ' + low + '</span>');
$('#currentConditions').html(currentConditions);
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
});
});
});
HTML:
<html>
<head>
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
<title></title>
</head>
<body>
<div id="header">
<div class="left"><h1 id="currentLocation">Your Current Location is </h1></div>
<div class="navbar"></div>
<div class="right"><i class="fa fa-github bigger_icon"></i></div>
</div>
<div id="container">
<h2 class="text-center content-title" id="currentTemp"></h2>
<div class="content-body text-center">
<p id="high-low"></p>
<button data-text-swap="Fahrenheit" id="unitButton" type="button" class="btn btn-success">Celsius</button>
<p id="currentConditions"></p>
</div>
</div>
</body>
</html>
I have done every change I can think of. console.log(el.text()) in the onclick clearly shows the text changing; but the function for changeUnits never seems to pick it up in the if statement when I run the function again during the onclick.
Looks like you're using html() instead of text(). I assume you're looking for button text instead of html, so try this:
$('.btn').on("click", function() {
$(this).text(function(f, c) {
return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
});
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius'){
return Math.round(Temp - 273.15) + " &degC";
}else{
return Math.round((Temp* (9/5)) - 459.67) + " &degF";
}
}
you are not calling the function, read comments in code
Also you are not passing any information to the '.btn' in the function passed to the text method.
$('.btn').on("click", function() {
var text = function(f, c) { // where are you getting your f and c parameters?
console.log(f); // should be undefined
console.log(c); // should be undefined
return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
}();
console.log(text); // should be 'Celsius'
$(this).text(text); // changed from }) to }())
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius') // change html() to text() as well
return Math.round(Temp - 273.15) + " &degC";
else
return Math.round((Temp* (9/5)) - 459.67) + " &degF";
}
Additionaly you should use a ID to associate your button to do this
<input id='thisID'>
// then call it in javascript
$("#thisID")
Toggleing the button
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
});
Here is what I think is your problem. I didn't get to test it because I need to get the weather API and stuff. By looking at your code, here is what I get.
When the page loads, you are getting weather data from OpenWeatherMap. However, you are not cashing this info in some sort of global variable in order for you to access it later. You have declared all your variables inside the ajax callback and you have no way of accessing them later.
Try to do this:
var currentTemp;
var high;
var low;
$(function() {
var loc;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
//weather API call
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
function(weather) {
var currentLocation = weather.name;
var currentConditions = weather.weather[0].description;
currentTemp = weather.main.temp;
high = weather.main.temp_max;
low = weather.main.temp_min;
var currentWind = weather.wind.speed;
var currentWdir = weather.wind.deg;
var sunRise = weather.sys.sunrise;
var sunSet = weather.sys.sunset;
var icon = weather.weather[0].icon;
//set HTML elements for weather info
$('#currentLocation').append(currentLocation);
updateDisplay();
$('#currentConditions').html(currentConditions);
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
});
});
});
function changeUnits(Temp) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
updateDisplay();
});
function updateDisplay(){
$('#currentTemp').html(changeUnits(currentTemp));
$('#high-low').html('<span id="high">High: ' + changeUnits(high) + '</span><br>'
+ '<span id="low">Low: ' + changeUnits(low) + '</span>');
}
I have introduced another function updateDisplay() to actually handle the changing of the displayed temps. As I said, I didn't get to test it. But I am pretty sure it will work.
JS:
var apiKey="get an openweathermap APIKey";
var loc;
var lat;
var long;
var temp;
var high;
var low;
var icon;
//var wind;
//var windDir;
//var windSpd;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
lat = parseFloat(loc[0]);
long = parseFloat(loc[1]);
getWeather(lat, long);
initGmaps(lat, long);
});
//api call to use lat and long to generate a map
window.addEventListener('load', function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '?key=AIzaSyDKgEmSnYmFmbhQVGY8K6NXxV5ym2yZXdc&callback=initMap';
document.body.appendChild(script);
});
function initGmaps(lat, long) {
var map = new GMaps({
div: '#map',
lat: lat,
lng: long,
zoom: 14,
disableDefaultUI: true,
mapTypeId: "satellite",
});
map.addMarker({
lat: lat,
lng: long
});
}
//using weather to get data and plug it into our page
function getWeather(lat, long) {
var api = 'http://api.openweathermap.org/data/2.5/weather?lat=' +
lat + '&lon=' + long + '&appid=' + apiKey;
$.ajax({
url: api,
dataType: 'json',
success: function(data) {
temp = {
f: Math.round(((data.main.temp * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp - 273.15)) * 100) / 100 + " °C"
};
high = {
f: Math.round(((data.main.temp_max * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
};
low = {
f: Math.round(((data.main.temp_min * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
};
windSpd = {
f: Math.round((data.wind.speed * 2.23694)*10)/10 + " MPH",
c: Math.round((data.wind.speed)*10)/10 + " M/S"
};
var windArr = ["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];
var windDir = windArr[Math.floor(((data.wind.deg/22.5)+.5))];
$('#currentLocation').append(data.name);
$('#high').append(" " + high.f);
$('#low').append(" " + low.f);
$('#currentTemp').html(temp.f);
$('#weatherDesc').html(data.weather[0].description);
$('#windDir').html(windDir);
$('#windDir').append('<span id="windSpd">' + windSpd.f + '</span>');
icon = data.weather[0].icon;
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').html('<img id="weatherImg" src="' + iconSrc + '"><br>');
}
});
}
$('#currentTemp').on('click', function() {
var current = $(this).data('nexttemp');
$('#currentTemp').text(temp[current]);
$('#high').html(high[current]);
$('#low').html(low[current]);
$('#windSpd').html(windSpd[current]);
if (current == 'c') {
$(this).data('nexttemp', 'f');
return;
}
$(this).data('nexttemp', 'c');
});
HTML:
<html>
<head>
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
<title></title>
</head>
<body>
<div id="header">
<div class="left"></div>
<div class="navbar"><h4>Free Code Camp Weather App</h4></div>
<div class="right"><i class="fa fa-github bigger_icon"></i></div>
</div>
<div id="container">
<div class="col-lg-4" id="map"></div>
<div class="col-lg-4">
<h1 id="currentLocation">Your Current Location is </h1>
</div>
<h2 class="center-text content-title" id="currentTemp"></h2>
<h3 id="caption">Click temperature to change Units</h3>
<div class="center-text">
<p class="oneLine" id="labels">High: <span id="high"></span></p>
<p class="oneLine" id="labels">Low: <span id="low"></span></p>
</div>
<p class="center-text" id="currentConditions"></p>
<p class="center-text" id="weatherDesc"></p>
<div class="windCompass col-lg-4">
<div class="compass">
<div class="direction">
<p id="windDir"></p>
</div>
<div class="arrow ne"></div>
</div>
</div>
</div>
</body>
</html>
CSS:
#import url(http://fonts.googleapis.com/css?family=Dosis:200,400,500,600);
body {
background: url(http://eskipaper.com/images/pixel-backgrounds-1.jpg);
background-size: auto;
background-repeat: no-repeat;
font-family: Ranga, cursive;
}
h4 {
margin-top: 7px;
}
h1 {
margin-left: -7px;
font-size: 1.05em;
color: white;
}
#header {
background: #2980b9;
color: white;
padding: 0 5px;
display: inline-block;
width: 100%;
margin: 0;
box-shadow: 0 2px 5px #555555;
}
#header .left {
display: inline-block;
width: auto;
float: left;
margin-top: 7px;
margin-left: 7px;
}
#header .navbar {
display: inline-block;
width: 60%;
}
#header .right {
display: inline-block;
width: auto;
text-align: right;
float: right;
margin-top: 2px;
margin-right: 7px;
vertical-align: bottom;
}
.bigger_icon {
margin-top: 10px;
font-size: 2em;
color: white;
}
#map {
height: 200px;
width: 200px;
border-radius: 5%;
margin-top: 20px;
}
#container {
background: rgba(66, 66, 66, 0.6);
display: block;
position: relative;
width: 40%;
margin: 24px auto;
min-height: 300px;
padding: 16px;
border-radius: 4px;
}
#container .center-text {
text-align: center;
}
h2 {
color: white;
font-family: Ranga, cursive;
font-size: 2.5em;
font-weight: bold;
margin-top: -230px;
}
#caption {
font-size: 17px;
text-align: center;
color: pink;
}
#labels {
color: darkGrey;
font-size: 1.5em;
}
.oneLine {
color: darkGrey;
font-size: 1.5em;
text-align: center;
display: inline;
padding: 5px;
}
#high {
text-align: center;
color: orange;
}
#low {
text-align: center;
color: blue;
}
#currentConditions {
text-align: center;
color: black;
}
#weatherDesc {
margin-top: -25px;
color: white;
}
.windCompass {
margin-left: 75%;
margin-top: -20%;
}
.compass {
display: block;
width: 120px;
height: 120px;
border-radius: 100%;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.85);
position: relative;
font-family: 'Dosis';
color: #555;
text-shadow: 1px 1px 1px white;
}
.compass:before {
font-weight: bold;
position: absolute;
text-align: center;
width: 100%;
content: "N";
font-size: 14px;
top: -2px;
}
.compass .direction {
height: 100%;
width: 100%;
display: block;
background: #f2f6f5;
background: -moz-linear-gradient(top, #f2f6f5 30%, #cbd5d6 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f2f6f5), color-stop(100%, #cbd5d6));
background: -webkit-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
background: o-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
border-radius: 100%;
}
.compass .direction p {
text-align: center;
margin: 0;
padding: 0;
position: absolute;
top: 50%;
left: 0;
width: 100%;
height: 100%;
line-height: 80px;
display: block;
margin-top: -35%;
font-size: 28px;
font-weight: bold;
}
.compass .direction p span {
display: block;
line-height: normal;
margin-top: -10%;
font-size: 17px;
text-transform: uppercase;
font-weight: normal;
font-family: Ranga, cursive;
}
.compass .arrow {
width: 100%;
height: 100%;
display: block;
position: absolute;
top: 0;
}
.compass .arrow:after {
content: "";
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 10px solid red;
position: absolute;
top: -6px;
left: 50%;
margin-left: -5px;
z-index: 99;
}
.compass .arrow.nne {
transform: rotate(22.5deg);
}
.compass .arrow.ne {
transform: rotate(45deg);
}
.compass .arrow.ene {
transform: rotate(67.5deg);
}
.compass .arrow.e {
transform: rotate(90deg);
}
.compass .arrow.ese {
transform: rotate(112.5deg);
}
.compass .arrow.se {
transform: rotate(135deg);
}
.compass .arrow.sse {
transform: rotate(157.5deg);
}
.compass .arrow.s {
transform: rotate(180deg);
}
.compass .arrow.ssw {
transform: rotate(202.5deg);
}
.compass .arrow.sw {
transform: rotate(-135deg);
}
.compass .arrow.wsw {
transform: rotate(-114.5deg);
}
.compass .arrow.w {
transform: rotate(-90deg);
}
.compass .arrow.wnw {
transform: rotate(-69.5deg);
}
.compass .arrow.nw {
transform: rotate(-45deg);
}
.compass .arrow.nnw {
transform: rotate(-24.5deg);
}
I ended up finding some Ajax and working with it to do what I expected the button to do. While not a button, it does what is intended. I also worked in changing the high, low, and wind speed to also change with the unit change.
I appreciate the help that everyone offered.
feel free to offer suggestions on the code as well for fixing the css for the compass gradient and making the stupid thing more responsive if you'd like. (The Map is not doing the responsive thing.
Your script probably gets loaded before the DOM is ready.
What you want to do here is one of a few options:
1. Load the JS script tag at the end of the body.
2. Wrap your $('.btn').on(...) function with document.on('ready') event, so this code will only be triggered when the DOM is ready.

Adding an extra two variables to a count simulator function

I've created the following fiddle https://jsfiddle.net/jnoweb/v421zzbe/2/
At the moment it has one variable which makes all three IDs count up to 20:
var game = {score:0},
scoreDisplay = [
document.getElementById("score1"),
document.getElementById("score2"),
document.getElementById("score3")];
function add20() {
TweenLite.to(game, 1, {score:"+=20", roundProps:"score", onUpdate:updateHandler, ease:Linear.easeNone});
}
function updateHandler() {
scoreDisplay.forEach(function(display) {
display.innerHTML = game.score;
});
}
add20();
I want to change this so that each ID counts to a different value, for example 16, 18 and 20!
Does anyone know how to achieve this?
Here is the more elegant, generic, configurable solution.
function ScoreDisplay(id, increment) {
this.elm = document.getElementById(id);
this.inc = increment;
this.game = {score: 0};
}
ScoreDisplay.prototype = {
update: function(){
this.elm.innerHTML = this.game.score;
}
};
var scoreDisplay = [];
scoreDisplay.push(new ScoreDisplay('score1', 16));
scoreDisplay.push(new ScoreDisplay('score2', 18));
scoreDisplay.push(new ScoreDisplay('score3', 20));
function addScore() {
scoreDisplay.forEach(function(sd) {
TweenLite.to(sd.game, 1, {score: "+=" + sd.inc, roundProps:"score", onUpdate:sd.update.bind(sd), ease:Linear.easeNone});
});
}
addScore();
#score1 {
position: relative;
font-size: 30px;
font-weight: bold;
padding: 20px;
text-align: center;
background-color: transparent;
color: $white;
border-radius: 20px 20px;
top: -11px;
left: -42px;
}
#score2 {
position: relative;
font-size: 30px;
font-weight: bold;
padding: 20px;
text-align: center;
background-color: transparent;
color: $white;
border-radius: 20px 20px;
top: -11px;
left: -42px;
}
#score3 {
position: relative;
font-size: 30px;
font-weight: bold;
padding: 20px;
text-align: center;
background-color: transparent;
color: $white;
border-radius: 20px 20px;
top: -11px;
left: -42px;
}
<!--TweenLite/TweenMax GSAP-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/CSSPlugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/easing/EasePack.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenLite.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TimelineLite.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/RoundPropsPlugin.min.js"></script>
<div id="prodArrow"></div>
<div id="prodCount">
<div id="score1"></div>
</div>
<div id="testArrow"></div>
<div id="testCount">
<div id="score2"></div>
</div>
<div id="devArrow"></div>
<div id="devCount">
<div id="score3"></div>
</div>
var game = {
score1: 0,
score2: 0,
score3: 0
},
scoreDisplay = [
document.getElementById("score1"),
document.getElementById("score2"),
document.getElementById("score3")
];
function add(scoreIndex, numToAdd) {
TweenLite.to(game, 1, {score:("+="+numToAdd), roundProps: ("score" + scoreIndex), onUpdate:updateHandler, ease:Linear.easeNone});
}
function updateHandler() {
scoreDisplay.forEach(function(display, i) {
var key = ("score" + (i+1))
display.innerHTML = game[key];
});
}
add(1 , 16);
add(2 , 18);
add(3 , 20);
What about this ?
var game = {
score1:0,
score2:0,
score3:0
},
scoreDisplay = [
document.getElementById("score1"),
document.getElementById("score2"),
document.getElementById("score3")];
function add20() {
TweenLite.to(game, 1, {score1:"+=16", score2:"+=18", score3:"+=20", roundProps:"score", onUpdate:updateHandler, ease:Linear.easeNone});
}
function updateHandler() {
scoreDisplay.forEach(function(display, key) {
var score = scoreDisplay[key].id;
display.innerHTML = game[score];
});
}
add20();
https://jsfiddle.net/hundma4g/

print the selected options from the jquery plugin

I'm trying to use a Jquery movie seat selection plugin on my jsp website. The plugin works well and i can able to select the seat.
My problem is, since i don't know Jquery i could not able to print the user selected seat on my jsp page.
kindly help me to print the users selected seat on jsp page. So that i can use them to store on my derby database.
HTML
<div class="demo">
<div id="seat-map">
<div class="front">SCREEN</div>
</div>
<div class="booking-details">
<p>Seat: </p>
<ul id="selected-seats"></ul>
<p>Tickets: <span id="counter">0</span></p>
<p>Total: <b>Rs.<span id="total">0</span></b></p>
<input type="button" value="BUY" class="checkout-button"/>
<div id="legend"></div>
</div>
<div style="clear:both"></div>
Jquery :
</style>
<script>
var price = 120; //price
$(document).ready(function() {
var $cart = $('#selected-seats'), //Sitting Area
$counter = $('#counter'), //Votes
$total = $('#total'); //Total money
var sc = $('#seat-map').seatCharts({
map: [ //Seating chart
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
],
naming : {
top : false,
getLabel : function (character, row, column) {
return column;
}
},
legend : { //Definition legend
node : $('#legend'),
items : [
[ 'a', 'available', 'Avail' ],
[ 'a', 'unavailable', 'Sold']
]
},
click: function () { //Click event
if (this.status() == 'available') { //optional seat
$('<li>R'+(this.settings.row+1)+' S'+this.settings.label+'</li>')
.attr('id', 'cart-item-'+this.settings.id)
.data('seatId', this.settings.id)
.appendTo($cart);
$counter.text(sc.find('selected').length+1);
$total.text(recalculateTotal(sc)+price);
return 'selected';
} else if (this.status() == 'selected') { //Checked
//Update Number
$counter.text(sc.find('selected').length-1);
//update totalnum
$total.text(recalculateTotal(sc)-price);
//Delete reservation
$('#cart-item-'+this.settings.id).remove();
//optional
return 'available';
} else if (this.status() == 'unavailable') { //sold
return 'unavailable';
} else {
return this.style();
}
}
});
//sold seat
sc.get(['1_2', '4_4','4_5','6_6','6_7','8_5','8_6','8_7','8_8', '10_1', '10_2']).status('unavailable');
});
//sum total money
function recalculateTotal(sc) {
var total = 0;
sc.find('selected').each(function () {
total += price;
});
return total;
}
</script>
CSS:
<style>
.front{width: 300px;margin: 5px 32px 45px 32px;background-color: #f0f0f0; color: #666;text-align: center;padding: 3px;border-radius: 5px;}
.booking-details {float: right;position: relative;width:200px;height: 450px; }
.booking-details h3 {margin: 5px 5px 0 0;font-size: 16px;}
.booking-details p{line-height:26px; font-size:16px; color:#999}
.booking-details p span{color:#666}
div.seatCharts-cell {color: #182C4E;height: 25px;width: 25px;line-height: 25px;margin: 3px;float: left;text-align: center;outline: none;font-size: 13px;}
div.seatCharts-seat {color: #fff;cursor: pointer;-webkit-border-radius:5px;- moz-border-radius:5px;border-radius: 5px;}
div.seatCharts-row {height: 35px;}
div.seatCharts-seat.available {background-color: #B9DEA0;}
div.seatCharts-seat.focused {background-color: #76B474;border: none;}
div.seatCharts-seat.selected {background-color: #E6CAC4;}
div.seatCharts-seat.unavailable {background-color: #472B34;cursor: not-allowed;}
div.seatCharts-container {border-right: 1px dotted #adadad;width: 400px;padding: 20px;float: left;}
div.seatCharts-legend {padding-left: 0px;position: absolute;bottom: 16px;}
ul.seatCharts-legendList {padding-left: 0px;}
.seatCharts-legendItem{float:left; width:90px;margin-top: 10px;line-height: 2;}
span.seatCharts-legendDescription {margin-left: 5px;line-height: 30px;}
.checkout-button {display: block;width:80px; height:24px; line- height:20px;margin: 10px auto;border:1px solid #999;font-size: 14px; cursor:pointer}
#selected-seats {max-height: 150px;overflow-y: auto;overflow-x: none;width: 200px;}
#selected-seats li{float:left; width:72px; height:26px; line-height:26px; border:1px solid #d3d3d3; background:#f7f7f7; margin:6px; font-size:14px; font- weight:bold; text-align:center}
</style>
Please Help!
Thanks.
I may suggest you to use the jQuery dialog plugin (dialog), plus jsPDF in order to produce a dialog on a print button containing a pdf version of the html related to your selected seat.
The result is like:
The snippet is:
var price = 120; //price
var sc;
//sum total money
function recalculateTotal(sc) {
var total = 0;
sc.find('selected').each(function () {
total += price;
});
return total;
}
$(function () {
var $cart = $('#selected-seats'), //Sitting Area
$counter = $('#counter'), //Votes
$total = $('#total'); //Total money
sc = $('#seat-map').seatCharts({
map: [ //Seating chart
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
],
naming: {
top: false,
getLabel: function (character, row, column) {
return column;
}
},
legend: { //Definition legend
node: $('#legend'),
items: [
['a', 'available', 'Avail'],
['a', 'unavailable', 'Sold']
]
},
click: function () { //Click event
if (this.status() == 'available') { //optional seat
$('<li>R' + (this.settings.row + 1) + ' S' + this.settings.label + '</li>')
.attr('id', 'cart-item-' + this.settings.id)
.data('seatId', this.settings.id)
.appendTo($cart);
$counter.text(sc.find('selected').length + 1);
$total.text(recalculateTotal(sc) + price);
return 'selected';
} else if (this.status() == 'selected') { //Checked
//Update Number
$counter.text(sc.find('selected').length - 1);
//update totalnum
$total.text(recalculateTotal(sc) - price);
//Delete reservation
$('#cart-item-' + this.settings.id).remove();
//optional
return 'available';
} else if (this.status() == 'unavailable') { //sold
return 'unavailable';
} else {
return this.style();
}
}
});
//sold seat
sc.get(['1_2', '4_4', '4_5', '6_6', '6_7', '8_5', '8_6', '8_7', '8_8', '10_1', '10_2']).status('unavailable');
$(':button[value="PRINT"]').on('click', function(e) {
e.preventDefault();
if ($('#selected-seats li').length > 0) {
var doc = new jsPDF();
var specialElementHandlers = {
'#selected-seats': function(element, renderer){
return true;
}
};
doc.fromHTML($('#selected-seats').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
var uriPdf = doc.output('datauristring');
$('<div>').prop('id', '_currentDialog').add('<iframe id="_myPdf" type="application/pdf" src="' + uriPdf + '"></iframe>').dialog({
title: "Selected seat",
width: 600,
height: 800,
close: function (event, ui) {
$('#_currentDialog').remove();
}
});
} else {
alert('No selected seat to print!')
}
});
});
.front {
width: 300px;
margin: 5px 32px 45px 32px;
background-color: #f0f0f0;
color: #666;
text-align: center;
padding: 3px;
border-radius: 5px;
}
.booking-details {
float: right;
position: relative;
width: 200px;
height: 450px;
}
.booking-details h3 {
margin: 5px 5px 0 0;
font-size: 16px;
}
.booking-details p {
line-height: 26px;
font-size: 16px;
color: #999
}
.booking-details p span {
color: #666
}
div.seatCharts-cell {
color: #182C4E;
height: 25px;
width: 25px;
line-height: 25px;
margin: 3px;
float: left;
text-align: center;
outline: none;
font-size: 13px;
}
div.seatCharts-seat {
color: #fff;
cursor: pointer;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
div.seatCharts-row {
height: 35px;
}
div.seatCharts-seat.available {
background-color: #B9DEA0;
}
div.seatCharts-seat.focused {
background-color: #76B474;
border: none;
}
div.seatCharts-seat.selected {
background-color: #E6CAC4;
}
div.seatCharts-seat.unavailable {
background-color: #472B34;
cursor: not-allowed;
}
div.seatCharts-container {
border-right: 1px dotted #adadad;
width: 400px;
padding: 20px;
float: left;
}
div.seatCharts-legend {
padding-left: 0px;
position: absolute;
bottom: 16px;
}
ul.seatCharts-legendList {
padding-left: 0px;
}
.seatCharts-legendItem {
float: left;
width: 90px;
margin-top: 10px;
line-height: 2;
}
span.seatCharts-legendDescription {
margin-left: 5px;
line-height: 30px;
}
.checkout-button {
display: inline;
width: 80px;
height: 24px;
line-height: 20px;
margin: 10px auto;
border: 1px solid #999;
font-size: 14px;
cursor: pointer
}
#selected-seats {
max-height: 150px;
overflow-y: auto;
overflow-x: none;
width: 200px;
}
#selected-seats li {
float: left;
width: 72px;
height: 26px;
line-height: 26px;
border: 1px solid #d3d3d3;
background: #f7f7f7;
margin: 6px;
font-size: 14px;
font- weight: bold;
text-align: center
}
#_myPdf {
width: 100% !important;
}
<link href="js/jquery.seat-chart/jquery.seat-charts.css" rel="stylesheet">
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="js/jquery.seat-chart/jquery.seat-charts.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<div class="demo">
<div id="seat-map">
<div class="front">SCREEN</div>
</div>
<div class="booking-details">
<p>Seat: </p>
<ul id="selected-seats"></ul>
<p>Tickets: <span id="counter">0</span></p>
<p>Total: <b>Rs.<span id="total">0</span></b></p>
<input type="button" value="BUY" class="checkout-button"/>
<input type="button" value="PRINT" class="checkout-button"/>
<div id="legend"></div>
</div>
<div style="clear:both"></div>
</div>
The function to print in the html with jquery is "html()" for example if you want to write in the div with the id legend you can do this:
$("#legend").html("<p>whatever you want to write</p>");
You can find more details on this page
w3schools tutorial
Hope it help

Categories