How to anchor position popup to left screen in openlayers 6 - openlayers-6

I have a popup when click to layer on map and popup displayed at selected position. I want to show popup to left screen, how can i do that. Please help me, my english not good. Thanks
My popup show like this
Popup here
I want when click popup will show left screen, not center

If you want the popup on center left, you could do it like this:
<html>
<head>
<meta charset="utf-8" />
<style>
.map {
height: 100%;
width: 100%;
}
html,
body {
height: 100%
}
.ol-popup {
background-color: white;
box-shadow: 0 1px 4px rgba(0,0,0,0.2);
padding: 15px;
border-radius: 10px;
border: 1px solid #cccccc;
bottom: 12px;
min-width: 280px;
}
.ol-popup:after {
border-top-color: white;
border-width: 10px;
left: 48px;
margin-left: -10px;
}
.ol-popup:before {
border-top-color: #cccccc;
border-width: 11px;
left: 48px;
margin-left: -11px;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.13.0/build/ol.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.13.0/css/ol.css">
</head>
<body>
<div id="popup" class="ol-popup">
<div id="popup-content"></div>
</div>
<div id="map" class="map"></div>
<script type="text/javascript">
const container = document.getElementById('popup');
const content = document.getElementById('popup-content');
document.addEventListener("DOMContentLoaded", function () {
drawMap();
});
function drawMap() {
const osmLayer = new ol.layer.Tile({
source: new ol.source.OSM({
attributions: '© OpenStreetMap',
})
});
map = new ol.Map({
target: 'map',
layers: [
osmLayer,
],
view: new ol.View(),
});
const popup = new ol.Overlay({
element: document.getElementById('popup'),
});
map.addOverlay(popup);
map.getView().fit([0,0,0,0]);
map.on('click', function (evt) {
const element = popup.getElement();
const popupMap = popup.getMap();
const coordinate = evt.coordinate;
const viewExtent = popupMap.getView().calculateExtent();
const centerPoint = ol.extent.getCenter(viewExtent);
content.innerHTML = '<p>You clicked here:</p><code>' + coordinate + '</code>';
popup.setPosition( [viewExtent[0], centerPoint[1]] );
});
}
</script>
</body>
</html>
Remove position absolute and determine the position:
https://jsfiddle.net/ve5mn0by/5/
EDIT:
without Openlayers Overlay, just HTML:
map.on('click', function (evt) {
const container = document.createElement('div');
const content = document.createElement('div');
container.style.width = '10rem';
container.style.height = '100%'
//container.style.backgroundColor = '#FF0000';
container.style.position = 'absolute';
container.style.display = 'flex';
content.style.width = '100%';
content.style.height = '10rem'
content.style.backgroundColor = '#FFFF00';
content.style.alignSelf = 'center';
container.appendChild(content);
document.body.appendChild(container);
});

Related

react-native-webview and array list

I'm using react-native-webview and another page I can render a static webview like this:
return `<html>
<head>
<style>
.t-center{
text-align: center;
</style>
</head>
<body>
<div class="t-center">
<h1>GUIA DE AGENDAMENTO - ENTREGA</h1>
<h1>0000000</h1>
</div>
</body>
</html>`
But now I need to render a list of items from an array inside a webview. I tried using the map but it didn't work:
return items.map((item) => {
return `<html>
<head>
<style>
.t-center{
text-align: center;
</style>
</head>
<body>
<div class="t-center">
<h1>GUIA DE AGENDAMENTO - ENTREGA</h1>
<h1>${item.namE_CLI}</h1>
</div>
</body>
</html>`;
});
here is the solution where you can find the props value injectedJavaScript which helps to inject JavaScript to webview. sample code given below how to add array list to webview.
ex:
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';
const App = () => {
let myList = `["A", "B", "C", "D"]`;
const overrideJs = `
let $buttons = $('<div id="buttonGallery">');
let myList = ${myList}
let myColors = ["red", "green", "blue", "red"];
myList.map(function(letter, index) {
let $button = $("<div></div>")
.addClass("buttons")
.attr("id", "button_" + letter)
.html("<p>" + letter + "</p>")
.on("mouseenter", function() {
$(this).css("background", myColors[index]);
})
.on("mouseleave", function() {
if (!$(this).hasClass('clicked')) {
$(this).css("background", "transparent");
}
})
.on("click", function() {
$(this).css("background", myColors[index]);
$(this).addClass('clicked');
})
$buttons.append($button);
});
$("body").append($buttons);
$("#done").on("click", clearColor);
function clearColor() {
$(".buttons").css({
backgroundColor: 'transparent'
});
$(".buttons").removeClass('clicked');
}
`
const html = `<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style media="screen">
.buttons {
width: 150px;
height: 50px;
border: solid 2px black;
text-align: center;
color: black;
cursor: pointer;
background-color: white;
margin: 2px;
}
#buttonGallery {
margin: 10px;
padding: 10px;
border: solid 2px black;
width: 155px;
}
#done {
width: 150px;
height: 50px;
border: solid 2px black;
text-align: center;
color: black;
cursor: pointer;
background-color: white;
margin: 2px;
}
</style>
</head>
<body>
<div id="done">
<p>done</p>
</div>
</body>
</html>
`
return (
<View style={{ flex: 1, backgroundColor: 'red' }}>
<WebView
ref={(r) => this.webviewRef = r}
source={{ html }}
// onMessage={}
injectedJavaScript={overrideJs}
injectedJavaScriptForMainFrameOnly={false}
allowUniversalAccessFromFileURLs={true}
/>
</View>
)
};
export default App;
Thanks Virendrasinh R, your propose is very good! But I found a way to do this with map and toString():
const names = items.map(function (item) {
return `<div class="row"><span class="title">${item["idcont"]} - ${item["nomE_CLI"]}</span></div>
<div class="row"><strong>Tipo:</strong> ${item["tipO_CONHECIMENTO"]}</div>
<div class="row"><strong>ContĂȘiner:</strong> ${item["idcont"]}</div>
<div class="row"><strong>N:</strong> ${item["numerO_CE_MERCANTE"]}</div>
<div class="row"><strong>Status:</strong> ${item["status"]}</div>
<div class="row"><strong>Data Status:</strong> ${item["datA_STATUS"]}</div>
<div class="row"><strong>Data Prevista:</strong> ${item["dH_PREV_INSPECAO"]}</div>
<div class="row last-row"><strong>Data Descarga:</strong> ${item["dH_DESCARGA"]}</div>
`;
});
const html = `
<html>
<head>
<style>
body{
padding: 0 25px;
}
.row{
font-size: 38px;
border-bottom: 1px solid ${theme.color.gray};
padding: 10px;
}
.last-row{
margin-bottom: 50px;
}
.title{
color: ${theme.color.success};
font-size: 48px;
font-weight: bold;
}
strong{
color: ${theme.color.primary};
}
</style>
</head>
<body>${names.toString()}</body>
</html>
`;

How to add data to post from js using axios and express?

this is my html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
</head>
<body>
<style>
body {
background-color: #F5F5F5;
font-size: 20px;
font-family: 'Courier New', Courier, monospace;
}
input {
width: 10rem;
outline: none;
border: 1px solid #232323;
background: transparent;
border-radius: 5px;
padding: 4px 10px;
margin: 8px 0;
}
button {
display: block;
background-color: transparent;
border: 1px solid #232323;
padding: 4px 10px;
border-radius: 5px;
cursor: pointer;
transition: 450ms;
}
button:hover {
background-color: #232323;
color: #FFF;
}
form {
width: 300px;
margin: 20px auto;
}
.message {
color: red;
}
</style>
<form>
<input type="text" name="username">
<div class="form_alert"></div>
<button type="submit">submit</button>
</form>
<div class="result">
</div>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"
integrity="sha512-bZS47S7sPOxkjU/4Bt0zrhEtWx0y0CRkhEp8IckzK+ltifIIE9EMIMTuT/mEzoIMewUINruDBIR/jJnbguonqQ=="
crossorigin="anonymous"
></script>
<script>
let result = document.querySelector('.result');
function getData () {
return new Promise( async (resolve, reject)=> {
const {data} = await axios.get('/api/users');
if(data) {
const users = data.data.map(user => {
return `<h5>${user.name}</h5>`;
});
resolve(result.innerHTML = users.join(' '));
}else {
reject(result.innerHTML = '<span>no data to fetch</span>');
}
}).then((resolve)=>{return resolve}).catch(reject=>{return reject});
}
getData();
const btn = document.querySelector('button');
const input = document.querySelector('input');
const formAlert = document.querySelector('.form_alert');
btn.onclick = async (e)=> {
e.preventDefault();
const nameValue = input.value;
try {
const {data} = await axios.post('/api/users', {name: nameValue});
const nameElement = document.createElement('h5');
nameElement.textContent = data;
console.log(data.data)
result.appendChild(nameElement);
}catch(error) {
formAlert.textContent = 'error';
}
input.value = '';
}
</script>
</body>
</html>
This my app.js file:
const express = require('express');
const app = express();
const users = require('./data');
app.use(express.static('./views'));
app.use(express.urlencoded({extended: false}));
app.get('/api/users', (req, res)=> {
res.status(201).json({success: true, data: users});
})
app.post('/api/users', (req, res)=> {
res.status(201).send('Success!');
})
app.listen(4000, ()=> console.log('server running on http://localhost:4000'));
So I have an input and I want when I create a name this name will be insert to my post request using axios secondly I want to access this name and push it into the textContent of the h5 element.
But the problem is when I push it the browser show me the success! word instead of the name that I create it into my input.
What is the solution for my Question ?
this is the data file :
const users = [
{name:'adil', id:1},
{name:'issam', id:2},
{name:'safae', id:3},
{name:'yassmin', id:4},
{name:'iyad', id:5},
]
module.exports = users;
Inside the views folder I have my html and css file.

Turnjs display tcpdf output as flipbook using pdfjs in same file

I want to display tcpdf output as flipbook using pdfjs in same file.
Method 1: Using Turnjs only (tried as we do for blob image)-not successful
First, I get base64 from $pdf->Output('', 'E');. Then, I convert to blob and create url. The pdf file I created contain two pages. I could not preview in turnjs. After that, I passed url to div inside div with id(flipbook). But , There are no content shown in flipbook.
<?php
ob_start();
require_once('plugin/tcpdf/tcpdf.php');
$pdf =new TCPDF();
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$html_p1='Text messaging, or texting, is the act of composing and sending electronic messages, typically consisting of alphabetic and numeric characters, between two or more users of mobile devices, desktops/laptops, or other type of compatible computer. Text messages may be sent over a cellular network, or may also be sent via an Internet connection.';
//echo $html;
$pdf->writeHTML($html_p1, true, 0, true, 0);
$pdf->AddPage();
$html_p2='A telephone call is a connection over a telephone network between the called party and the calling party.';
$pdf->writeHTML($html_p2, true, 0, true, 0);
$base64PdfString = $pdf->Output('', 'E');
$base64PdfArray = explode("\r\n", $base64PdfString);
$base64 = '';
for($i = 5; $i < count($base64PdfArray); $i++)
{
$base64 .= $base64PdfArray[$i];
}
?>
<!doctype html>
<!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!--> <html lang="en"> <!--<![endif]-->
<head>
<meta name="viewport" content="width = 1050, user-scalable = no" />
<script type="text/javascript" src="plugin/turnjs4/extras/jquery.min.1.7.js"></script>
<script type="text/javascript" src="plugin/turnjs4/extras/modernizr.2.5.3.min.js"></script>
<script>
const b64toBlob = (b64Data, contentType='', sliceSize=512) =>
{
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize)
{
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++)
{
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
$( document ).ready(function() {
const contentType ='application/pdf';
const b64Data ='<?php echo $base64;?>';
const blob =b64toBlob(b64Data, contentType);
const blobUrl =URL.createObjectURL(blob);
var div_container = document.querySelector('#flipbook');
var element = document.createElement("div");
element.style.backgroundImage = "url(" + blobUrl + ")";
div_container.appendChild(element);
})
</script>
</head>
<body>
<div class="flipbook-viewport">
<div class="container">
<div class="flipbook" id="flipbook">
</div>
</div>
</div>
<script type="text/javascript">
function loadApp() {
// Create the flipbook
$('.flipbook').turn({
// Width
width:922,
// Height
height:600,
// Elevation
elevation: 50,
// Enable gradients
gradients: true,
// Auto center this flipbook
autoCenter: true
});
}
// Load the HTML4 version if there's not CSS transform
yepnope({
test : Modernizr.csstransforms,
yep: ['plugin/turnjs4/lib/turn.js'],
nope: ['plugin/turnjs4/lib/turn.html4.min.js'],
both: ['plugin/turnjs4/samples/basic/css/basic.css'],
complete: loadApp
});
</script>
</body>
</html>
Method 2: Using Pdf flipbook converter with turnjs and pdfjs libraries.-successful
I placed the url (php file output pdf to browser using tcpdf) as default url in viewer.js. This method could run successfully.
If possible , I want to combine turnjs with pdfjs in same file. After create tcpdf output, turnjs and pdfjs use that blob output within same file to display as flipbook.
Thank in advance.
Here is the solution!
Save 64bit format of tcpdf output $pdf->Output('', 'E') to variable $base64PdfString.
Explode $base64PdfString to array and get only base64 parts(value of index 5 onwards from the array).
Convert base64 to blob in javascript by atob(b64Data),new Uint8Array(byteNumbers) and new Blob(byteArrays, {type: contentType}).
Create blobUrl using URL.createObjectURL(blob).
Hardcode cover div as first page.
Create turnjs instance.page: 1 refer to page on load. So, could not define this before add page to turnjs.
$("#book").turn({
page: 1,
autoCenter: true,
});
Create list array and add page start from 2 to last page of pdf files using pdf_doc.numPages.
Add all pages to turnjs inside PDFJS.getDocument({ url: blobUrl }).then(function(pdf_doc){}).
a) Get page from pdf blob by pdf_doc.getPage((page-1)).then(function(p){}).
b) Create html element, canvas. Create renderContext(RenderContext encapsulates the information needed to produce a specific rendering from a RenderableImage) and add pag1.getContext('2d') of canvas to key, canvasContext of renderContext. Then, Render the pdf page on this by p.render(renderContext).then(function(){}).
<?php
ob_start();
require_once('plugin/tcpdf/tcpdf.php');
$pdf = new TCPDF();
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$html_p1 = 'Text messaging, or texting, is the act of composing and sending electronic messages, typically consisting of alphabetic and numeric characters, between two or more users of mobile devices, desktops/laptops, or other type of compatible computer. Text messages may be sent over a cellular network, or may also be sent via an Internet connection';
//echo $html;
$pdf->writeHTML($html_p1, true, 0, true, 0);
$pdf->AddPage();
$html_p2 = 'A telephone call is a connection over a telephone network between the called party and the calling party.';
$pdf->writeHTML($html_p2, true, 0, true, 0);
$base64PdfString = $pdf->Output('', 'E');
$base64PdfArray = explode("\r\n", $base64PdfString);
$base64 = '';
for($i = 5; $i < count($base64PdfArray); $i++){
$base64 .= $base64PdfArray[$i];
}
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js">
</script>
<script type="text/javascript" src="plugin/turnjs4/lib/turn.min.js">
</script>
<script type="text/javascript" src="plugin/pdfjs_ex/pdf.js">
</script>
<script>
const b64toBlob = (b64Data, contentType='', sliceSize=512) =>
{
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize)
{
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++)
{
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
function addPage(page, book, pdf_doc)
{
if (!book.turn('hasPage', page))
{
var element = $('<div />', {'class': 'page '+((page%2==0) ? 'odd' : 'even'), 'id': 'page-'+page}).html('<i class="loader"></i>');
book.turn('addPage', element, page);
pdf_doc.getPage((page-1)).then(function(p)
{
var scale = 1;
var viewport = p.getViewport(scale);
var pag1 =document.createElement('canvas');
pag1.id ='Pg_1';
var context1 =pag1.getContext('2d');
pag1.height =viewport.height;
pag1.width =viewport.width;
var renderContext =
{
canvasContext: context1,
viewport: viewport
};
p.render(renderContext).then(function()
{
pag1.toBlob(function(blob)
{
var burl =URL.createObjectURL(blob);
setTimeout(function()
{
element.html('<div style="background-image:url('+burl+'); width: 400px; height: 500px; background-size: cover;"></div><div style="top: 0px; left: 0px; overflow: hidden; z-index: 1; width: 461px; height: 600px;"></div>');
}, 1000);
})
})
})
}
}
</script>
<style type="text/css">
body
{
background: #ccc;
}
#book
{
width: 800px;
height: 500px;
}
#book .turn-page
{
background-color: white;
}
#book .cover
{
background: #333;
}
#book .cover h1
{
color: white;
text-align: center;
font-size: 50px;
line-height: 500px;
margin: 0px;
}
#book .loader
{
background-image: url(loader.gif);
width: 24px;
height: 24px;
display: block;
position: absolute;
top: 238px;
left: 188px;
}
#book .data
{
text-align: center;
font-size: 40px;
color: #999;
line-height: 500px;
}
#controls
{
width: 800px;
text-align: center;
margin: 20px 0px;
font: 30px arial;
}
#controls input, #controls label
{
font: 30px arial;
}
#book .odd
{
background-image: -webkit-linear-gradient(left, #FFF 95%, #ddd 100%);
background-image: -moz-linear-gradient(left, #FFF 95%, #ddd 100%);
background-image: -o-linear-gradient(left, #FFF 95%, #ddd 100%);
background-image: -ms-linear-gradient(left, #FFF 95%, #ddd 100%);
}
#book .even
{
background-image: -webkit-linear-gradient(right, #FFF 95%, #ddd 100%);
background-image: -moz-linear-gradient(right, #FFF 95%, #ddd 100%);
background-image: -o-linear-gradient(right, #FFF 95%, #ddd 100%);
background-image: -ms-linear-gradient(right, #FFF 95%, #ddd 100%);
}
</style>
</head>
<body>
<div id="book">
<div class="cover">
<h1>
Cover
</h1>
</div>
</div>
<!--<div id="controls">
<label for="page-number">
Page:
</label> <input type="text" size="3" id="page-number"> of
<span id="number-pages">
</span>
</div>-->
<script type="text/javascript">
$(window).ready(function()
{
const contentType ='application/pdf';
const b64Data ='<?php echo $base64;?>';
const blob =b64toBlob(b64Data, contentType);
const blobUrl =URL.createObjectURL(blob);
PDFJS.getDocument({ url: blobUrl }).then(function(pdf_doc)
{
__PDF_DOC = pdf_doc;
__TOTAL_PAGES = __PDF_DOC.numPages;
$("#book").turn({
page: 1,
/* width: 400,
height: 300,*/
autoCenter: true,
});
//addPage(2, $("#book"),pdf_doc);
var list = [];
for (var i = 1; i <= __TOTAL_PAGES; i++)
{
list.push(i+1);
}
for (page = 0; page<list.length; page++)
addPage(list[page], $("#book"),pdf_doc);
})
});
$(window).bind('keydown', function(e)
{
if (e.target && e.target.tagName.toLowerCase()!='input')
if (e.keyCode==37)
$('#book').turn('previous');
else if (e.keyCode==39)
$('#book').turn('next');
});
</script>
</body>
</html>

getUserMedia recording do not stop after wait on mdn example

This example using promises on mdn to grab/record video stream on fly, work fine until you click on Stop recording button, then all is correctly stopped, also audio/video hardware that will result off on browser: but if you let elapse the counter time, without clicking on the Stop button, you'll see that the example will not close the audio/video that will remain opened, like still recording (and the hardware result still engaged):
https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API/Recording_a_media_element
(the working example is on bottom of the same page or on codepen or jsfiddle as linked)
How it should be closed when wait function elapsed the time, without require a click into the Stop button? Anybody know if it is possible?
It is very possible. This is the code i've come up, now all is stopped, even if no click on button stop: the click is simulated in case.
Thank to this referral
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
the resulting (and working fine) code is just like this (complete to copy/paste as html file to test out):
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
font: 14px "Open Sans", "Arial", sans-serif;
}
video {
margin-top: 2px;
border: 1px solid black;
}
.button {
cursor: pointer;
display: block;
width: 160px;
border: 1px solid black;
font-size: 16px;
text-align: center;
padding-top: 2px;
padding-bottom: 4px;
color: white;
background-color: darkgreen;
text-decoration: none;
}
h2 {
margin-bottom: 4px;
}
.left {
margin-right: 10px;
float: left;
width: 160px;
padding: 0px;
}
.right {
margin-left: 10px;
float: left;
width: 160px;
padding: 0px;
}
.bottom {
clear: both;
padding-top: 10px;
}
</style>
</head>
<body>
<p>Click the "Start" button to begin video recording for a few seconds. You can stop
the video by clicking the creatively-named "Stop" button. The "Download"
button will download the received data (although it's in a raw, unwrapped form
that isn't very useful).
</p>
<br>
<div class="left">
<div id="startButton" class="button">
Start
</div>
<h2>Preview</h2>
<video id="preview" width="160" height="120" autoplay muted></video>
</div>
<div class="right">
<div id="stopButton" class="button">
Stop
</div>
<h2>Recording</h2>
<video id="recording" width="160" height="120" controls></video>
<a id="downloadButton" class="button">
Download
</a>
</div>
<div class="bottom">
<pre id="log"></pre>
</div>
<script>
let preview = document.getElementById("preview");
let recording = document.getElementById("recording");
let startButton = document.getElementById("startButton");
let stopButton = document.getElementById("stopButton");
let downloadButton = document.getElementById("downloadButton");
let logElement = document.getElementById("log");
let recordingTimeMS = 3000;
function log(msg) {
logElement.innerHTML += msg + "\n";
}
function wait(delayInMS) {
return new Promise(resolve => setTimeout(resolve, delayInMS));
}
function startRecording(stream, lengthInMS) {
let recorder = new MediaRecorder(stream);
let data = [];
recorder.ondataavailable = event => data.push(event.data);
recorder.start();
log(recorder.state + " for " + (lengthInMS/1000) + " seconds...");
recorder.addEventListener('dataavailable', function(event) {
console.log(recorder.state);
w3simulateClick(stopButton, 'click');
});
let stopped = new Promise((resolve, reject) => {
recorder.onstop = resolve;
recorder.onerror = event => reject(event.name);
});
let recorded = wait(lengthInMS).then(
() => recorder.state == "recording" && recorder.stop()
)
return Promise.all([
stopped,
recorded
])
.then(() => data);
}
function stop(stream) {
stream.getTracks().forEach(track => track.stop());
}
startButton.addEventListener("click", function() {
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(stream => {
preview.srcObject = stream;
downloadButton.href = stream;
preview.captureStream = preview.captureStream || preview.mozCaptureStream;
return new Promise(resolve => preview.onplaying = resolve);
}).then(() => startRecording(preview.captureStream(), recordingTimeMS))
.then (recordedChunks => {
let recordedBlob = new Blob(recordedChunks, { type: "video/webm" });
recording.src = URL.createObjectURL(recordedBlob);
downloadButton.href = recording.src;
downloadButton.download = "RecordedVideo.webm";
log("Successfully recorded " + recordedBlob.size + " bytes of " +
recordedBlob.type + " media.");
})
.catch(log);
}, false); stopButton.addEventListener("click", function() {
stop(preview.srcObject);
}, false);
function w3simulateClick(el) {
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
//var cb = document.getElementById('checkbox');
var cancelled = el.dispatchEvent(event);
if (cancelled) {
// A handler called preventDefault.
alert("cancelled");
} else {
// None of the handlers called preventDefault.
alert("not cancelled");
}
}
</script>
</body>
</html>
cheers to all cool people!

Google Maps API simple Debugging

I want to use the google maps API to:
-search for an address on a map
-place a marker on a map and drag it
Combining some pieces of code i came up with this (apparently it is not working). Can somebody pleasy debug me?:D
Thanks!
<!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: 50px;
padding: 0px
}
.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;
padding: 0 11px 0 13px;
width: 400px;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
text-overflow: ellipsis;
}
#pac-input:focus {
border-color: #4d90fe;
margin-left: -1px;
padding-left: 14px; /* Regular padding-left + 1. */
width: 401px;
}
.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&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);
});
}
function addMyMarker()
{ //function that will add markers on button click
var marker = new google.maps.Marker({
position:mapCenter,
map: map,
draggable:true,
animation: google.maps.Animation.DROP,
title:"This a new marker!",
icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#target {
width: 345px;
}
</style>
<script type="text/javascript">
function addMyMarker()
{ //function that will add markers on button click
var marker = new google.maps.Marker({
position:mapCenter,
map: map,
draggable:true,
animation: google.maps.Animation.DROP,
title:"This a new marker!",
icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
});
}
</script>
</head>
<body>
<button id="drop" onClick="addMyMarker()">Drop Markers</button>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map-canvas"></div>
</body>
</html>
First, make the map variable global, so you can access it from any function. Then make sure that you define the mapCenter (globally), like this:
new google.maps.LatLng(-33.8902, 151.1759)
Then make sure that you have only one addMyMarker function (just remove the second one).