Canvas algorithm to plot signatures randomly like a signed yearbook? - html

I'm looking for the best approach to plot multiple signatures randomly on a page like a high school yearbook using Canvas or SVG. Anyone know of existing algorithms or open source code similar to this?

Did you look into the following javascript libraries? I've used both of them and they work quite well:
SignaturePad or jSignature
Both of the offer a fallback to flash if the browser doesn't support it. We have chosen jSignature since the overall performance on different tablets when drawing new signature was better, but I personally like the style & API of signaturePad better.
You can record the signatures as example on a secured admin page and then just plot them wherever you want them.
Update
Since you just want random strings and not really signatures I recommend you'll have a look at HTML5 Canvas – Arrays and Random text:
<!DOCTYPE html>
<html>
<head>
<title>Random Text</title>
<script type="text/javascript">
var canvas, ctx;
var quotes = new Array();
var img = new Image(); // Create new img element
//or you can also use:
//var quotes = [];
function setup(){
//canvas and context setup
canvas=document.getElementById("myCanvas");
ctx=canvas.getContext("2d");
//create values for the array
quotes[0]="I";
quotes[1]="think";
quotes[2]="you";
quotes[3]="always";
quotes[4]="have";
quotes[5]="regrets";
//function calls
setInterval(draw,300);
window.addEventListener("keydown",checkKeyboard);
}
function draw(){
var randomIndex = Math.floor(Math.random()*quotes.length);
var randomColor = Math.round(Math.random()*80);
var randomX = Math.random()*canvas.width;
var randomY = Math.random()*canvas.height*2-canvas.width/2;
var randomSize = Math.random()*30+10;
ctx.fillStyle="rgba(255,255,255,0.8)";
ctx.font=randomSize+"px Arial Black, Gadget, sans-serif";
ctx.fillText(quotes[randomIndex],randomX,randomY);
ctx.lineWidth=1;
//ctx.strokeText(quotes[randomIndex],randomX,randomY);
}
function checkKeyboard(myEvt){
if(myEvt.keyCode==13){
ctx.clearRect(0,0,canvas.width,canvas.height);
}
}
</script>
</head>
<body onload="setup()">
<canvas id="myCanvas" width="800" height="600" style="border:1px solid; background:url(bg-hand.jpg)"></canvas>
<p>Press "ENTER" to clear the canvas</p>
</body>
</html>

Related

whats the difference between html2canvas and rasterizehtml.js

Apparently there are solutions to capturing screenshot of a web page:
Snapabug works by using an applet
GrabzIt I guess this is done on the server side.
Webkit2png is a command line tool, so not really part of the browser code.
There are probably other solutions that use ActiveX.
But I am interested in a Javascript only solution. From what I understand, both html2canvas and rasterizeHTML.js allow to convert html (in a web page) to an image. So, in what way is the implementation of html2canvas vs rasterizehtml.js different ? From what I understand both of them seem to use Canvas to generate the result. So in what way are they different? Which one is better ?
The main difference is that Rasterize is a wrapper around SVG foreignObject and html2canvas is essentially a reimplementation of browser HTML rendering from scratch. There are a lot of security headaches that Rasterize has to handle, but I think that its approach is better, as suggested by its being only 950 lines of code to html2canvas's 2400.
If the HTML you're rendering isn't very complex or doesn't need to be pixel-perfect, you may be able to skip Rasterize and use foreignObject directly, as described in MDN: Drawing DOM objects into a canvas:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
'<em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
I tried html2canvas.js and rasterizeHTML.js for visualisation of a piece of html. Both have some issues, though. html2canvas.js can't get through with elements which have transformation (For example, text with css scale transform). As long as, I can't make rasterizeHTML.js to draw a canvas inside the canvas which displays the html.

HTML5 Progress Element Scripting

I'm trying to display a HTML5 progress element to show the download progress of a large image file.
I've checked a few answers to similar questions already posted on this forum but they don't seem to directly answer the question (or more likely it's just my ignorance) or they get very technical and therefore way beyond me.
I've downloaded a HTML5 / JavaScript example file that shows the basic method (see code below) but I can't figure out how to link this script to my image download.
Any advice would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<title>Developer Drive | Displaying the Progress of Tasks with HTML5 | Demo</title>
<script type="text/javascript">
var currProgress = 0;
var done = false;
var total = 100;
function startProgress() {
var prBar = document.getElementById("prog");
var startButt = document.getElementById("startBtn");
var val = document.getElementById("numValue");
startButt.disabled=true;
prBar.value = currProgress;
val.innerHTML = Math.round((currProgress/total)*100)+"%";
currProgress++;
if(currProgress>100) done=true;
if(!done)
setTimeout("startProgress()", 100);
else
{
document.getElementById("startBtn").disabled = false;
done = false;
currProgress = 0;
}
}
</script>
</head>
<body>
<p>Task progress:</p>
<progress id="prog" value="0" max="100"></progress>
<input id="startBtn" type="button" value="start" onclick="startProgress()"/>
<div id="numValue">0%</div>
</body>
</html>
If you are looking to track the progress of an XMLHttpRequest (which could be loading an image, or anything else), Adobe has a great example there. Ctrl+U is your friend :)
Basically, you'll want to do that:
var xhr = new XMLHttpRequest();
xhr.onprogress = function(e){
// This tests whether the server gave you the total number of bytes that were
// about to be sent; some servers don't (this is config-dependend), and
// without that information you can't know how far along you are
if (e.lengthComputable)
{
// e.loaded contains how much was loaded, while e.total contains
// the total size of the file, so you'll want to get the quotient:
progressBar.value = e.loaded / e.total * 100;
}
else
{
// You can't know the progress in term of percents, but you could still
// do something with `e.loaded`
}
};
Mozilla's Developer site has some more details, if you want to see what can be done.
Hope that's enough for you :)
PS: Now that I think about it, I see no reason not to use the e.total as progressBar.max, and simply push e.loaded into progressBar.value

Storing HTML5 canvas containing images

How do you store a canvas that contains images using the toDataURL method? Everything works fine for text and drawing, but I don't know how to handle images. Any help would be appreciated. Thanks
I have modified my question as follows:
This works when the image is pulled directly from a .png. However, when I call the Google Charts API, toDataURL doesn't work even though the image renders correctly on the canvas. Google Charts is returning a .png. Anyone have any ideas? Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8">
function test() {
var c = document.getElementById("drawing-canvas");
var cxt = c.getContext("2d");
// This doesn't work.
//var imgsrc = 'http://chart.apis.google.com/chart?cht=tx&chf=bg,s,ffffff&chco=000000&
chl=a';
// This works
var imgsrc = 'chart.png';
var img = new Image();
img.src = imgsrc;
cxt.drawImage(img,0,0);
}
function wr() {
var cc = document.getElementById("drawing-canvas");
var url = cc.toDataURL();
var newImg = document.createElement("img");
newImg.src = url;
document.body.appendChild(newImg);
}
</script>
</head>
<body onload = "test();">
<canvas id="drawing-canvas" width = "500px" height = "500px" style="background-color:
#ffffff; border: 2px solid #000000;">
Your browser does not support the canvas element.
</canvas>
<input type = "button" value = "go" onclick = "wr();">
</body>
</html>
First of all, your chart didn't even render on the canvas when I tested it. You need to wait for the image to load. Your chart.png image probably loads instantaneously since it's cached, but the one generated by Google Charts API isn't. This is what you should do:
var img = new Image();
img.onload = function()
{
cxt.drawImage(img,0,0);
}
img.src = imgsrc;
Aside from that, you must be getting a SECURITY_ERR in your browser's console. This is because the Canvas security model doesn't allow you to export images coming from an external URL. You should use a server-side language to save the Google Charts image to your server, then load it from there.
The HTML canvas element has a method called toDataURL, that will return a data URL image representing the canvas. You can check the documentation API on the MDN.
Specifically, it says about toDataURL:
toDataURL(in optional DOMString type, in any ...args)
returns DOMString
Returns a data: URL containing a representation of the image in the format specified by type (defaults to PNG).
If the height or width of the canvas is 0, "data:," representing the empty string, is returned.
If the type requested is not image/png, and the returned value starts with data:image/png, then the requested type is not supported.
Chrome supports the image/webp type.
If the requested type is image/jpeg or image/webp, then the second argument, if it is between 0.0 and 1.0, is treated as indicating image quality; if the second argument is anything else, the default value for image quality is used. Other arguments are ignored.
And provides and example on how to use it:
function test() {
var canvas = document.getElementById("canvas");
var url = canvas.toDataURL();
var newImg = document.createElement("img");
newImg.src = url;
document.body.appendChild(newImg);
}
In this example, we use the dataURL as the source attribute of an img element, but you can do whatever you want you it (like storing it somewhere, or sending it to the server with an ajax call).
Note that most of the methods involved in drawing on canvas are methods of drawing context (obtained by a call to getContext), while this method is one of the canvas element.

Drawing text to <canvas> with #font-face does not work at the first time

When I draw a text in a canvas with a typeface that is loaded via #font-face, the text doesn't show correctly. It doesn't show at all (in Chrome 13 and Firefox 5), or the typeface is wrong (Opera 11). This type of unexpected behavior occurs only at the first drawing with the typeface. After then everything works fine.
Is it the standard behavior or something?
Thank you.
PS: Following is the source code of the test case
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>#font-face and <canvas></title>
<style id="css">
#font-face {
font-family: 'Press Start 2P';
src: url('fonts/PressStart2P.ttf');
}
</style>
<style>
canvas, pre {
border: 1px solid black;
padding: 0 1em;
}
</style>
</head>
<body>
<h1>#font-face and <canvas></h1>
<p>
Description: click the button several times, and you will see the problem.
The first line won't show at all, or with a wrong typeface even if it does.
<strong>If you have visited this page before, you may have to refresh (or reload) it.</strong>
</p>
<p>
<button id="draw">#draw</button>
</p>
<p>
<canvas width="250" height="250">
Your browser does not support the CANVAS element.
Try the latest Firefox, Google Chrome, Safari or Opera.
</canvas>
</p>
<h2>#font-face</h2>
<pre id="view-css"></pre>
<h2>Script</h2>
<pre id="view-script"></pre>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script id="script">
var x = 30,
y = 10;
$('#draw').click(function () {
var canvas = $('canvas')[0],
ctx = canvas.getContext('2d');
ctx.font = '12px "Press Start 2P"';
ctx.fillStyle = '#000';
ctx.fillText('Hello, world!', x, y += 20);
ctx.fillRect(x - 20, y - 10, 10, 10);
});
</script>
<script>
$('#view-css').text($('#css').text());
$('#view-script').text($('#script').text());
</script>
</body>
</html>
Drawing on canvas has to happen and return immediately when you call the fillText method. However, the browser has not yet loaded the font from the network, which is a background task. So it has to fall back to the font it does have available.
If you want to make sure the font is available, have some other element on the page preload it, eg.:
<div style="font-family: PressStart;">.</div>
Use this trick and bind an onerror event to an Image element.
Demo here: works on the latest Chrome.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://fonts.googleapis.com/css?family=Vast+Shadow';
document.getElementsByTagName('head')[0].appendChild(link);
// Trick from https://stackoverflow.com/questions/2635814/
var image = new Image();
image.src = link.href;
image.onerror = function() {
ctx.font = '50px "Vast Shadow"';
ctx.textBaseline = 'top';
ctx.fillText('Hello!', 20, 10);
};
You can load fonts with the FontFace API before using it in the canvas:
const myFont = new FontFace('My Font', 'url(https://myfont.woff2)');
myFont.load().then((font) => {
document.fonts.add(font);
console.log('Font loaded');
});
The font resource myfont.woff2 is first downloaded. Once the download completes, the font is added to the document's FontFaceSet.
The specification of the FontFace API is a working draft at the time of this writing. See browser compatibility table here.
The nub of the problem is that you are trying to use the font but the browser has not loaded it yet and possibly has not even requested it. What you need is something that will load the font and give you a callback once it is loaded; once you get the callback, you know it is okay to use the font.
Look at Google's WebFont Loader; it seems like a "custom" provider and an active callback after the load would make it work.
I've never used it before, but from a quick scan of the docs you need to make a css file fonts/pressstart2p.css, like this:
#font-face {
font-family: 'Press Start 2P';
font-style: normal;
font-weight: normal;
src: local('Press Start 2P'), url('http://lemon-factory.net/reproduce/fonts/Press Start 2P.ttf') format('ttf');
}
Then add the following JS:
WebFontConfig = {
custom: { families: ['Press Start 2P'],
urls: [ 'http://lemon-factory.net/reproduce/fonts/pressstart2p.css']},
active: function() {
/* code to execute once all font families are loaded */
console.log(" I sure hope my font is loaded now. ");
}
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
What about using simple CSS to hide a div using the font like this:
CSS:
#preloadfont {
font-family: YourFont;
opacity:0;
height:0;
width:0;
display:inline-block;
}
HTML:
<body>
<div id="preloadfont">.</div>
<canvas id="yourcanvas"></canvas>
...
</body>
https://drafts.csswg.org/css-font-loading/
var myFont = new FontFace('My Font', 'url(https://myfont.woff2)');
myFont.load().then(function(font){
// with canvas, if this is ommited won't work
document.fonts.add(font);
console.log('Font loaded');
});
i've bumped into the issue when playing with it recently http://people.opera.com/patrickl/experiments/canvas/scroller/
worked around it by adding the font-family to canvas directly in the CSS, so you can just add
canvas { font-family: PressStart; }
This article sorted out my issues with lazy loaded fonts not being displayed.
How to load web fonts to avoid performance issues and speed up page loading
This helped me ...
<link rel="preload" as="font" href="assets/fonts/Maki2/fontmaki2.css" rel="stylesheet" crossorigin="anonymous">
Since I've not found any example of the actual FontFace usage, here's #Fred
Fred Bergman's answer, slightly modified
const fontUrl = 'https://fonts.gstatic.com/s/robotomono/v22/L0xuDF4xlVMF-BfR8bXMIhJHg45mwgGEFl0_Of2_ROW-AJi8SJQt.woff'
const robotoFont = new FontFace('Roboto Mono', `url(${fontUrl})`);
// Canvas variables
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
robotoFont.load().then((font: FontFace) => {
// This is required
document.fonts.add(font);
// Usage example
ctx.font = `30px '${font.family}'`;
ctx.fillText("Hello World!", 10, 50);
});
Here's the compatibility table
If you want to redraw everytime a new font is loaded (and probably change the rendering) the font loading api has a nice event for that, too. I had problems with the Promise in a complete dynamic environment.
var fontFaceSet = document.fonts;
if (fontFaceSet && fontFaceSet.addEventListener) {
fontFaceSet.addEventListener('loadingdone', function () {
// Redraw something
});
} else {
// no fallback is possible without this API as a font files download can be triggered
// at any time when a new glyph is rendered on screen
}
I am not sure if this will help you, but to solve the problem with my code I simply created a for loop at the top of my Javascript which ran through all the fonts that I wanted to load. I then ran a function to clear the canvas and preload the items I wanted on the canvas. So far it has worked perfectly. That was my logic I have posted my code below:
var fontLibrary = ["Acme","Aladin","Amarante","Belgrano","CantoraOne","Capriola","CevicheOne","Chango","ChelaOne","CherryCreamSoda",
"ConcertOne","Condiment","Damion","Devonshire","FugazOne","GermaniaOne","GorditasBold","GorditasRegular",
"KaushanScript","LeckerliOne","Lemon","LilitaOne","LuckiestGuy","Molle","MrDafoe","MrsSheppards",
"Norican","OriginalSurfer","OswaldBold","OswaldLight","OswaldRegular","Pacifico","Paprika","Playball",
"Quando","Ranchers","SansitaOne","SpicyRice","TitanOne","Yellowtail","Yesteryear"];
for (var i=0; i < fontLibrary.length; i++) {
context.fillText("Sample",250,50);
context.font="34px " + fontLibrary[i];
}
changefontType();
function changefontType() {
selfonttype = $("#selfontype").val();
inputtextgo1();
}
function inputtextgo1() {
var y = 50;
var lineHeight = 36;
area1text = document.getElementById("bag1areatext").value;
context.clearRect(0, 0, 500, 95)
context.drawImage(section1backgroundimage, 0, 0);
context.font="34px " + selfonttype;
context.fillStyle = seltextcolor;
context.fillText(area1text, 250, y);
}
I wrote a jsfiddle incorporating most of the suggested fixes here but none resolved the issue. However, I am a novice programmer so perhaps did not code the suggested fixes correctly:
http://jsfiddle.net/HatHead/GcxQ9/23/
HTML:
<!-- you need to empty your browser cache and do a hard reload EVERYTIME to test this otherwise it will appear to working when, in fact, it isn't -->
<h1>Title Font</h1>
<p>Paragraph font...</p>
<canvas id="myCanvas" width="740" height="400"></canvas>
CSS:
#import url(http://fonts.googleapis.com/css?family=Architects+Daughter);
#import url(http://fonts.googleapis.com/css?family=Rock+Salt);
canvas {
font-family:'Rock Salt', 'Architects Daughter'
}
.wf-loading p {
font-family: serif
}
.wf-inactive p {
font-family: serif
}
.wf-active p {
font-family:'Architects Daughter', serif;
font-size: 24px;
font-weight: bold;
}
.wf-loading h1 {
font-family: serif;
font-weight: 400;
font-size: 42px
}
.wf-inactive h1 {
font-family: serif;
font-weight: 400;
font-size: 42px
}
.wf-active h1 {
font-family:'Rock Salt', serif;
font-weight: 400;
font-size: 42px;
}
JS:
// do the Google Font Loader stuff....
WebFontConfig = {
google: {
families: ['Architects Daughter', 'Rock Salt']
}
};
(function () {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
//play with the milliseconds delay to find the threshold - don't forget to empty your browser cache and do a hard reload!
setTimeout(WriteCanvasText, 0);
function WriteCanvasText() {
// write some text to the canvas
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.font = "normal" + " " + "normal" + " " + "bold" + " " + "42px" + " " + "Rock Salt";
context.fillStyle = "#d50";
context.fillText("Canvas Title", 5, 100);
context.font = "normal" + " " + "normal" + " " + "bold" + " " + "24px" + " " + "Architects Daughter";
context.fillText("Here is some text on the canvas...", 5, 180);
}
Workaround
I eventually gave in and, on the first load, used an image of the text while also positioning the text with the font-faces outside of the canvas display area. All subsequent displays of the font-faces within the canvas display area worked no problem. This is not an elegant workaround by any means.
The solution is baked into my website but if anyone needs I will try to create a jsfiddle to demonstrate.
Some browsers support the CSS Font Loading specification. It allows you to register register a callback for when all the fonts have been loaded. You can delay drawing your canvas (or at least drawing text into your canvas) until then, and trigger a redraw once the font is available.
The canvas is drawn independently of the DOM loading. The preload technique will only work if the canvas is drawn after the preload.
My solution, even if it is not the best:
CSS:
.preloadFont {
font-family: 'Audiowide', Impact, Charcoal, sans-serif, cursive;
font-size: 0;
position: absolute;
visibility: hidden;
}
HTML:
<body onload="init()">
<div class="preloadFont">.</div>
<canvas id="yourCanvas"></canvas>
</body>
JavaScript:
function init() {
myCanvas.draw();
}
I try to use FontFaceSet.load to fix the problem:
https://jsfiddle.net/wengshenshun/gr1zkvtq/30
const prepareFontLoad = (fontList) => Promise.all(fontList.map(font => document.fonts.load(font)))
You can find the browser compatibility from https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSet/load
First of all use Google's Web Font loader as was advised in the other answer and add your drawing code to the callback it provides to indicate the fonts have been loaded. However this is not the end of the story. From this point it is very browser dependent. Most of the time it will work fine, but sometimes it may be required to wait for couple hundreds of milliseconds or use the fonts somewhere else on the page. I tried different options and the one method that afaik always works is to quickly draw some test messages in the canvas with the font family and font size combinations that you are going to use. You can do it with the same color as background, so they won't even be visible and it will happen very fast. After that fonts always worked for me and in all browsers.
My answer addresses Google Web fonts rather than #font-face. I searched everywhere for a solution to the problem of the font not showing up in the canvas. I tried timers, setInterval, font-delay libraries, and all kinds of tricks. Nothing worked. (Including putting font-family in the CSS for canvas or the ID of the canvas element.)
However, I found that animating text rendered in a Google font worked easily. What's the difference? In canvas animation, we re-draw the animated items again and again. So I got the idea to render the text twice.
That did not work either -- until I also added a short (100ms) timer delay. I've only tested on a Mac so far. Chrome worked fine at 100ms. Safari required a page reload, so I increased the timer to 1000, and then it was fine. Firefox 18.0.2 and 20.0 wouldn't load anything on the canvas if I was using Google fonts (including the animation version).
Full code: http://www.macloo.com/examples/canvas/canvas10.html
http://www.macloo.com/examples/canvas/scripts/canvas10.js
Faces same problem. After reading "bobince" and others comments, I uses following javascript to workaround it :
$('body').append("<div id='loadfont' style='font-family: myfont;'>.</div>");
$('#loadfont').remove();
Add a delay as below
<script>
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
setTimeout(function() {
ctx.font = "24px 'Proxy6'"; // uninstalled #fontface font style
ctx.textBaseline = 'top';
ctx.fillText('What!', 20, 10);
}, 100);
</script>

Is it possible to embed the sidebar with Google Maps?

We'd like to use Google Maps to keep track of local garage sales. We've created a map (see here) and we'd like to embed that map on our website. However, when we do, we lose the sidebar of the map that contains a list of all the garage sales.
We're quite familiar with how to embed a Google; they've made the process quite simple. However, is there a way that we can embed the map and keep the sidebar list of garage sales?
To my knowledge, the best way would be to create your own container of the sales and link them to a map you are populating. I am assuming you are building and entering your data on Google's site and using the embed feature, which means my answers is significantly more work.
You would need to have your down data source and use the Maps API to create a map and a sidebar.
Your woudln't be using the iFrame anymore, you would be coding your own solution. If you have done JavaScript before, it is really fairly easy, if you haven't there are some good examples.
this tutorial http://econym.org.uk/gmap/basic2.htm shows exactly how to do it and supplies the code (which i reproduce by kind permission of the authors: Community Church Javascript Team http://www.bisphamchurch.org.uk)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Google Maps</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAPDUET0Qt7p2VcSk6JNU1sBSM5jMcmVqUpI7aqV44cW1cEECiThQYkcZUPRJn9vy_TWxWvuLoOfSFBw" type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<!-- you can use tables or divs for the overall layout -->
<table border=1>
<tr>
<td>
<div id="map" style="width: 550px; height: 450px"></div>
</td>
<td width = 150 valign="top" style="text-decoration: underline; color: #4444ff;">
<div id="side_bar"></div>
</td>
</tr>
</table>
Back to the tutorial page
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
if (GBrowserIsCompatible()) {
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
return marker;
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
GEvent.trigger(gmarkers[i], "click");
}
// create the map
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng( 43.907787,-79.359741), 8);
// add the points
var point = new GLatLng(43.65654,-79.90138);
var marker = createMarker(point,"This place","Some stuff to display in the<br>First Info Window")
map.addOverlay(marker);
var point = new GLatLng(43.91892,-78.89231);
var marker = createMarker(point,"That place","Some stuff to display in the<br>Second Info Window")
map.addOverlay(marker);
var point = new GLatLng(43.82589,-78.89231);
var marker = createMarker(point,"The other place","Some stuff to display in the<br>Third Info Window")
map.addOverlay(marker);
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
}
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
//]]>
</script>
</body>
</html>
I'm well into accessing the Google Maps API v3 with Javascript, and I've experimented successfully with a lot of different sample scripts, but I've come to the conclusion that the best (and quickest) method for producing embedded maps - with sidebars and lots of other options - is to go to http://www.mymapsplus.com/AddMyMap (thanks Chris B), and make a £10 donation to get rid of the adverts in generated maps - see e.g. http://www.hope-projects.org.uk/node/41. Their Edit page allows you to add or change almost any option you could think of with a few clicks.
What you want to do requires use of the MAPS API but it's not very hard if you know some javascript. Essentially, load the datapoints into a Javascript array, plot them on the map and then populate your html with the array information.
This link is a page I recently wrote that does the above and also dynamically repopulates the array from the db as the user drags the map (hardly any CSS at present either).
map with dynamic links
Happy to answer any more comments.
P.S. Cool map icon!
Tim
I found one site that will generate your map with a sidebar, but if you want more control, you'll need to create your own map, as the others have suggested.
http://www.mymapsplus.com/AddMyMap
http://www.mapchannels.com/
Another site that will generate your map with a sidebar is mapalist.com.