getUserMedia recording do not stop after wait on mdn example - getusermedia

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!

Related

How to anchor position popup to left screen in 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);
});

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>

SSL configuration issue with RabbitMQ Web-Stomp Plugin

Firstly, I followed this to generate keys, certificates and CA certificates to directories which are client, server and testca. Then I verified, SSL works.
Then I followed this to configure RabbitMQ Web-Stomp Plugin, and my ssl_config is as following:
[
{rabbitmq_web_stomp,
[{ssl_config, [{port, 15671},
{backlog, 1024},
{certfile, "path/to/certs/client/cert.pem"},
{keyfile, "path/to/certs/client/key.pem"},
{cacertfile, "path/to/certs/testca/cacert.pem"},
{password, "changeme"}]}]}
].
However, when I tried to connect it via websockets by following code, which is copied from here, and I made some modifications.
<!DOCTYPE html>
<html><head>
<script src="jquery.min.js"></script>
<script src="stomp.js"></script>
<style>
.box {
width: 440px;
float: left;
margin: 0 20px 0 20px;
}
.box div, .box input {
border: 1px solid;
-moz-border-radius: 4px;
border-radius: 4px;
width: 100%;
padding: 5px;
margin: 3px 0 10px 0;
}
.box div {
border-color: grey;
height: 300px;
overflow: auto;
}
div code {
display: block;
}
#first div code {
-moz-border-radius: 2px;
border-radius: 2px;
border: 1px solid #eee;
margin-bottom: 5px;
}
#second div {
font-size: 0.8em;
}
</style>
<title>RabbitMQ Web STOMP Examples : Echo Server</title>
<link href="main.css" rel="stylesheet" type="text/css"/>
</head><body lang="en">
<h1>RabbitMQ Web STOMP Examples > Echo Server</h1>
<div id="first" class="box">
<h2>Received</h2>
<div></div>
<form><input autocomplete="off" value="Type here..."></input></form>
</div>
<div id="second" class="box">
<h2>Logs</h2>
<div></div>
</div>
<script>
var has_had_focus = false;
var pipe = function(el_name, send) {
var div = $(el_name + ' div');
var inp = $(el_name + ' input');
var form = $(el_name + ' form');
var print = function(m, p) {
p = (p === undefined) ? '' : JSON.stringify(p);
div.append($("<code>").text(m + ' ' + p));
div.scrollTop(div.scrollTop() + 10000);
};
if (send) {
form.submit(function() {
send(inp.val());
inp.val('');
return false;
});
}
return print;
};
// Stomp.js boilerplate
var client = Stomp.client('wss://192.168.111.131:15671/ws');
client.debug = pipe('#second');
var print_first = pipe('#first', function(data) {
client.send('/queue/webstomp', {"content-type":"text/plain"}, data);
});
var on_connect = function(x) {
id = client.subscribe("/queue/webstomp", function(d) {
print_first(d.body);
});
};
var on_error = function() {
console.log('error');
};
client.connect('test', 'test', on_connect, on_error, '/');
$('#first input').focus(function() {
if (!has_had_focus) {
has_had_focus = true;
$(this).val("");
}
});
</script>
</body></html>
it replied me that I lost connection as following screenshot.
I'd be really appreciate any helpful suggestion on this issue.
BTW: this code example works when I didn't use SSL.
Finally I figured this out by referring this post, so the key point is to explicitly authorized my certificate by visiting the address in https first, in my case is wss://192.168.111.131:15671/ws. So I need to visit https://192.168.111.131:15671/ws in browser and authorize the exception and then I can make my wss connection normally.

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).

Disable right-click menu on WebView

Well, this is exactly what I need to do :
When the user right-clicks on a WebView, the typical menu (without "reload",etc) should not show up.
How can this be done? Any ideas?
P.S. Also : is it possible that a custom menu is shown?
It is simple to prevent the context menu with html:
<body oncontextmenu="return false;">
or with javascript (jquery):
$(document).bind(“contextmenu”, function (e) {
e.preventDefault();
});
Or, if you want to show a custom html context menu using javascript...
HTML:
<div id="context-menu">
<ul>
<li>Item1</li>
<li>Item2</li>
<li>Item3</li>
</ul>
</div>
<div id="op">Right click anywhere!</div>
CSS:
#context-menu {
display: none;
position: fixed;
border: 1px solid #ddd;
background: white;
box-shadow: 2px 2px 1px grey;
}
#context-menu ul {
list-style: none;
padding: 0;
margin: 0;
}
#context-menu li {
width:150px;
padding: 5px 8px;
}
#context-menu li:hover {
background:#eaeaea;
cursor:pointer;
}
JS:
function startFocusOut() {
$(document).on("click", function () {
$("#context-menu").fadeOut(20); // To hide the context menu
$(document).off("click");
});
}
$(function(){
$(document).bind("contextmenu", function (e) {
e.preventDefault(); // To prevent the default context menu.
$("#context-menu").css("left", e.pageX); // position with cursor
$("#context-menu").css("top", e.pageY);
$("#context-menu").fadeIn(20, startFocusOut()); // show the menu
});
$("#context-menu li").click(function () {
$("#op").text("You have selected " + $(this).text()); // Performing the selected function.
});
});
Jsfiddle: http://jsfiddle.net/VRy93/