Onclick location, using location in function - javascript

I'm making tile map with two layers: map from my files stored on HDD, second is OSM. I've made it with gdal2tiles.py
How it looks: Two layers using OpenLayers
I want to add a onclick popup which will show link to the original tile in bigger resolution. My idea is to attach a .csv file with following structure:
[latitude],[longitude],[image index]
My function in python parses this file and gets image index. Here is it:
def find_pic(lat, lng):
my_file = open('log wynikowy epsg 3857.csv', 'r')
list_of_lines = my_file.readlines()
print len(list_of_lines)
for line in list_of_lines:
if (line.rstrip()).split(",")[0] == lat and (line.rstrip()).split(',')[1] == lng:
return line.rstrip().split(',')[2]
Then I tried to rewrite it in JavaScript:
function find_pic(lat, lng) {
fh = fopen(getScriptPath('log wynikowy epsg 3857.csv'), 0);
fh_length = flength(fh);
var allText = fread(fh, fh_length);
var fldData = [];
for (x = 0; x < allTextLines.length; x++) {
fldData = allTextLines[x].split(',');
}
for (i = 0; i < fldData.length.length; i++) {
if (allTextLines[i].split(',')[0] == lat && allTextLines[i].split(',')[1] == lng) {
var result = allTextLines[i].split(',')[2];
}
}
var pic_link = "/data/" + result + ".jpg";
return pic_link;
}
In my html file, I copy-paste popup with location example and try to implement my function. Here is the whole HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
<head>
<title>Ortofotomapa</title>
<meta http-equiv='imagetoolbar' content='no'/>
<style type="text/css"> v\:* {behavior:url(#default#VML);}
html, body { overflow: hidden; padding: 0; height: 100%; width: 100%; font-family: 'Lucida Grande',Geneva,Arial,Verdana,sans-serif; }
body { margin: 10px; background: black; }
h1 { margin: 0; padding: 6px; border:0; font-size: 20pt; }
#header { height: 43px; padding: 0; background-color: #eee; border: 1px solid #888; }
#subheader { height: 12px; text-align: right; font-size: 10px; color: #555;}
#map { height: 95%; border: 1px solid #888; }
.olImageLoadError { display: none; }
.olControlLayerSwitcher .layersDiv { border-radius: 10px 0 0 10px; }
</style>
<script src='http://maps.google.com/maps/api/js?sensor=false&v=3.7'></script>
<script src="http://www.openlayers.org/api/2.12/OpenLayers.js"></script>
<script>
var map;
var mapBounds = new OpenLayers.Bounds( 20.9278783732, 52.0107452018, 20.943887533, 52.0184497743);
var mapMinZoom = 14;
var mapMaxZoom = 20;
var emptyTileURL = "http://www.maptiler.org/img/none.png";
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
function init(){
var options = {
div: "map",
controls: [],
projection: "EPSG:900913",
displayProjection: new OpenLayers.Projection("EPSG:4326"),
numZoomLevels: 20
};
map = new OpenLayers.Map(options);
// Create OSM layer
var osm = new OpenLayers.Layer.OSM("OpenStreetMap");
// create TMS Overlay layer
var tmsoverlay = new OpenLayers.Layer.TMS("TMS Overlay", "",
{
serviceVersion: '.',
layername: '.',
alpha: true,
type: 'png',
isBaseLayer: false,
getURL: getURL
});
if (OpenLayers.Util.alphaHack() == false) {
tmsoverlay.setOpacity(1.0);
}
map.addLayers([osm, tmsoverlay]);
var switcherControl = new OpenLayers.Control.LayerSwitcher();
map.addControl(switcherControl);
switcherControl.maximizeControl();
map.zoomToExtent(mapBounds.transform(map.displayProjection, map.projection));
map.addControls([//new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.MousePosition({
numDigits: 10}),
//new OpenLayers.Control.ArgParser(),
new OpenLayers.Control.Attribution()]);
}
function getURL(bounds) {
bounds = this.adjustBounds(bounds);
var res = this.getServerResolution();
var x = Math.round((bounds.left - this.tileOrigin.lon) / (res * this.tileSize.w));
var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
var z = this.getServerZoom();
if (this.map.baseLayer.CLASS_NAME === 'OpenLayers.Layer.Bing') {
z+=1;
}
var path = this.serviceVersion + "/" + this.layername + "/" + z + "/" + x + "/" + y + "." + this.type;
var url = this.url;
if (OpenLayers.Util.isArray(url)) {
url = this.selectUrl(path, url);
}
if (mapBounds.intersectsBounds(bounds) && (z >= mapMinZoom) && (z <= mapMaxZoom)) {
return url + path;
} else {
return emptyTileURL;
}
}
function getWindowHeight() {
if (self.innerHeight) return self.innerHeight;
if (document.documentElement && document.documentElement.clientHeight)
return document.documentElement.clientHeight;
if (document.body) return document.body.clientHeight;
return 0;
}
function getWindowWidth() {
if (self.innerWidth) return self.innerWidth;
if (document.documentElement && document.documentElement.clientWidth)
return document.documentElement.clientWidth;
if (document.body) return document.body.clientWidth;
return 0;
}
function resize() {
var map = document.getElementById("map");
var header = document.getElementById("header");
var subheader = document.getElementById("subheader");
map.style.height = (getWindowHeight()-80) + "px";
map.style.width = (getWindowWidth()-20) + "px";
header.style.width = (getWindowWidth()-20) + "px";
subheader.style.width = (getWindowWidth()-20) + "px";
if (map.updateSize) { map.updateSize(); };
}
function find_pic(lat, lng){
fh = fopen(getScriptPath('log wynikowy epsg 3857.csv'), 0);
fh_length = flength(fh);
var allText = fread(fh, fh_length);
var fldData =[];
for (x=0; x<allTextLines.length; x++){
fldData = allTextLines[x].split(',');
}
for (i=0; i<fldData.length.length; i++){
if (allTextLines[i].split(',')[0] == lat && allTextLines[i].split(',')[1] == lng){
var result = allTextLines[i].split(',')[2];
}
}
var link_pic = "/data/" + result + ".jpg";
return link_pic;
}
var overlay = new ol.Overlay({
element: container,
autoPan: true,
autoPanAnimation: {
duration: 250
}
}));
closer.onclick = function() {
overlay.setPosition(undefined);
closer.blur();
return false;
};
map.on('singleclick', function(evt) {
var coordinate = evt.coordinate;
var link_pic = find_pic(coordinate[0],coordinate[1]);
content.innerHTML = '<p>Link do oryginalnego zdjecia: <a href=link_pic>Klik</a></p>';
overlay.setPosition(coordinate);
});
onresize=function(){ resize(); };
var element = document.getElementById('popup');
</script>
</head>
<body onload="init()">
<div id="header"><h1>Ortofotomapa</h1></div>
<div id="subheader">Generated by MapTiler/GDAL2Tiles, Copyright © 2008 Klokan Petr Pridal, GDAL & OSGeo GSoC
<!-- PLEASE, LET THIS NOTE ABOUT AUTHOR AND PROJECT SOMEWHERE ON YOUR WEBSITE, OR AT LEAST IN THE COMMENT IN HTML. THANK YOU -->
</div>
<div id="map"></div>
<script type="text/javascript" >resize()</script>
</body>
</html>
EDIT:After this, page is all black. I want to have onclick popup, which will contain link to a big resolution photo.

Related

Please i need help: Trying to have my animation move from initial coordinates to new inputted coordinates using JavaScript

I have Layout with a machine, i intend to have this machine (purple animation) move from point A to point B based on input cordinate x and cordinate Y. I followed some online tutorials but still not been able to get it. The animation currently moves manually with arrow keys but i intend to have it move automatically. The aim is to have the animation move at a slow frame pace to the inserted coordinates. Any help will be appreciated.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> Farm Harvest </title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="grid"></div>
<input type="number" id = 'cords1' placeholder="X-Cordinates">
<input type="number" id = 'cords2' placeholder="Y-Cordinates">
<button id = "mybtn" onclick="myCords();">Get Value</button>
<script src="app.js"></script>
</body>
</html>
CSS:
.grid {
position: absolute;
width: 560px;
height: 300px;
border: solid 1px black;
margin-top: 100px;
}
.user {
position: absolute;
width: 30px;
height: 20px;
background-color: blueviolet;
}
.block {
position: absolute;
width: 100px;
height: 20px;
background-color: blue;
}
JS:
const grid = document.querySelector('.grid')
const value1 = document.getElementById('cord1')
const value2 = document.getElementById('cord2')
const blockWidth = 100
const blockHeight = 20
const boardWidth = 560
const boardHeight = 300
var mouseX, mouseY;
var stepWidthFactor = 200;
const userStart = [10, 270]
let currentPosition = userStarnst userStart1 = [10, 270]
let currentPosition1 = userStart1
const user1 = [10, 270]
let currentPosition2 = user1
//my block
class Block {
constructor(xAxis, yAxis) {
this.bottomLeft = [xAxis, yAxis]
this.bottomRight = [xAxis + blockWidth, yAxis]
this.topRight = [xAxis + blockWidth, yAxis + blockHeight]
this.topLeft = [xAxis, yAxis + blockHeight]
}
}
class moveblock{
constructor(xAxis,yAxis){
this.xAxis = inputval0;
this.yAxis = inputval1;
let currentPosition3 = user2;
}
}
//all my blocks
const blocks = [
new Block(120, 210),
new Block(230, 210),
new Block(340, 210),
new Block(120, 140),
new Block(230, 140),
new Block(340, 140),
new Block(120, 70),
new Block(230, 70),
new Block(340, 70),
]
//draw my blocks
function addBlocks() {
for (let i = 0; i < blocks.length; i++) {
const block = document.createElement('div')
block.classList.add('block')
block.style.left = blocks[i].bottomLeft[0] + 'px'
block.style.bottom = blocks[i].bottomLeft[1] + 'px'
grid.appendChild(block)
console.log(blocks[i].bottomLeft)
}
}
addBlocks()
//add user
const user = document.createElement('div')
user.classList.add('user')
grid.appendChild(user)
drawUser()
//move user
function moveUser(e) {
switch (e.key) {
case 'ArrowLeft':
if (currentPosition[0] > 0) {
currentPosition[0] -= 10
console.log(currentPosition[0] > 0)
drawUser()
}
break
case 'ArrowRight':
if (currentPosition[0] < (boardWidth - blockWidth)) {
currentPosition[0] += 10
console.log(currentPosition[0])
drawUser()
}
break
case 'ArrowDown':
if (currentPosition1[0] < (boardHeight - blockHeight)) {
currentPosition1[0] += 10
console.log(currentPosition1[0]>0)
drawUser()
}
break
case 'ArrowUp':
if (currentPosition1[0] > 0) {
currentPosition1[0] -= 10
console.log(currentPosition1[0])
drawUser()
}
break
}
}
document.addEventListener('keydown', moveUser)
//draw User
function drawUser() {
user.style.top = currentPosition1 [0] + 'px'
user.style.left = currentPosition[0] + 'px'
user.style.bottom = currentPosition[0] + 'px'
user.style.right = currentPosition[0] + 'px'
}
function myCords(){
const user2 = [inputval0,inputval1]
let currentPosition3 = user2;
var inputval0 = document.getElementById('cords1').value;
var inputval1 = document.getElementById('cords2').value;
if(inputval0 < boardHeight && inputval1 < boardWidth && inputval0 != 0 && inputval1 != 0){
alert("good cords " + "X: "+ inputval0 + " " +"Y: " +inputval1)
}
else{
alert("wrong cordinates")
}
}document.addEventListener('onclick',myCords)
function drawnewUser(){
user.style.left = currentPosition + 'px';
user.style.top = currentPosition + 'px'
user.style.bottom = currentPosition + 'px'
user.style.right = currentPosition + 'px'
}

I can't access timeline in main.js, timeline initialize in the file anim.js

Hello everyone I have such a problem. I have two scripts, anim.js and main.js . In anim.js describes the animation, and in main.js I'm trying to make a stop by pressing a button. I'm trying to make a stop through timeline, but I can't access timeline in main.js, timeline initialize in the file anim.js
anim.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="Adobe_Animate_CC" name="authoring-tool">
<title>anim</title>
<!-- write your code here -->
<style>
#animation_container {
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
body, canvas {
background: none transparent !important;
}
</style>
<script src="../js/libs/adobe/createjs.js"></script>
<script src="anim.js"></script>
<script>
var canvas, stage, exportRoot, anim_container, dom_overlay_container, fnStartAnimation;
function init() {
canvas = document.getElementById("canvas");
anim_container = document.getElementById("animation_container");
dom_overlay_container = document.getElementById("dom_overlay_container");
var comp = AdobeAn.getComposition("4D38855BFA773041952A1579DB0CC3CC");
var lib = comp.getLibrary();
var loader = new createjs.LoadQueue(false);
loader.addEventListener("fileload", function (evt) {
handleFileLoad(evt, comp)
});
loader.addEventListener("complete", function (evt) {
handleComplete(evt, comp)
});
var lib = comp.getLibrary();
loader.loadManifest(lib.properties.manifest);
}
function handleFileLoad(evt, comp) {
var images = comp.getImages();
if (evt && (evt.item.type == "image")) {
images[evt.item.id] = evt.result;
}
}
function handleComplete(evt, comp) {
//This function is always called, irrespective of the content. You can use the variable "stage" after it is created
//in token create_stage.
var lib = comp.getLibrary();
var ss = comp.getSpriteSheet();
var queue = evt.target;
var ssMetadata = lib.ssMetadata;
for (i = 0; i < ssMetadata.length; i++) {
ss[ssMetadata[i].name] = new createjs.SpriteSheet({
"images": [queue.getResult(ssMetadata[i].name)],
"frames": ssMetadata[i].frames
})
}
exportRoot = new lib.anim();
stage = new lib.Stage(canvas);
//Registers the "tick" event listener.
fnStartAnimation = function () {
stage.addChild(exportRoot);
createjs.Ticker.setFPS(lib.properties.fps);
createjs.Ticker.addEventListener("tick", stage);
};
//Code to support hidpi screens and responsive scaling.
AdobeAn.makeResponsive(true, 'both', true, 1, [canvas, anim_container, dom_overlay_container]);
AdobeAn.compositionLoaded(lib.properties.id);
fnStartAnimation();
}
</script>
<script src="../js/main.js"></script>
<script>
function doLoadIframe() {
console.log('catch1');
let msg = function() {
p = 'привет';
return p;
}
//отправка события родителю
parent.postMessage(msg(), '*');
parent.focus();
init();
//setTimeout(stpAnimDef, 100);
}
</script>
<script>
window.addEventListener("message", function(msg){
console.log(msg.data);
if (msg.data == 'stop') {
stopAnimation();
} else if (msg.data == 'play'){
playAnimation();
}
let text = document.querySelector('.textAnim');
text.value = msg.data;
});
</script>
<!-- write your code here -->
</head>
<body onload="doLoadIframe();" style="margin:0px;">
<div id="animation_container" style="width:1280px; height:720px">
<canvas height="720" id="canvas"
style="position: absolute; display: block;"
width="1280"></canvas>
<div id="dom_overlay_container"
style="pointer-events:none; overflow:hidden; width:1280px; height:720px; position: absolute; left: 0px; top: 0px; display: block;">
</div>
</div>
<input type='text' class='textAnim' />
</body>
</html>
anim.js
var timeline = new createjs.Timeline({paused: true});
(function (cjs, an) {
var p; // shortcut to reference prototypes
var lib={};var ss={};var img={};
lib.ssMetadata = [
{name:"anim_atlas_", frames: [[0,0,233,233]]}
];
// symbols:
(lib.CachedTexturedBitmap_1 = function() {
this.initialize(ss["anim_atlas_"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
// helper functions:
function mc_symbol_clone() {
var clone = this._cloneProps(new this.constructor(this.mode, this.startPosition, this.loop));
clone.gotoAndStop(this.currentFrame);
clone.paused = this.paused;
clone.framerate = this.framerate;
return clone;
}
function getMCSymbolPrototype(symbol, nominalBounds, frameBounds) {
var prototype = cjs.extend(symbol, cjs.MovieClip);
prototype.clone = mc_symbol_clone;
prototype.nominalBounds = nominalBounds;
prototype.frameBounds = frameBounds;
return prototype;
}
(lib.Символ1 = function(mode,startPosition,loop) {
this.initialize(mode,startPosition,loop,{});
// Слой_1
this.instance = new lib.CachedTexturedBitmap_1();
this.instance.parent = this;
this.instance.setTransform(-0.5,-0.5,0.5,0.5);
var t = cjs.Tween.get(this.instance).wait(1);
timeline.addTween(t/*cjs.Tween.get(this.instance).wait(1)*/);
}).prototype = getMCSymbolPrototype(lib.Символ1, new cjs.Rectangle(-0.5,-0.5,116.5,116.5), null);
// stage content:
(lib.anim = function(mode,startPosition,loop) {
this.initialize(mode,startPosition,loop,{});
// Слой_1
this.instance = new lib.Символ1();
this.instance.parent = this;
this.instance.setTransform(210.85,268.85,1,1,0,0,0,57.8,57.8);
var t1 = cjs.Tween.get(this.instance).wait(1).to({x:243.8},0).wait(1).to({x:276.8},0).wait(1).to({x:309.8},0).wait(1).to({x:342.8},0).wait(1).to({x:375.8},0).wait(1).to({x:408.8},0).wait(1).to({x:441.8},0).wait(1).to({x:474.8},0).wait(1).to({x:507.8},0).wait(1).to({x:540.8},0).wait(1).to({x:573.8},0).wait(1).to({x:606.8},0).wait(1).to({x:639.8},0).wait(1).to({x:672.8},0).wait(1).to({x:705.75},0).wait(1).to({x:738.75},0).wait(1).to({x:771.75},0).wait(1).to({x:804.75},0).wait(1).to({x:837.75},0).wait(1).to({x:870.75},0).wait(1).to({x:903.75},0).wait(1).to({x:936.75},0).wait(1).to({x:969.75},0).wait(1).to({x:1002.75},0).wait(1).to({x:1035.75},0).wait(1).to({x:1068.75},0).wait(1).to({x:1101.75},0).wait(1).to({x:1134.75},0).wait(1).to({x:1167.75},0).wait(1)
.call(function(){
this.dispatchEvent("foo");
}, null, timeline);
timeline.addTween(t1);
timeline.setPaused(false);
//this.timeline.addTween(cjs.Tween.get(this.instance, {reversed:true})./*wait(1).to({x:243.8},0).wait(1).to({x:276.8},0).wait(1).to({x:309.8},0).wait(1).to({x:342.8},0).wait(1).to({x:375.8},0).wait(1).to({x:408.8},0).wait(1).to({x:441.8},0).wait(1).to({x:474.8},0).wait(1).to({x:507.8},0).*/wait(1).to({x:540.8},0).wait(1).to({x:573.8},0).wait(1).to({x:606.8},0).wait(1).to({x:639.8},0).wait(1).to({x:672.8},0).wait(1).to({x:705.75},0).wait(1).to({x:738.75},0).wait(1).to({x:771.75},0).wait(1).to({x:804.75},0).wait(1).to({x:837.75},0).wait(1).to({x:870.75},0).wait(1).to({x:903.75},0).wait(1).to({x:936.75},0).wait(1).to({x:969.75},0).wait(1).to({x:1002.75},0).wait(1).to({x:1035.75},0).wait(1).to({x:1068.75},0).wait(1).to({x:1101.75},0).wait(1).to({x:1134.75},0).wait(1).to({x:1167.75},0).wait(1));
//this.timeline.addTween(cjs.Tween.get(this.instance).wait(1).to({x:540.8},0).wait(1).to({x:573.8},0).wait(1).to({x:606.8},0).wait(1).to({x:639.8},0).wait(1).to({x:672.8},0).wait(1).to({x:705.75},0).wait(1).to({x:738.75},0).wait(1).to({x:771.75},0).wait(1).to({x:804.75},0).wait(1).to({x:837.75},0).wait(1).to({x:870.75},0).wait(1).to({x:903.75},0).wait(1).to({x:936.75},0).wait(1).to({x:969.75},0).wait(1).to({x:1002.75},0).wait(1).to({x:1035.75},0).wait(1).to({x:1068.75},0).wait(1).to({x:1101.75},0).wait(1).to({x:1134.75},0).wait(1).to({x:1167.75},0).wait(1).to({x:1134.75},0).wait(1).to({x:1101.75},0).wait(1).to({x:1068.75},0).wait(1).to({x:1035.75},0).wait(1).to({x:1002.75},0).wait(1).to({x:969.75},0).wait(1).to({x:936.75},0).wait(1).to({x:903.75},0).wait(1).to({x:870.75},0).wait(1).to({x:837.75},0).wait(1).to({x:804.75},0).wait(1).to({x:771.75},0).wait(1).to({x:738.75},0).wait(1).to({x:705.75},0).wait(1).to({x:672.8},0).wait(1).to({x:639.8},0).wait(1).to({x:606.8},0).wait(1).to({x:573.8},0).wait(1).to({x:540.8},0).wait(1));
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(792.6,570.6,433.30000000000007,-243.5);
// library properties:
lib.properties = {
id: '4D38855BFA773041952A1579DB0CC3CC',
width: 1280,
height: 720,
fps: 20,
color: "#FFFFFF",
opacity: 1.00,
manifest: [
{src:"images/anim_atlas_.png", id:"anim_atlas_"}
],
preloads: []
};
// bootstrap callback support:
(lib.Stage = function(canvas) {
createjs.Stage.call(this, canvas);
}).prototype = p = new createjs.Stage();
p.setAutoPlay = function(autoPlay) {
this.tickEnabled = autoPlay;
}
p.play = function() { this.tickEnabled = true; this.getChildAt(0).gotoAndPlay(this.getTimelinePosition()) }
p.stop = function(ms) { if(ms) this.seek(ms); this.tickEnabled = false; }
p.seek = function(ms) { this.tickEnabled = true; this.getChildAt(0).gotoAndStop(lib.properties.fps * ms / 1000); }
p.getDuration = function() { return this.getChildAt(0).totalFrames / lib.properties.fps * 1000; }
p.getTimelinePosition = function() { return this.getChildAt(0).currentFrame / lib.properties.fps * 1000; }
an.bootcompsLoaded = an.bootcompsLoaded || [];
if(!an.bootstrapListeners) {
an.bootstrapListeners=[];
}
an.bootstrapCallback=function(fnCallback) {
an.bootstrapListeners.push(fnCallback);
if(an.bootcompsLoaded.length > 0) {
for(var i=0; i<an.bootcompsLoaded.length; ++i) {
fnCallback(an.bootcompsLoaded[i]);
}
}
};
an.compositions = an.compositions || {};
an.compositions['4D38855BFA773041952A1579DB0CC3CC'] = {
getStage: function() { return exportRoot.getStage(); },
getLibrary: function() { return lib; },
getSpriteSheet: function() { return ss; },
getImages: function() { return img; }
};
an.compositionLoaded = function(id) {
an.bootcompsLoaded.push(id);
for(var j=0; j<an.bootstrapListeners.length; j++) {
an.bootstrapListeners[j](id);
}
}
an.getComposition = function(id) {
return an.compositions[id];
}
an.makeResponsive = function(isResp, respDim, isScale, scaleType, domContainers) {
var lastW, lastH, lastS=1;
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
function resizeCanvas() {
var w = lib.properties.width, h = lib.properties.height;
var iw = window.innerWidth, ih=window.innerHeight;
var pRatio = window.devicePixelRatio || 1, xRatio=iw/w, yRatio=ih/h, sRatio=1;
if(isResp) {
if((respDim=='width'&&lastW==iw) || (respDim=='height'&&lastH==ih)) {
sRatio = lastS;
}
else if(!isScale) {
if(iw<w || ih<h)
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==1) {
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==2) {
sRatio = Math.max(xRatio, yRatio);
}
}
domContainers[0].width = w * pRatio * sRatio;
domContainers[0].height = h * pRatio * sRatio;
domContainers.forEach(function(container) {
container.style.width = w * sRatio + 'px';
container.style.height = h * sRatio + 'px';
});
stage.scaleX = pRatio*sRatio;
stage.scaleY = pRatio*sRatio;
lastW = iw; lastH = ih; lastS = sRatio;
stage.tickOnUpdate = false;
stage.update();
stage.tickOnUpdate = true;
}
}
})(createjs = createjs||{}, AdobeAn = AdobeAn||{});
var createjs, AdobeAn;
main.js
function stopAnimation() {
console.log(timeline);
}
Cut and paste you all script to bottom of body htm tag

Delete function fails when there is more than 1 marker on Google Maps

I am working on Google Maps feature that allows people to drag markers from a sidebar and place them on a map. When a user clicks a marker the info window pops up and gives some data along with a delete button.
This delete button works fine when there is only 1 marker on the map, but when there is more than one it fails to delete the right marker (as you can see from the gif below).
This is what I have for my JavaScript
var map, iw, drag_area, actual, mark;
var overview, zIndex = 0;
newMarkers = []; //declare empty markers array
id = 0; //marker id set at 0
function helper() {
this.setMap(map);
this.draw = function() {};
}
helper.prototype = new google.maps.OverlayView();
function fillMarker(icon) {
var div = document.createElement("div");
div.style.backgroundImage = "url(" + icon + ")";
var left;
if (mark.id == "m1") {
left = "0px";
} else if (mark.id == "m2") {
left = "50px";
} else if (mark.id == "m3") {
left = "100px";
}
div.style.left = left;
div.id = mark.id;
div.className = "drag";
div.onmousedown = div.ontouchstart = initDrag;
drag_area.replaceChild(div, mark);
mark = null;
}
function createDraggedMarker(latlng, icon) {
var icon = {
url: icon,
size: new google.maps.Size(32, 32),
anchor: new google.maps.Point(15, 32)
};
marker = new google.maps.Marker({
position: latlng,
map: map,
clickable: true,
draggable: true,
crossOnDrag: false,
optimized: false,
icon: icon,
zIndex: zIndex,
id: id++ //increment the ID
});
newMarkers.push(marker);
google.maps.event.addListener(marker, "click", function() {
actual = marker;
var lat = actual.getPosition().lat();
var lng = actual.getPosition().lng();
var contentStr = "<div class='infowindow'>" + lat.toFixed(6) + ", " + lng.toFixed(6) + "<\/div>";
var delMe = "<br /><input type = 'button' value = 'Delete' onclick = 'DeleteMarker(" + marker.id + ")' value = 'Delete' />"
iw.setContent(contentStr + delMe);
iw.open(map, this);
});
google.maps.event.addListener(marker, "dragstart", function() {
if (actual == marker) iw.close();
zIndex += 1;
marker.setZIndex(zIndex);
});
}
function initDrag(evt) {
function getPt(evt) {
var pt = {};
if (evt && evt.touches && evt.touches.length) {
pt.x = evt.touches[0].clientX;
pt.y = evt.touches[0].clientY;
} else {
if (!evt) var evt = window.event;
pt.x = evt.clientX;
pt.y = evt.clientY;
}
return pt;
};
var drag = function(mEvt) {
if (mark && mark.className == "drag") {
var pt = getPt(mEvt),
x = pt.x - o.x,
y = pt.y - o.y;
mark.style.left = (mark.x + x) + "px";
mark.style.top = (mark.y + y) + "px";
mark.onmouseup = mark.ontouchend = function() {
var mapDiv = map.getDiv(),
mapLeft = mapDiv.offsetLeft,
mapTop = mapDiv.offsetTop,
mapWidth = mapDiv.offsetWidth,
mapHeight = mapDiv.offsetHeight;
var dragLeft = drag_area.offsetLeft,
dragTop = drag_area.offsetTop,
iconWidth = mark.offsetWidth,
iconHeight = mark.offsetHeight;
var newLeft = mark.offsetLeft + dragLeft + iconWidth / 2;
var newTop = mark.offsetTop + dragTop + iconHeight / 2;
if (dragLeft > mapLeft && newLeft < (mapLeft + mapWidth) && newTop > mapTop && newTop < (mapTop + mapHeight)) {
var offset = 1;
var divPt = new google.maps.Point(newLeft - mapLeft - offset, newTop - mapTop + (iconHeight / 2));
var proj = overview.getProjection();
var latlng = proj.fromContainerPixelToLatLng(divPt);
var icon = mark.style.backgroundImage.slice(4, -1).replace(/"/g, "");
createDraggedMarker(latlng, icon);
fillMarker(icon);
}
};
}
return false;
};
if (!evt) var evt = window.event;
mark = evt.target ? evt.target : evt.srcElement ? evt.srcElement : evt.touches ? evt.touches[0].target : null;
if (mark.className != "drag") {
if (d.cancelable) d.preventDefault();
mark = null;
return;
} else {
zIndex++;
mark.style.zIndex = zIndex.toString();
mark.x = mark.offsetLeft;
mark.y = mark.offsetTop;
var o = getPt(evt);
if (evt.type === "touchstart") {
mark.onmousedown = null;
mark.ontouchmove = drag;
mark.ontouchend = function() {
mark.ontouchmove = null;
mark.ontouchend = null;
mark.ontouchstart = initDrag;
};
} else {
document.onmousemove = drag;
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
if (mark) mark = null;
};
}
}
return false;
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.052491, 9.84375),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]
},
panControl: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
iw = new google.maps.InfoWindow();
google.maps.event.addListener(map, "click", function() {
if (iw) iw.close();
});
drag_area = document.getElementById("markers");
var divArray = drag_area.getElementsByTagName("div");
for (var i = 0; i < divArray.length; i++) {
var div = divArray[i];
div.onmousedown = div.ontouchstart = initDrag;
}
overview = new helper();
}
//Delete the marker by ID
function DeleteMarker(id) {
for (var i = 0; i < newMarkers.length; i++) {
if (newMarkers[i].id == marker.id) {
console.log("This ID: " + this.marker.id);
//markers[i].setMap(null);
newMarkers[i].setMap(null);
newMarkers.splice(i, -1);
return;
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
body,
html {
height: 100%;
width: 100%;
}
#map {
float: left;
margin: 0 25px 10px 14px;
width: 64%;
height: 70%;
}
#desc {
float: left;
margin: 0 25px 10px 20px;
width: 10em;
}
#markers {
position: absolute;
top: 140px;
left: 70%;
width: 200px;
height: 110px;
}
.drag {
position: absolute;
width: 32px;
height: 32px;
}
.infowindow {
margin-top: 20px;
width: 180px;
height: 60px;
}
#media screen and (max-width: 890px) {
body,
html,
#map {
margin: 0;
}
#map {
width: 100%;
height: 50%;
}
#desc {
margin: 100px 14px 0;
width: 93%;
}
.include >b {
float: right;
margin-top: 17px;
}
#markers {
/* center horizontal and do not overlap the map */
position: absolute;
top: 50%;
left: 50%;
width: 10em;
height: 6em;
margin-top: 5em;
margin-left: -5em;
}
#markers > p {
margin-top: 0;
font-size: 80%;
}
.infowindow {
margin-top: 10px;
width: 150px;
height: 25px;
}
}
<h3>Delete button does not work when there is more than 1 marker</h3>
<div id="map"></div>
<div id="desc"></div>
<div id="markers">
<p>Drag the markers to a location on the map</p>
<div id="m1" class="drag" style="left:0; background-image: url('http://maps.google.com/mapfiles/ms/micons/blue.png')"></div>
<div id="m2" class="drag" style="left:50px; background-image: url('http://maps.google.com/mapfiles/ms/micons/green.png')"></div>
<div id="m3" class="drag" style="left:100px; background-image: url('http://maps.google.com/mapfiles/ms/micons/yellow.png')"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
So yeah, the delete button only works if there is only 1 Marker on the map, anything more than that and it fails.
Here is my Fiddle: http://jsfiddle.net/xpvt214o/797910/
I think the problem lies in the fact that you're defining marker as global in createDraggedMarker, therefore marker always has the reference to the last added marker thus delete only works on the last added marker.
Changes to make it work:
Make marker local to the method createDraggedMarker
modify DeleteMarker so that it uses the argument id to search in the array for the marker to delete instead of marker.id
The rest remains unchanged.
I marked the changes in the code with comments.
Working fiddle

How can i implement a simple menu for my game made with HTML?

i'm making a simple game with HTML only, more or less it works... My question is if i can make a simple menu /with "click to start" or something similar/ with an image at the background and 1 button to start the game. And if i can make it in the same archive.
Thanks.
<canvas id="ctx" width="1024" height="800" style="border:3px solid #000000;"></canvas>
<script>
var Height = 800;
var Width = 1024;
var timeElapset = Date.now();
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Consolas';
var frameCount = 0;
var score = 0;
var player = {
x:50,
spdX:30,
y:40,
spdY:30,
name:'P',
hp:10,
width:20,
height:20,
color:'green',
};
var enemyList = {};
getDistance = function (Obj1,Obj2){
var vx = Obj1.x - Obj2.x;
var vy = Obj1.y - Obj2.y;
return Math.sqrt((vx*vx)+(vy*vy));
}
checkCollision = function (Obj1,Obj2){
var rect1 = {
x: Obj1.x - Obj1.width/2,
y: Obj1.y - Obj1.height/2,
height: Obj1.height,
width: Obj1.width,
}
var rect2 = {
x: Obj2.x - Obj2.width/2,
y: Obj2.y - Obj2.height/2,
height: Obj2.height,
width: Obj2.width,
}
return testCollisionRectRect(rect1,rect2); //true o false
}
Enemy = function (id,x,y,spdX,spdY,width,height){
var enemy = {
x:x,
spdX:spdX,
y:y,
spdY:spdY,
name:'E',
id:id,
width:width,
height:height,
color:'black',
};
enemyList[id] = enemy;
}
document.onmousemove = function(mouse){
var mouseX = mouse.clientX - document.getElementById('ctx').getBoundingClientRect().left;
var mouseY = mouse.clientY - document.getElementById('ctx').getBoundingClientRect().top;
if(mouseX < player.width/2)
mouseX = player.width/2;
if(mouseX > Width-player.width/2)
mouseX = Width - player.width/2;
if(mouseY < player.height/2)
mouseY = player.height/2;
if(mouseY > Height - player.height/2)
mouseY = Height - player.height/2;
player.x = mouseX;
player.y = mouseY;
}
updateEntity = function (Z){
updatePosition(Z);
drawPlayer(Z);
}
updatePosition = function(Z){
Z.x += Z.spdX;
Z.y += Z.spdY;
if(Z.x < 0 || Z.x > Width){
Z.spdX = -Z.spdX;
}
if(Z.y < 0 || Z.y > Height){
Z.spdY = -Z.spdY;
}
}
testCollisionRectRect = function(rect1,rect2){
return rect1.x <= rect2.x+rect2.width &&
rect2.x <= rect1.x+rect1.width &&
rect1.y <= rect2.y + rect2.height &&
rect2.y <= rect1.y + rect1.height;
}
drawPlayer = function(Z){
ctx.save();
ctx.fillStyle = Z.color;
ctx.fillRect(Z.x-Z.width/2,Z.y-Z.height/2,Z.width,Z.height);
ctx.restore();
}
update = function(){
ctx.clearRect(0,0,Width,Height);
frameCount++;
score++;
if(frameCount % 100 == 0)
randomGenerateEnemy();
for(var key in enemyList){
updateEntity(enemyList[key]);
var isColliding = checkCollision(player, enemyList[key]);
if(isColliding){
player.hp = player.hp -1;
}
}
if(player.hp <= 0){
var timeSurvived = Date.now() - timeElapset;
console.log("Has ganado Kappa, Tiempo vivo " + timeSurvived + " ms.");
ctx.fillText(" You Lose! ", Width/2, Height/2);
GameEngine();
}
drawPlayer(player);
ctx.fillText(player.hp + " Hp",20,30);
ctx.fillText('Puntuacion: ' + score/10,700,30);
}
GameEngine = function(){
player.hp = 13;
timeElapset = Date.now();
frameCount = 0;
score = 0;
enemyList = {};
randomGenerateEnemy();
randomGenerateEnemy();
randomGenerateEnemy();
randomGenerateEnemy();
}
randomGenerateEnemy = function(){
var x = Math.random()*Width;
var y = Math.random()*Height;
var height = 10 + Math.random()*70;
var width = 10 + Math.random()*70;
var id = Math.random();
var spdX = 5 + Math.random() * 5;
var spdY = 5 + Math.random() * 5;
Enemy(id,x,y,spdX,spdY,width,height);
}
GameEngine();
setInterval(update,30);
</script>
That's what i have.
The code also contains javascript.For proper gaming function .js file has to be called on your html page.Also use css to make it attractive.Consider this example
enter code here
<html>
<head>
<title>Your game title</title>
<script type="text/javascript" src="src/Common.js"></script>
<script type="text/javascript" src="src/Perlin.js"></script>
<script type="text/javascript" src="src/ChaikinCurve.js"></script>
<script type="text/javascript">
var app = null;
window.onload = function() {
utils.loadShaderXml("src/render/shaders.xml", null, function(shaders) {
if (shaders instanceof Exception) {
app = shaders;
} else {
try {
app = new App('canvas', shaders, null);
} catch (e) {
app = e;
}
}
});
document.onselectstart = function () {
return false;
};
};
function application() {
if (app == null) {
alert("Application is absent");
throw "no application";
} else if (app instanceof Exception) {
alert("An exception occured while creating the application:\n" + app.message);
throw app;
} else {
return app;
}
}
</script>
<style type="text/css">
body{
margin: 0px; padding: 0px; overflow: hidden;
background: #000;
}
#canvas-holder.active {
position: absolute;
padding: 0px;
left: 50%;
top: 50%;
}
#canvas-holder.inactive {
position: absolute;
top:50%;
width: 100%;
text-align: center;
}
#canvas {
padding: 0px;
width: 100%;
height: 100%;
color: #fff;
font-family: Allan, Arial;
font-size: 40px;
}
</style>
</head>
<body>
<div id="canvas-holder" class="inactive">
<div id="canvas">Your game` is loading...</div>
</div>
<div style="font-family: Lobster; visibility: hidden">one</div>
<div style="font-family: Allan; visibility: hidden">two</div>
<div style="font-family: Meddon; visibility: hidden">three</div>
<div style="font-family: Cuprum; visibility: hidden">four</div>
</body>
</html>

Draw a bendable arrow between two html elements

I am developing a view for some items in my web site. Currently I have the items displayed in the HTML but now I need to draw some lines between the elements that will represent a connection between them, it's like a Gantt Chart but it doesn't include any time functionality, I only need to connect the items with the ones associated to them. I'm using JSTL to bring some data from a controller and I managed to draw the elements like the following image: http://i271.photobucket.com/albums/jj131/djrickel/before.png
And the way I need to display is in the following image:
http://i271.photobucket.com/albums/jj131/djrickel/after.png
This is how I'm creating my table containing the elements that I want to display:
<div class="container">
<table>
<tbody>
<c:forEach items="${nodeGraphs}" var="nodeGraph">
<tr>
<c:forEach var="i" begin="0" end="5">
<td>
<c:if test="${nodeGraph.columnID == i}">
<label class="label label-default">${nodeGraph.nodeObject.item.type}${nodeGraph.nodeObject.item.contextId}</label>
</c:if>
</td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
</div>
Does anyone know a way to create connecting lines between the elements using JQuery, JSon, Javascript or any HTML process? I can change from the table I'm using to div or span without any issue. I'm just looking the best way to display the information. Thanks in advance.
Probably the best way to do that is use HTML5 canvas, but if You want use div's try use this code:
(On JSFiddle: http://fiddle.jshell.net/22rar61n/9/)
var Line = (function() {
var diff = function(a, b) {
var d = Math.abs(a - b);
if (d === 0) {
d = 1;
}
return d;
}
var countWidth = function(line) {
return diff(line.endX, line.startX);
};
var countHeight = function(line) {
return diff(line.endY, line.startY);
};
var Line = function(options) {
this.startX = options.startX;
this.startY = options.startY;
this.endX = options.endX;
this.endY = options.endY;
}
Line.prototype.drowIn = function($container) {
var self = this;
var line = jQuery("<div></div>", {
class: "line " + self.LineType(),
css: {
"color": "red",
"top": self.startY,
"left": self.startX,
"width": countWidth(self),
"height": countHeight(self),
"background-color": "#000"
}
});
$container.append(line);
};
Line.prototype.LineType = function() {
if (this.startX != this.endX) {
return "horizontal";
}
return "vertical";
}
return Line;
})();
var Arrow = (function() {
var Arrow = function(start, end) {
this.start = start;
this.end = end;
}
Arrow.prototype.drowIn = function($container) {
var ArrowContainer = jQuery("<div></div>", {
class: "arrowContainer"
});
var line1 = new Line({
startX: this.start.x,
startY: this.start.y,
endX: this.start.x,
endY: this.end.y
});
line1.drowIn(ArrowContainer);
var line2 = new Line({
startX: this.start.x,
startY: this.end.y,
endX: this.end.x,
endY: this.end.y
});
line2.drowIn(ArrowContainer);
$container.append(ArrowContainer);
}
return Arrow;
})();
var Element = (function() {
var Element = function(options) {
var op = jQuery.extend({}, options);
this.x = op.x || -1;
this.y = op.y || -1;
this.content = op.content || "";
this.container = op.$container || "";
this.node = null;
this.subElements = [];
};
Element.prototype.addSubElement = function(element) {
element.container = this.container;
element.content = this.content + "." + (this.subElements.length + 1);
this.subElements.push(element);
};
Element.prototype.drow = function() {
var self = this;
this.node = jQuery("<div></div>", {
class: "element",
text: this.content,
css: {
top: self.y,
left: self.x
}
});
this.container.append(this.node);
var nexLvl = 0;
var lastHeight = nexLvl;
var lastLvl = 0;
var oldIndex = -1;
var outerHeightAndTop = jQuery(self.node).outerHeight() + jQuery(self.node).offset().top;
jQuery.each(this.subElements, function(index, element) {
var height = outerHeightAndTop * (index + 1 + lastLvl);
if (lastHeight != 0) {
height = lastHeight + outerHeightAndTop;
}
if (nexLvl != 0) {
oldIndex = index;
height = height + ((jQuery(self.node).outerHeight()) * nexLvl);
lastLvl = nexLvl;
}
lastHeight = height;
nexLvl = element.getMaxLevel();
element.x = jQuery(self.node).outerWidth() + jQuery(self.node).offset().left;
element.y = height;
element.drow();
self.connectWith(element);
});
};
Element.prototype.connectWith = function(element) {
var startY = jQuery(this.node).outerHeight() + this.y;
var startX = (jQuery(this.node).outerWidth() / 2) + this.x;
var endY = (jQuery(element.node).outerHeight() / 2) + element.y;
var arrow = new Arrow({
x: startX,
y: startY
}, {
x: element.x,
y: endY
});
arrow.drowIn(this.container);
};
function getLevelOnPosition(index) {
return this.subElements[index].getMaxLevel();
}
Element.prototype.getMaxLevel = function(initLvl) {
var lvl = initLvl || 0;
var maxLvl = lvl;
if (this.subElements.length > 0) {
maxLvl = lvl++;
}
jQuery.each(this.subElements, function(index, element) {
lvl = element.getMaxLevel(lvl);
if (lvl > maxLvl) {
maxLvl = lvl;
}
});
return maxLvl;
}
return Element;
})();
jQuery(document).ready(function() {
var container = jQuery("#container");
var e = new Element({
x: 10,
y: 10,
content: "a1",
$container: container
});
var sube = new Element();
e.addSubElement(sube);
var sube2 = new Element();
sube.addSubElement(sube2);
sube2.addSubElement(new Element());
var e2 = new Element();
e.addSubElement(e2);
e2.addSubElement(new Element());
e.addSubElement(new Element());
e.drow();
});
#container {
position: relative;
}
#container > .element {
position: absolute;
border: 1px solid black;
background-color: gray;
color: white;
padding: 2px;
z-index: 10;
}
#container > .arrowContainer {
position: absolute;
}
#container > .arrowContainer > .line {
position: absolute;
z-index: 50;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container"></div>

Categories