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>
Related
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);
});
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.
I have to add a custon SVG file instead of the navigation icon from ArcGIS in the 'locate' widget ('esri-icon-locate'). Here the problem is, the default icon is appearing top of the custom svg file. Is there any way to hide the default icon?
view.when(_ => {
const n = document.getElementsByClassName("esri-icon-locate");
if (n && n.length === 1) {
n[0].classList += " mapnavigation"
}
});
and the css,
.mapnavigation:before{
display: block;
background: url('mapnavigation.svg');
background-repeat: no-repeat;
background-size: 17px 17px;
background-color: #ffffff;
}
You were really close to the solution, you just need to make it the only class of the node. Take a look at the example I put for you,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />
<title>Locate button | Sample | ArcGIS API for JavaScript 4.18</title>
<link rel="stylesheet" href="https://js.arcgis.com/4.18/esri/themes/light/main.css" />
<style>
html,
body,
#viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
.my-svg-icon {
background: url(https://openlayers.org/en/latest/examples/data/square.svg);
width: 20px;
height: 20px;
}
</style>
<script src="https://js.arcgis.com/4.18/"></script>
<script>
require([
"esri/Map",
"esri/views/MapView",
"esri/widgets/Locate"
], function (Map, MapView, Locate) {
var map = new Map({
basemap: "topo-vector"
});
var view = new MapView({
container: "viewDiv",
map: map,
center: [-56.049, 38.485, 78],
zoom: 3
});
var locateBtn = new Locate({
view: view
});
// Add the locate widget to the top left corner of the view
view.ui.add(locateBtn, {
position: "top-left"
});
view.when(_ => {
const n = document.getElementsByClassName("esri-icon-locate");
if (n && n.length === 1) {
n[0].classList = 'my-svg-icon';
}
});
});
</script>
</head>
<body>
<div id="viewDiv"></div>
</body>
</html>
My map is showing all of the data in a fusion table when I would like to restrict it.
Also, how would I query by the 'Geographic Name' field? I tried the query below but it would not work.
***Edit I solved the problem below by using code similar to this:
select: 'State Abbr.',
from: '1xdysxZ94uUFIit9eXmnw1fYc6VcQiXhceFd_CVKa',
where: "'State Abbr.' = 'FL'",
The issue was the lack of quotations.
Any assistance is appreciated!
select: 'State-County',
from: '1xdysxZ94uUFIit9eXmnw1fYc6VcQiXhceFd_CVKa',
where: 'State-County = AL-Autauga'
Here is my code currently:
****Edit: I have fixed the issue below by updating the code as follows
query: {
select: 'GEO_ID',
from: '1xdysxZ94uUFIit9eXmnw1fYc6VcQiXhceFd_CVKa',
where: "GEO_ID = '05000US01001'"
},
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geocoding service</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var geocoder;
var map;
var layer;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.0754, -84.2946);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
layer = new google.maps.FusionTablesLayer({
query: {
select: 'GEO_ID',
from: '1xdysxZ94uUFIit9eXmnw1fYc6VcQiXhceFd_CVKa',
where: 'GEO_ID = 05000US01001'
},
supressInfoWindows: true,
styles: [
{polygonOptions: {fillColor:'#0040FF',fillOpacity:0.1,strokeColor:'#FF0000',strokeWeight:2,strokeOpacity:0.6 }}
]
});
layer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox" value="Alpharetta, Georgia">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
</div>
</body>
</html>
Link to Fusion Table: https://www.google.com/fusiontables/data?docid=1xdysxZ94uUFIit9eXmnw1fYc6VcQiXhceFd_CVKa#rows:id=3
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).