How do I animate paperjs onMouseEnter/Leave? - paperjs

All examples I see of paperjs involving movement, happens inside of onFrame, but how do I animate on mouse events?
var circle1 = new Shape.Circle(new Point(80, 50), 30);
circle1.strokeColor = 'green';
circle1.fillColor = 'green';
circle1.onMouseEnter = function (event) {
circle1.scale(1.2);
}
This works, but it doesn't animate.

You can make animation with setInterval like below code.
var circle1 = new Shape.Circle(new Point(80, 50), 30);
circle1.strokeColor = 'green';
circle1.fillColor = 'green';
circle1.onMouseEnter = function (event) {
var totalScale = 1
var id = setInterval(function(){
var scale = 1.01
totalScale *= scale;
if(totalScale > 2){
clearInterval(id)
}
circle1.scale(scale);
} , 50)
}
Add: [onFrame] version, is this what you want?
var circle1 = new Shape.Circle(new Point(80, 50), 30);
circle1.strokeColor = 'green';
circle1.fillColor = 'green';
circle1.onMouseEnter = function (event) {
circle1.onFrame = function(){
circle1.scale(1.01)
}
}
circle1.onMouseLeave = function (event) {
circle1.onFrame = null
}

Related

First page is blackened after adding watermark

Page is blackened after adding watermark in case of some pdf files . Please see attached image.
What could be the reason , and possible fix.
see the blacked out page image
It does not happen for all the files but for some files only.
Code is here in dotnetfiddle.
var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
} var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
}

Leaflet-markercluster default icons missing

Default icons not showing for MarkerCluster plugin after using IconCreateFunction.
I want to use the default icons for the plugin but when using attached code I loose all the icons functions, I only get the numbers with no icons and if I activate the "childCount" I get one type of circle with the numbers offcenter within the icon. The markers has already been clustered and I want to add this value to the markercluster that is why I'm using the IconCreateFuncton so the numbers on the map shows correctly but I have lost all the icons and its beautiful functions... what is missing?
Result below using "var childCount"
$.getJSON("../test/test.geojson", function(json) {
geoLayer = L.geoJson(json, {
pointToLayer: function(feature, latlng) {
var log_p = feature.properties.log_p;
var marker;
if (log_p > 0){
marker = new L.shapeMarker(latlng, {radius: log_p*25, fillColor: '#2b83ba', fillOpacity: 0.5, color: '#000000', weight: 1, shape: 'circle'});
}
else {
marker = null
}
return marker;
},
onEachFeature: function(feature, layer) {
var popupText = "Amount per day: " + '<b>' + feature.properties.total + '</b>';
layer.bindPopup(popupText, {
closeButton: true,
offset: L.point(0, -20)
});
layer.on('click', function() {
layer.openPopup();
});
},
});
var markers = new L.MarkerClusterGroup({
iconCreateFunction: function(cluster) {
var children = cluster.getAllChildMarkers();
var sum = 0;
for (var i = 0; i < children.length; i++) {
sum += children[i].feature.properties.total;
}
/*
var childCount = cluster.getAllChildMarkers();
var c = ' marker-cluster-';
if (childCount < 10) {
c += 'small';
} else if (childCount < 500) {
c += 'medium';
} else {
c += 'large';
}
*/
return new L.DivIcon({ html: '<b>' + sum + '</b>', className: 'marker-cluster'/* + c */, iconSize: new L.Point(40, 40) });
}
});
markers.addLayer(geoLayer)
map.addLayer(markers);
});
Markercluster icons, styles and functions are lost
I manage to solve the problem, a few lines of code was missing. I added them to the original JavaScript code as follows.
$.getJSON("../test/test.geojson", function(json) {
geoLayer = L.geoJson(json, {
pointToLayer: function(feature, latlng) {
var log_p = feature.properties.log_p;
var marker;
if (log_p > 0) {
marker = new L.shapeMarker(latlng, {
radius: log_p * 25,
fillColor: '#2b83ba',
fillOpacity: 0.5,
color: '#000000',
weight: 1,
shape: 'circle'
});
} else {
marker = null
}
return marker;
},
onEachFeature: function(feature, layer) {
var popupText = "Amount per day: " + '<b>' + feature.properties.total + '</b>';
layer.bindPopup(popupText, {
closeButton: true,
offset: L.point(0, -20)
});
layer.on('click', function() {
layer.openPopup();
});
},
});
var clusters = new L.MarkerClusterGroup({
maxClusterRadius: 125,
iconCreateFunction: function(cluster) {
var children = cluster.getAllChildMarkers();
var sum = 0;
for (var i = 0; i < children.length; i++) {
sum += children[i].feature.properties.total;
}
var childCount = cluster.getChildCount()
var c = ' marker-cluster-';
if (childCount + sum <= 50) {
c += 'small';
} else if (childCount + sum <= 250) {
c += 'medium';
} else {
c += 'large';
}
return new L.DivIcon({
html: '<div><span>' + sum + '</span></div>',
className: 'marker-cluster marker-cluster-' + c,
iconSize: new L.Point(40, 40)
});
},
});
clusters.addLayer(geoLayer)
map.addLayer(clusters);
});

three.js and confetti

I'm trying to make a confetti explosion and I'm having issues with projecting the confetti out. My idea is to have a fast explosion outwards in all directions (1 sec) then the confetti floats to the ground. I'm sure my math is wrong because I'm not getting it to expand.
I've taken three.js code and made some mods:
http://givememypatientinfo.com/ParticleBlocksConfetti.html
Any suggestions are welcome. I'm a noob at the three.js... but love the library!
Code:
var container, stats;
var camera, controls, scene, projector, renderer;
var objects = [], plane;
var vel = 1;
var vel2 = 0.01;
var accel = .3;
var accel2 = -.9;
var force = 1;
var frame = 0;
var mouse = new THREE.Vector2(),
offset = new THREE.Vector3(),
INTERSECTED, SELECTED;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;
/*//controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;*/
scene = new THREE.Scene();
scene.add( new THREE.AmbientLight( 0x505050 ) );
var light = new THREE.SpotLight( 0xffffff, 1.5 );
light.position.set( 0, 500, 2000 );
light.castShadow = true;
light.shadowCameraNear = 200;
light.shadowCameraFar = camera.far;
light.shadowCameraFov = 50;
light.shadowBias = -0.00022;
light.shadowDarkness = 0.5;
light.shadowMapWidth = 2048;
light.shadowMapHeight = 2048;
scene.add( light );
var geometry = new THREE.CubeGeometry( 40, 40, 40 );
//make confetti for particle system
for ( var i = 0; i < 100; i ++ ) {
var object = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: Math.random() * 0xffffff } ) );
//object.material.ambient = object.material.color;
/*object.position.x = Math.random() * 500 - 100;
object.position.y = Math.random() * 500 - 100;
object.position.z = 300;*/
object.position.x = Math.random() * 100 - 100;
object.position.y = Math.random() * 100 - 100;
object.position.z = 300;
object.rotation.x = Math.random() * 2 * Math.PI;
object.rotation.y = Math.random() * 2 * Math.PI;
object.rotation.z = Math.random() * 2 * Math.PI;
object.scale.x = .1;
object.scale.y = Math.random() * .8 + .1;
object.scale.z = Math.random() * .5 + .1;
object.castShadow = false;
object.receiveShadow = true;
scene.add( object );
objects.push( object );
}
plane = new THREE.Mesh( new THREE.PlaneGeometry( 2000, 2000, 8, 8 ), new THREE.MeshBasicMaterial( { color: 0x000000, opacity: 0.25, transparent: true, wireframe: true } ) );
plane.visible = false;
scene.add( plane );
projector = new THREE.Projector();
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.sortObjects = false;
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMapEnabled = true;
renderer.shadowMapType = THREE.PCFShadowMap;
container.appendChild( renderer.domElement );
var info = document.createElement( 'div' );
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'three.js webgl - draggable cubes';
container.appendChild( info );
}
function animate_particles(frame) {
//will update each particle
if (frame < 50){
var pCount = objects.length-1;
if (frame < 40){
vel += accel*2;
}else {
vel = vel + accel2;
}
while(pCount > -1) {
if (frame < 30){
objects[pCount].position.y += vel;
}else{
objects[pCount].position.y -= vel;
}
//objects[pCount].rotation.x += Math.random()*.7;
//objects[pCount].rotation.z += Math.random()*.01;
//objects[pCount].rotation.y += Math.random()*.01;
pCount--;
}
}
}
function animate() {
requestAnimationFrame( animate );
animate_particles(frame);
render();
//stats.update();
}
function render() {
renderer.render( scene, camera );
frame++;
}
</script>
This could be what you were trying to archieve. I modified your code a little bit and commented the changes. Basically I just added a random direction vector, normalized it and added a random speed to the particles. In the animate_particles function, I am moving the confetti along the random direction vector at the random speed.
var container, stats;
var camera, controls, scene, projector, renderer;
var objects = [], plane;
var vel = 1;
var vel2 = 0.01;
var accel = .3;
var accel2 = -.9;
var force = 1;
var frame = 0;
var mouse = new THREE.Vector2(),
offset = new THREE.Vector3(),
INTERSECTED, SELECTED;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;
/*//controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;*/
scene = new THREE.Scene();
scene.add( new THREE.AmbientLight( 0x505050 ) );
var light = new THREE.SpotLight( 0xffffff, 1.5 );
light.position.set( 0, 500, 2000 );
light.castShadow = true;
light.shadowCameraNear = 200;
light.shadowCameraFar = camera.far;
light.shadowCameraFov = 50;
light.shadowBias = -0.00022;
light.shadowDarkness = 0.5;
light.shadowMapWidth = 2048;
light.shadowMapHeight = 2048;
scene.add( light );
var geometry = new THREE.CubeGeometry( 40, 40, 40 );
//make confetti for particle system
for ( var i = 0; i < 100; i ++ ) {
var object = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: Math.random() * 0xffffff } ) );
//object.material.ambient = object.material.color;
/*object.position.x = Math.random() * 500 - 100;
object.position.y = Math.random() * 500 - 100;
object.position.z = 300;*/
object.position.x = Math.random() * 100 - 100;
object.position.y = Math.random() * 100 - 100;
object.position.z = 300;
object.rotation.x = Math.random() * 2 * Math.PI;
object.rotation.y = Math.random() * 2 * Math.PI;
object.rotation.z = Math.random() * 2 * Math.PI;
object.scale.x = .1;
object.scale.y = Math.random() * .8 + .1;
object.scale.z = Math.random() * .5 + .1;
// give every "particle" a random expanding direction vector and normalize it to receive a length of 1.
object.directionVector = new THREE.Vector3( Math.random() - .5, Math.random() - .5, Math.random() - .5 )
object.directionVector.normalize();
// and a random expanding Speed
object.expandingSpeed = Math.random() * 100;
object.castShadow = false;
object.receiveShadow = true;
scene.add( object );
objects.push( object );
}
plane = new THREE.Mesh( new THREE.PlaneGeometry( 2000, 2000, 8, 8 ), new THREE.MeshBasicMaterial( { color: 0x000000, opacity: 0.25, transparent: true, wireframe: true } ) );
plane.visible = false;
scene.add( plane );
projector = new THREE.Projector();
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.sortObjects = false;
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMapEnabled = true;
renderer.shadowMapType = THREE.PCFShadowMap;
container.appendChild( renderer.domElement );
var info = document.createElement( 'div' );
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'three.js webgl - draggable cubes';
container.appendChild( info );
}
function animate_particles(frame) {
//will update each particle
if (frame < 50){
var pCount = objects.length-1;
if (frame < 40){
vel += accel*2;
}else {
vel = vel + accel2;
}
while(pCount > -1) {
if (frame < 30){
// commented that out. not sure why you put it there.
//objects[pCount].position.y += vel;
// move objects along random direction vector at the individual random speed.
objects[pCount].position.x += objects[pCount].directionVector.x * objects[pCount].expandingSpeed;
objects[pCount].position.y += objects[pCount].directionVector.y * objects[pCount].expandingSpeed;
objects[pCount].position.z += objects[pCount].directionVector.z * objects[pCount].expandingSpeed;
}else{
objects[pCount].position.y -= vel;
}
//objects[pCount].rotation.x += Math.random()*.7;
//objects[pCount].rotation.z += Math.random()*.01;
//objects[pCount].rotation.y += Math.random()*.01;
pCount--;
}
}
}
function animate() {
requestAnimationFrame( animate );
animate_particles(frame);
render();
//stats.update();
}
function render() {
renderer.render( scene, camera );
frame++;
}
I've just made a plugin for create Confetti Effect with THREE.js: https://github.com/mrgoonie/three.confetti.explosion.js
Things would be easier with:
var confetti = new ExplosionConfetti({
rate: 1, // percent of explosion in every tick - smaller is fewer - be careful, larger than 10 may crash your browser!
amount: 200, // max amount particle of an explosion
radius: 800, // max radius of an explosion
areaWidth: 500, // width of the area
areaHeight: 500, // height of the area
fallingHeight: 500, // start exploding from Y position
fallingSpeed: 1, // max falling speed
colors: [0xffffff, 0xff0000, 0xffff00] // random colors
});
scene.add( confetti.object );
Cheers,

Text Overlay - Displayed in wrong Position

I have implemented the accepted answer to this Question. When I run the html file, the text which I'm writing over the Google Map marker is displayed in wrong location (Refer the picture error.png). Can anyone help me to display the text exactly over the marker?.
Marker.html
<html><head>
<title> Hi </title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function TxtOverlay(pos, txt, cls, map){
this.pos = pos;
this.txt_ = txt;
this.cls_ = cls;
this.map_ = map;
this.div_ = null;
this.setMap(map);
}
TxtOverlay.prototype = new google.maps.OverlayView();
TxtOverlay.prototype.onAdd = function(){
var div = document.createElement('DIV');
div.className = this.cls_;
div.innerHTML = this.txt_;
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
div.style.left = ( position.x) + 'px';
div.style.top = ( position.y)+ 'px';
var panes = this.getPanes();
panes.floatPane.appendChild(div);
}
TxtOverlay.prototype.draw = function(){
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
var div = this.div_;
div.style.left = ( position.x) + 'px';
div.style.top = ( position.y)+ 'px';
}
TxtOverlay.prototype.onRemove = function(){
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
TxtOverlay.prototype.hide = function(){
if (this.div_) {
this.div_.style.visibility = "hidden";
}
}
TxtOverlay.prototype.show = function(){
if (this.div_) {
this.div_.style.visibility = "visible";
}
}
TxtOverlay.prototype.toggle = function(){
if (this.div_) {
if (this.div_.style.visibility == "hidden") {
this.show();
}
else {
this.hide();
}
}
}
TxtOverlay.prototype.toggleDOM = function(){
if (this.getMap()) {
this.setMap(null);
}
else {
this.setMap(this.map_);
}
}
var map;
function init(){
var latlng = new google.maps.LatLng(37.90695894, -122.07920128);
var myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!",
icon:"./bluepin.PNG"
});
customTxt = "<div>1</div>"
txt = new TxtOverlay(latlng,customTxt,"customBox",map )
}
</script>
<style>
.customBox {
background: AARRGGBB;
border: 1px;
color:#ffffff;
position: relative;
}
</style>
</head>
<body onload="init()">
<div id="map" style="width: 600px; height: 600px;">
</div>
</body>
</html>
You need to offset the div so it appears over the marker. An offset of (-5, -30) works for this marker and the number "1".
function TxtOverlay(pos, txt, cls, map, offset){
this.pos = pos;
this.txt_ = txt;
this.cls_ = cls;
this.map_ = map;
this.offset_ = offset;
this.div_ = null;
this.setMap(map);
}
TxtOverlay.prototype.onAdd = function(){
var div = document.createElement('DIV');
div.className = this.cls_;
div.innerHTML = this.txt_;
this.div_ = div;
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
div.style.left = ( position.x + this.offset_.x) + 'px';
div.style.top = ( position.y + this.offset_.y)+ 'px';
var panes = this.getPanes();
panes.floatPane.appendChild(div);
}
TxtOverlay.prototype.draw = function(){
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
var div = this.div_;
div.style.left = ( position.x + this.offset_.x) + 'px';
div.style.top = ( position.y + this.offset_.y)+ 'px';
}
txt = new TxtOverlay(latlng,customTxt,"customBox",map,new google.maps.Point(-5,-30) )
Example
you might also look atthe MarkerWithLabel utility library
Example

Changing Marker Icons while using MarkerClusterer (Works in IE9 and Chrome, Doesn't Work in Firefox or earlier IE versions)

I have a public-facing site using GoogleMaps API v3 and the MarkerClusterer library. The page that is having a problem can be found here (http://www.mihomes.com/Find-Your-New-Home/San-Antonio-Homes). If you view this page in IE9 or Chrome, the correct pin icon images are shown, while in previous IE versions and Firefox different (and incorrect) pin icons.
IE9
Firefox 3.6.8
Here is the JavaScript code that generates the pins/clustering:
$(function() {
var dl_grid = new DLGrid(".GMapGrid");
dl_grid.init();
var dl_map = new DLMap("#map");
dl_map.init();
var markers = dl_grid.CollectMarkerData();
dl_map.LoadMarkers(markers);
});
var DLIcons = new function() {
var me = this;
me.NormalIcon = "/images/GoogleMapsIcons/mi_icon_n.png";
me.HoverIcon = "/images/GoogleMapsIcons/new_mi_icon_r.png";
me.ClusterIcon = "/images/GoogleMapsIcons/mi_icon_n.png";
me.ClusterHoverIcon = "/images/GoogleMapsIcons/new_mi_icon_r.png";
me.SalesCenterIcon = "/images/GoogleMapsIcons/new_mi_icon_n2.gif";
me.DesignCenterIcon = "/images/GoogleMapsIcons/mi_dc_n.png";
me.DesignCenterHoverIcon = "/images/GoogleMapsIcons/mi_dc_r.png";
};
//Used for all functions relating to the table below the map
var DLGrid = function(grid_selector) {
//Initialize variables
var me = this;
me.grid = $(grid_selector);
//Initialize
me.init = function() {
setupTableSorting();
setupHoverEvents();
setupZoomButtons();
};
//Setup the table sorting
var setupTableSorting = function() {
//Init tablesorter plugin
var sort_options = { headers: { 0: { sorter: false }, 4: { sorter: false} } };
if (MI_DIVISION_LANDING_TABLE_SORT_OPTIONS != undefined) {
sort_options = MI_DIVISION_LANDING_TABLE_SORT_OPTIONS;
}
me.grid.tablesorter(sort_options);
//As soon as the user sorts, remove all Community Groups
me.grid.bind("sortEnd", function() {
me.grid.find("tr.communityGroup").remove();
$("tr.groupedCommunity").removeClass("groupedCommunity").addClass("ungroupedCommunity");
//$("tr.ungroupedCommunity").removeClass("ungroupedCommunity");
me.grid.trigger("update");
});
};
var highlightRow = function(marker) {
var markerId = (typeof (marker) == "string") ? marker : marker.jsonData.MarkerID;
$(me.grid).find("#" + markerId).addClass("highlightedRow");
};
// Bind to mouseover/mouseout events and highlight the proper row in the table
// Trigger mouseover/mouseout events when you hover over a row in the table
var setupHoverEvents = function() {
$(document).bind("MARKER_MOUSEOVER", function(e, marker) {
$(me.grid).find("tbody tr.highlightedRow").removeClass("highlightedRow");
if (typeof (marker) != "string" && marker.length != undefined) {
for (var i = 0; i < marker.length; i++) {
highlightRow(marker[i]);
}
}
else {
highlightRow(marker);
}
});
// $(document).bind("MULTIPLE_MARKER_MOUSEOVER", function(e, markers) {
// $(me.grid).find("tbody tr.highlightedRow").removeClass("highlightedRow");
// for (var i = 0; i < markers.length; i++) {
// var markerId = (typeof (markers[i]) == "string") ? markers[i] : markers[i].jsonData.MarkerID;
// $(me.grid).find("#" + markerId).addClass("highlightedRow");
// }
// });
$(me.grid).find("tbody tr").mouseover(function() {
$(document).trigger("MARKER_MOUSEOVER", [$(this).attr("id")]);
});
};
// The zoom buttons next to each row should zoom to a marker and show it's info window
var setupZoomButtons = function() {
$(me.grid).find("tbody tr .zoom_link img").click(function() {
$(document).trigger("MAP_SHOW_MARKER_POPUP_AND_ZOOM", [$(this).parent().parent().attr("id")]);
});
};
// Collect and parse the JSON data from the hidden 'data' column in the table
me.CollectMarkerData = function() {
var markers = [];
$.each(me.grid.find("tbody tr:not(.communityGroup)"), function(i, row) {
var dataCell = $(row).children("td.data");
var rawContent = $(dataCell).text();
var json_data = {};
if (rawContent.length > 0) {
json_data = JSON.parse(rawContent);
}
json_data["MarkerID"] = $(row).attr("id");
markers.push(json_data);
});
return markers;
};
};
//Used for all functions relating to map
var DLMap = function(map_div_selector) {
//Initialize variables
var me = this;
me.mapDivSelector = map_div_selector;
me.mapObj;
me.init = function() {
setupMap();
bindHoverEvents();
setupPopupEvents();
setupDesignCenter();
};
//Basic setup of map
var setupMap = function() {
me.mapObj = new DLGoogleMap(me.mapDivSelector);
me.mapObj.init(onMarkerMouseOver, showMarkerPopup);
};
// Add an array of markers (from json data) to the map
me.LoadMarkers = function(markers) {
$.each(markers, function(i, json_marker) {
me.mapObj.addMarker(json_marker);
});
me.mapObj.fitMapToMarkers();
};
var showMarkerPopup = function(markerJson, zoomToLocation) {
var source = $("#MapMarkerInfoWindow").html();
var template = Handlebars.compile(source);
var content = template(markerJson);
var triggerKey = (zoomToLocation == true) ? "MAP_SHOW_POPUP_AND_ZOOM" : "MAP_SHOW_POPUP";
$(document).trigger(triggerKey, [content, markerJson.Lat, markerJson.Lng]);
};
var onMarkerMouseOver = function(markerJson) {
$(document).trigger("MARKER_MOUSEOVER", markerJson);
}
// Highlight (or unhighlight) a marker when a mouseover/mouseout event is triggered
var bindHoverEvents = function() {
$(document).bind("MARKER_MOUSEOVER", function(e, marker) {
if (typeof (marker) != "string" && marker.length != undefined) {
marker = marker[0];
}
me.mapObj.resetMarkerHighlighting();
me.mapObj.highlightMarker(marker);
});
// $(document).bind("MULTIPLE_MARKER_MOUSEOVER", function(e, markers) {
// me.mapObj.resetMarkerHighlighting();
// if (markers[0].cluster != null) {
// me.mapObj.highlightCluster(markers[0]
// }
// });
};
var setupPopupEvents = function() {
$(document).bind("MAP_SHOW_POPUP", function(e, content, lat, lng) {
me.mapObj.showPopup(content, lat, lng);
});
$(document).bind("MAP_SHOW_POPUP_AND_ZOOM", function(e, content, lat, lng) {
me.mapObj.showPopup(content, lat, lng, true);
});
$(document).bind("MAP_SHOW_MARKER_POPUP", function(e, marker) {
if (typeof (marker) == "string") {
marker = me.mapObj.findMarkerByID(marker);
}
showMarkerPopup(marker.jsonData);
});
$(document).bind("MAP_SHOW_MARKER_POPUP_AND_ZOOM", function(e, marker) {
if (typeof (marker) == "string") {
marker = me.mapObj.findMarkerByID(marker);
}
showMarkerPopup(marker.jsonData, true);
});
};
var setupDesignCenter = function() {
var jsonText = $.trim($("#DesignCenterData").text());
if (jsonText.length > 5) {
var dcJson = JSON.parse(jsonText);
me.mapObj.addDesignCenterMarker(dcJson);
}
};
};
var DLGoogleMap = function(map_div_selector) {
//Initialize variables
var me = this;
me.mapDiv = $(map_div_selector);
me.gmap;
me.markers = [];
me.markerClusterer;
me.infoWindow;
me.onMouseOver;
me.onClick;
me.ZOOM_TO_LEVEL = 14;
me.highlightedMarkers = [];
me.designCenterMarker = null;
//Extend Google Map Classes
google.maps.Marker.prototype.jsonData = null;
google.maps.Marker.prototype.iconImg = null;
google.maps.Marker.prototype.iconHoverImg = null;
me.init = function(onMouseOver, onClick) {
me.onMouseOver = onMouseOver;
me.onClick = onClick;
setupMap();
setupClustering();
setupDrivingDirectionLinks();
};
var setupMap = function() {
//var latlng = new google.maps.LatLng(40.05, -82.95);
var myOptions = {
zoom: 14,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
me.gmap = new google.maps.Map(document.getElementById("map"), myOptions);
me.infoWindow = new google.maps.InfoWindow();
};
var setupDrivingDirectionLinks = function() {
$("a.gDirectionsLink").live("click", function(e) {
e.preventDefault();
$(".gPopupInfo").hide();
$(".gDrivingDirections").show();
});
$("a.gCloseDrivingDirections").live("click", function(e) {
e.preventDefault();
$(".gDrivingDirections").hide();
$(".gPopupInfo").show();
});
};
//Add a single json marker to the map
me.addMarker = function(jsonMarker) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(jsonMarker.Lat, jsonMarker.Lng),
title: jsonMarker.Name
});
marker.jsonData = jsonMarker;
if (jsonMarker.HasSalesCenter == "True") {
marker.iconImg = DLIcons.SalesCenterIcon;
}
else {
marker.iconImg = DLIcons.NormalIcon;
}
marker.iconHoverImg = DLIcons.HoverIcon;
marker.icon = marker.iconImg;
google.maps.event.addListener(marker, 'click', function() {
me.onClick(marker.jsonData);
});
google.maps.event.addListener(marker, 'mouseover', function() { me.onMouseOver(marker) });
me.markerClusterer.addMarker(marker);
me.markers.push(marker);
};
//Add an arbitrary marker
me.addDesignCenterMarker = function(dcJson) {
me.designCenterMarker = new google.maps.Marker({
position: new google.maps.LatLng(dcJson.Lat, dcJson.Lng),
title: "Design Center",
map: me.gmap
});
me.designCenterMarker.jsonData = dcJson;
me.designCenterMarker.iconImg = DLIcons.DesignCenterIcon;
me.designCenterMarker.iconHoverImg = DLIcons.DesignCenterHoverIcon;
me.designCenterMarker.icon = me.designCenterMarker.iconImg;
google.maps.event.addListener(me.designCenterMarker, 'mouseover', function() {
me.highlightMarker(me.designCenterMarker);
});
google.maps.event.addListener(me.designCenterMarker, 'mouseout', function() {
me.unHighlightMarker(me.designCenterMarker);
});
google.maps.event.addListener(me.designCenterMarker, 'click', function() {
me.infoWindow.close();
var source = $("#DesignCenterInfoWindow").html();
var template = Handlebars.compile(source);
var content = template(me.designCenterMarker.jsonData);
me.showPopup(content, me.designCenterMarker.jsonData.Lat, me.designCenterMarker.jsonData.Lng);
});
};
me.resetMarkerHighlighting = function() {
for (var i = 0; i < me.highlightedMarkers.length; i++) {
me.unHighlightMarker(me.highlightedMarkers[i]);
}
me.highlightedMarkers = [];
}
me.highlightMarker = function(m) {
var marker = (typeof (m) == "string") ? me.findMarkerByID(m) : m;
if (marker != null) {
if (marker.cluster == null || (marker.cluster.hasMultipleMarkers() == false)) {
marker.setIcon(marker.iconHoverImg);
}
else {
highlightCluster(marker.cluster);
}
me.highlightedMarkers.push(marker);
}
};
me.unHighlightMarker = function(m) {
var marker = (typeof (m) == "string") ? me.findMarkerByID(m) : m;
if (marker != null) {
if (marker.cluster == null || (marker.cluster.hasMultipleMarkers() == false)) {
marker.setIcon(marker.iconImg);
}
else {
unHighlightCluster(marker.cluster);
}
}
};
me.zoomAndShowPopup = function(content, lat, lng) {
};
me.showPopup = function(content, lat, lng, zoomToLocation) {
if (zoomToLocation == true) {
var adjustedLat = lat - (me.gmap.getZoom() * 0.01);
me.zoomToLocation(adjustedLat, lng);
}
me.infoWindow.setContent(content);
me.infoWindow.setPosition(new google.maps.LatLng(lat, lng));
me.infoWindow.open(me.gmap);
};
me.zoomToLocation = function(lat, lng) {
me.gmap.setZoom(me.ZOOM_TO_LEVEL)
me.gmap.setCenter(new google.maps.LatLng(lat, lng));
};
me.fitMapToMarkers = function() {
me.markerClusterer.fitMapToMarkers();
};
//Setup the map 'clustering', so that nearby markers will cluster together to form 1 icon
var setupClustering = function() {
Cluster.prototype.iconImg = DLIcons.ClusterIcon;
Cluster.prototype.iconHoverImg = DLIcons.ClusterHoverIcon;
var mc_options = {
gridSize: 15,
maxZoom: 15,
zoomOnClick: false,
styles: [{ url: DLIcons.ClusterIcon, height: 30, width: 20, textColor: "#fff", textSize: 10}],
showMarkerCount: false,
onClusterAdded: onClusterAdded
};
me.markerClusterer = new MarkerClusterer(me.gmap, [], mc_options);
//Setup Cluster Info Windows with a list of marker links
google.maps.event.addListener(me.markerClusterer, 'clusterclick', function(cluster) {
me.infoWindow.close();
var source = $("#MapClusterInfoWindow").html();
var template = Handlebars.compile(source);
var markers = getClusterJsonMarkers(cluster);
var data = {
markers: markers
};
var content = template(data);
$(document).trigger("MAP_SHOW_POPUP", [content, cluster.getCenter().lat(), cluster.getCenter().lng()]);
});
//Setup Cluster marker highlighting
google.maps.event.addListener(me.markerClusterer, 'clustermouseover', function(cluster) {
me.resetMarkerHighlighting();
highlightCluster(cluster);
var cmarkers = cluster.getMarkers();
$(document).trigger("MARKER_MOUSEOVER", [cmarkers]);
});
$(".openMarkerPopup").live("click", function(e) {
e.preventDefault();
$(document).trigger("MAP_SHOW_MARKER_POPUP", [$(this).attr("rel")]);
});
};
var onClusterAdded = function(cluster) {
if (clusterHasSalesCenter(cluster)) {
cluster.iconImg = DLIcons.SalesCenterIcon;
cluster.updateIconUrl(cluster.iconImg);
}
else {
cluster.iconImg = DLIcons.ClusterIcon;
}
};
var clusterHasSalesCenter = function(cluster) {
if ((cluster == undefined) || (cluster.markers_ == undefined)) {
return false;
}
for (var i = 0; i < cluster.markers_.length; i++) {
if (cluster.markers_[i].jsonData.HasSalesCenter == "True") {
return true;
}
}
return false;
};
var highlightCluster = function(cluster) {
//me.highlightedMarkers = [];
// for (var i = 0; i < cluster.markers_.length; i++) {
// me.highlightedMarkers.push(cluster.markers_[i]);
// }
cluster.updateIconUrl(cluster.iconHoverImg);
};
var unHighlightCluster = function(cluster) {
cluster.updateIconUrl(cluster.iconImg);
};
var getClusterJsonMarkers = function(cluster) {
var jsonMarkers = [];
var gmarkers = cluster.getMarkers();
for (var i = 0; i < gmarkers.length; i++) {
jsonMarkers.push(gmarkers[i].jsonData);
}
return jsonMarkers;
};
// Get a marker on the map given it's MarkerID
me.findMarkerByID = function(markerId) {
for (var i = 0; i < me.markers.length; i++) {
if (me.markers[i].jsonData.MarkerID == markerId) {
return me.markers[i];
break;
}
}
return null;
};
};
This website is built using .NET Framework 3.5 and ASP.NET WebForms.
Thanks for the assistance.

Resources