I want to change this random function to onclick function - javascript

I am actually creating circles on page randomly and I want to draw these onclick function. But Which code I have is random function which randomly distribute on page. So how can I change this code to onclick ?
<!DOCTYPE html>
<html lang='en'>
<head>
<html>
<input type="text" name="test" style="width: 130px; height: 30px "value="" id="text" placeholder="Enter length"/>
</html>
<meta charset='utf-8' />
<script type='text/javascript' src='OpenLayers.js'></script>
<script type='text/javascript'>
var map;
var vector_layer;
function init() {
//Create a map with an empty array of controls
map = new OpenLayers.Map('map_element');
//Create a base layer
var wms_layer = new OpenLayers.Layer.WMS(
'OpenLayers WMS',
'http://vmap0.tiles.osgeo.org/wms/vmap0',
{layers: 'basic'},
{}
);
map.addLayer(wms_layer);
//Add vector layer
vector_layer = new OpenLayers.Layer.Vector('Settlement Vector Layer');
map.addLayer(vector_layer);
var settlement_values = {
4: 'circle'
}
//Create some points
for(var i=0; i<20; i++){
vector_layer.addFeatures([new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(
(Math.floor(Math.random() * 360) - 180),
(Math.floor(Math.random() * 180) - 90)
),
{
'settlement_type': settlement_values[(Math.floor(Math.random() * 15))]
}
)]);
}
//Create a style map object
var vector_style_map = new OpenLayers.StyleMap({});
//ADD RULES
//We need to create a 'lookup table' that contains the desired values
// and corresponding symbolizer
var x=document.getElementById("text").value;
var symbolizers_lookup = {
'circle': {
'fillColor': '#336699','fillOpacity':.8, 'pointRadius':x, 'strokeColor': '#003366', 'strokeWidth':2
}
}
//Now, call addUniqueValueRules and pass in the symbolizer lookups
vector_style_map.addUniqueValueRules('default', 'settlement_type', symbolizers_lookup);
//Add the style map to the vector layer
vector_layer.styleMap = vector_style_map;
if(!map.getCenter()){
map.zoomToMaxExtent();
}
}
</script>
</head>
<body onload='init();'>
<div id='map_element' style='width: 600px; height: 600px;'></div>
</body>
</html>

Change onload to onclick in your body tag.
<body onclick='init();'> <!-- <======== HERE -->
<div id='map_element' style='width: 600px; height: 600px;'></div>
</body>
</html>

Related

Cannot delete buttons using js

I can't delete two <button> tags using javascript. When you enter the wrong pin, I want the buttons to delete themselves but somehow it's not working.
var radar = document.getElementsByTagName("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin) {
document.write("Podany pin: " + pin_request);
alert("Podano właściwy pin.");
} else {
document.write("odmowa dostępu.");
radar.parentNode.removeChild(radar);
}
<html>
<head>
<meta charset="UTF-8">
<style>
html {
text-align: center;
padding: 7em;
display: block;
}
button {
margin: 1cm;
}
</style>
</head>
<body><br>
<button>dodaj pieniądze</button>
<button>zainwestuj w nieruchomości</button>
<script src="do visual studio code.js"></script>
</body>
</html>
Also sorry for half-English code.
You can use querySelectorAll to get elements and in loop remove them.
var radar = document.querySelectorAll("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin)
{
document.write("Podany pin: "+pin_request);
alert("Podano właściwy pin.");
}
else {
document.write("odmowa dostępu.");
radar.forEach(el=>{
el.remove();
})
}
<html>
<head>
<meta charset="UTF-8">
<style>
html{text-align:center; padding:7em; display:block;}
button{
margin:1cm;
}
</style>
</head>
<body><br>
<button>dodaj pieniądze</button>
<button>zainwestuj w nieruchomości</button>
<script src="do visual studio code.js"></script>
</body>
getElementyByTagName() returns an array of elements, but removeChild() only takes one element as an argument. If you use a loop it should work:
var parent = radar[0].parentNode
for(var i = 0; i < radar.length; i++) {
parent.removeChild(radar[i])
}
<!DOCTYPE HTML5>
<html>
<head>
<meta charset="UTF-8">
<style>
html{text-align:center; padding:7em; display:block;}
button{
margin:1cm;
}
</style>
</head>
<body><br>
<button>dodaj pieniądze</button>
<button>zainwestuj w nieruchomości</button>
<script>
var radar = document.querySelectorAll("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin)
{
document.write("Podany pin: "+pin_request);
alert("Podano właściwy pin.");
}
else {
document.write("odmowa dostępu.");
radar.forEach(ele =>{
ele.remove();
})
}
</script>
</body>
</html>
This should work
var radar = document.getElementsByTagName("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin)
{
document.write("Podany pin: "+pin_request);
alert("Podano właściwy pin.");
}
else {
document.write("odmowa dostępu.");
var elem = document.getElementById('btn1');
elem.parentNode.removeChild(elem);
var elem2 = document.getElementById('btn2');
elem2.parentNode.removeChild(elem2);
}
<button id = 'btn1'>dodaj pieniądze</button>
<button id = 'btn2'>zainwestuj w nieruchomości</button>

Longitude, Latitude to OSM pixel in 256x256 Tile

OpenStreetMap (OSM) have a Tile server. A tile is a 256x256 image of the world in a specific zoom.
I have longitude and latitude and I can find the correct tile by using this function.
function long2tile(lon,zoom) {return (Math.floor((lon+180)/360*Math.pow(2,zoom))); }
function lat2tile(lat,zoom) { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); }
var zoom = 4;
var x= long2tile(13.393562,zoom);
var y = lat2tile(52.519582,zoom);
document.getElementById('a').src='https://tile.openstreetmap.org/'+zoom+'/'+ x+'/'+y+'.png';
<img src="" id="a" style="border:1px solid black"/>
My problem is that Id like to know what coordinate in the 256x256 pixel is the location i set.
How to get the x-y coordiaten inside this one tile?
The rounding makes the difference!
function lo2t(lon,zoom){
return (lon+180)/360*Math.pow(2,zoom);
}
function la2t(lat,zoom){
return (1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom);
}
function long2tile(lon,zoom) {return Math.floor(lo2t(lon,zoom)); }
function lat2tile(lat,zoom) {return Math.floor(la2t(lat,zoom)); }
function long2tfac(lon,zoom) {
return long2tile(lon,zoom)-lo2t(lon,zoom);
}
function lat2tfac(lat,zoom) {
return lat2tile(lat,zoom)-la2t(lat,zoom);
}
var zoom = 4;
var x= long2tile(13.393562,zoom);
var y = lat2tile(52.519582,zoom);
document.getElementById('a').src='https://tile.openstreetmap.org/'+zoom+'/'+ x+'/'+y+'.png';
var point = document.getElementById('point');
var pos=";"; pos+="left:"+long2tfac(13.393562,zoom)*-256;
pos+="px;top:"+lat2tfac(52.519582,zoom)*-256;
point.setAttribute('style',point.getAttribute('style')+pos+'px;');
<img src="" id="a" style="border:1px solid black"/>
<div id="point" style="display:block; position:absolute; width:30px; height:30px; border:1px solid black; border-radius:15px;"> </div>
You can use the OpenLayers library for that purpose, it can manage all sort of calculations and transformations for you:
const source = new ol.source.OSM();
const grid = source.getTileGrid();
const projectedCoordinate=ol.proj.fromLonLat([13.393562,52.519582], "EPSG:3857");
const tileCoord = grid.getTileCoordForCoordAndZ(projectedCoordinate, 4/*zoom-level*/);
const projectedExtent=grid.getTileCoordExtent(tileCoord);
const extent = ol.proj.transformExtent(projectedExtent, ol.proj.get('EPSG:3857'), ol.proj.get('EPSG:4326'));
const yWidth=extent[2]-extent[0];
const xWidth=extent[3]-extent[1];
const tileUrlFunction = source.getTileUrlFunction();
const url=tileUrlFunction(tileCoord, 1, ol.proj.get('EPSG:3857'))
function convertPixelToLonLat(xPixel,yPixel){
if(!(xPixel>=0 && xPixel<=256)){
throw new Error('invalid xPixel');
}
if(!(yPixel>=0 && yPixel<=256)){
throw new Error('invalid yPixel');
}
return {lon:extent[1]+xWidth/256*xPixel,lat:extent[2]-yWidth/256*yPixel}
}
document.querySelector('img').src=url;
console.log("top-left of tile:",convertPixelToLonLat(0,0))
console.log("bottom-right of tile:",convertPixelToLonLat(256,256))
console.log("middle of tile:",convertPixelToLonLat(128,128))
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<title>Test</title>
</head>
<body>
<img />
</body>
</html>

I am autoincrementing the value of an input element. I want to get the value

I am using the value of an input element as a measurement of the radius of a google maps circle. I want the value of the input element to increase every second and immediately use the value as the radius of the circle. I was sort of able to do this but I have to change the value myself for it to work. I want the radius of the circle to automatically increase.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="datetime">
Number: <input type="number" id="time" value="40">
</div>
<script>
function timeInterval() {
setInterval(function(){
document.getElementById("time").stepUp(10);
}, 1000);
}
window.onload = timeInterval;
function initMap() {
var annArbor = {lat: 42.271084, lng: -83.737277};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: annArbor
});
var circle = new google.maps.Circle( {
map : map,
center : annArbor,
radius : parseInt(document.getElementById("time").value),
editable : false,
strokeColor : '#FF0099',
strokeOpacity : 1,
strokeWeight : 2,
fillColor : '#009ee0',
fillOpacity : 0.2
} );
var time = document.getElementById('time');
time.addEventListener('input', function() {
circle.setRadius(parseInt(document.getElementById('time').value));
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
</body>
</html>
Just update circle on both input & interval.
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="datetime">
Number: <input type="number" id="time" value="40">
</div>
<script>
function timeInterval() {
setInterval(function(){
document.getElementById("time").stepUp(10);
setRadius()
}, 1000);
}
window.onload = timeInterval;
var circle;
function setRadius(){
circle.setRadius(parseInt(document.getElementById('time').value));
}
function initMap() {
var annArbor = {lat: 42.271084, lng: -83.737277};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: annArbor
});
circle = new google.maps.Circle( {
map : map,
center : annArbor,
radius : parseInt(document.getElementById("time").value),
editable : false,
strokeColor : '#FF0099',
strokeOpacity : 1,
strokeWeight : 2,
fillColor : '#009ee0',
fillOpacity : 0.2
} );
var time = document.getElementById('time');
time.addEventListener('input', setRadius);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
</body>
</html>

Odd array behaviour in JavaScript

I'm attempting to draw boxes onto a canvas using JavaScript; my code works, but I'm having trouble with my arrays. Say I have a multi-demensional array called map and it is declared like so:
var map = [
[0,1,1],
[0,0,1],
[0,1,1],
];
Where 1 is a box and 0 is blank space, but when I run my code the output looks like the following:
0,0,0
1,0,1
1,1,1
Is there any way to fix this so the output matches map? My code looks like this:
var canvas = null;
var ctx = null;
var x,y,count,inc,ax,ay;
var map = [
[0,0,0],
[1,0,1],
[1,1,1],
];
window.onload = function () {
canvas = document.getElementById("gameArea");
ctx = canvas.getContext("2d");
y=0;
x=0;
ax=0;
ay=0;
count=0;
inc=0;
for(;count<3;count++){
if(count>0){
inc = inc + 40;
console.log("inc:"+inc);
console.log();
}
ay=count;
console.log("ay:"+ay);
console.log();
y = y + inc;
console.log("y:"+y);
console.log();
for(;ax<3;x=x+40,ax++){
if(map[ax][ay]==1){
console.log(ax+","+ay)
console.log(map[ax][ay]);
console.log();
ctx.strokeRect(x,y,40,40);
console.log("block:"+x+","+y);
}
}
console.log();
x=0;
y=0;
ax=0;
}
};
And the HTML is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Single Stage</title>
<script src="js/game.js" type="text/javascript">
</script>
<style type="text/css">
#gameArea{
display:block;
margin:0 auto;
background-color:#FFFFFF;
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameArea" width='800' height='480'></canvas>
</body>
</html>
You've just mixed up your rows and columns
try switching map[ax][ay]==1 to map[ay][ax]==1

How can i put image into the <div id="item1"></div>?

I am facing this problem.. May i know, how can i put image into this element tag,
<div id="item1"></div>
The purpose of this code below, is when the user click "+" the image will appear. And When the user click "play" button, the image that appeared, is supposed to put into the tag as mentioned above.
Unfortunately, i am not able to make the image that just appear, to be put into the tag..
I know there is hardcoding method, but sorry, i am not looking for this method..
<!DOCTYPE html>
<html>
<head>
<script src="code.jquery.com/jquery-1.7.2.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
.myClass {
width: 40px; height: 40px; float:left;
padding: 1px; margin:3px; position:absolute;
left:50px; top:60px; background:blue; color:white;
}
</style>
</head>
<body bgcolor="green";>
<div id="item1" class="myClass">F1</div>
<div id="item2" class="myClass">F2</div>
<div id="item3" class="myClass">F3</div>
<script>
var predator;
var Predatorlist = [];
function addvalue()
{
Predatorlist.push(uniqueid)
alert(Predatorlist);
}
function removevalue()
{
Predatorlist.pop(uniqueid)
alert(x.innerHTML=Predatorlist);
}
//************** End of Array ***********************
function Add() {
var id = Math.floor(Math.random()*101+1);
x = Math.random() * 550;
y = Math.random() * 250;
if (document.getElementById('amount').value < 50){
document.getElementById('amount').value++;
svg = document.getElementById("main");
var id = 'predator';
uniqueid = "frog" + document.getElementById('amount').value;
//namespaces for SVG
svgNS="http://www.w3.org/2000/svg";
xlinkNS="http://www.w3.org/1999/xlink";
// create a image element
image = document.createElementNS(svgNS, 'image');
// set id and other attributes
image.setAttributeNS(null, "id", uniqueid);
image.setAttributeNS(xlinkNS, "href","jef-frog.gif");
image.setAttributeNS(null, "x", x);
image.setAttributeNS(null, "y", y);
image.setAttributeNS(null, "width", "50");
image.setAttributeNS(null, "height", "50");
// append to svg
svg.appendChild(image);
} else {
alert("we got 50");
}
}
function Remove() {
if(document.getElementById('amount').value > 0)
{
document.getElementById('amount').value--;
svg = document.getElementById("main");
svg.removeChild(svg.lastChild);
}
}
function numinput(e){
// get the input value if enter
key=e.keyCode || e.which;
if (key==13){
total = document.getElementById("amount").value;
dummy = total;
// clear svg with image to avoid clearing the canvas
svg = document.getElementById("main");
element = svg.getElementsByTagName("image");
while(element.length>0){
element = svg.getElementsByTagName("image");
element[0].parentNode.removeChild(element[0]);
}
// use the input to create the number of frog.
while (dummy>0)
{
Add();
dummy--;
}
document.getElementById("amount").value = total;
}
}
function randomRange(min,max) {
return Math.random() * (max-min) + min;
}
/* Generate some random starting position */
var startItem1X = randomRange(50,100);
var startItem1Y = randomRange(50,100);
var startItem2X = randomRange(50,100);
var startItem2Y = randomRange(50,100);
var startItem3X = randomRange(50,100);
var startItem3Y = randomRange(50,100);
var startmyClassX = randomRange(50,100);
var startmyClassY = randomRange(50,100);
var item1 = $("#item1"),cycle1;
var item2 = $("#item2"),cycle1;
var item3 = $("#item3"),cycle1;
function runItem1() {
/* Set a the starting position to be random by editing the css */
$("#item1").css("left", startItem1X+"px");
$("#item1").css("top", startItem1Y+"px");
/* Cycle1 and Cycle2 variables allow infinite loop */
(cycle1 = function() {
var m = randomRange(50,100);
var n = randomRange(75,150);
item1.appendChild(image)
item1.animate({left:'+='+n},2000);
item1.animate({left:'+='+m, top:'+='+m}, 2000)
item1.animate({left:'-='+m, top:'+='+m}, 2000)
item1.animate({left:'-='+n},2000);
item1.animate({top:'-='+n},2000,cycle1)
})();
}
function runItem2() {
$("#item2").css("left", startItem2X+"px");
$("#item2").css("top", startItem2Y+"px");
(cycle2 = function() {
var m = randomRange(50,100);
var n = randomRange(75,150);
item2.animate({top:'+='+m, left:'+='+n},2000);
item2.animate({left:'-='+n},2000);
item2.animate({left:'+='+n, top:'-='+n},2000);
item2.animate({left:'-='+n},2000)
item2.animate({top:'+='+m},2000,cycle2)
})();
}
runItem1();
runItem2();
</script>
<SVG xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" id="main" style="border:inset 1px #000000;width:600;height:300"><param name='wmode' value='transparent'/></SVG>
<img src="jef-frog.gif" alt="frogsonice.com" width="100" height="100"/><BR/>
<INPUT type="button" value="+" onClick="Add(); addvalue();">
<INPUT type="text" id="amount" value=0 maxlength="3" size="1" onkeypress="numinput(evt)">
<INPUT type="button" value="-" onClick="Remove(); removevalue();">
<INPUT type="button" value="Play" onClick="runItem1(); runItem2();">
</body>
</html>
Many thanks to whoever out there, taking time to read and trying to help.. Thanks again..
would do it.
$('#your-play-button').click(function(e) {
$('#item1').html('<img src="mygif.gif" />');
});
edit after looking into your code you could replace:
document.getElementById('amount')
by $("#amount") etc. and really work with jQuery. Because now you don't use the advantage of jQuery, but you are just writing plain javascript...
well you can add a img tag using the innerhtml property or creating the element and appending it to div. then based on your logic you can set the tag's src of the image to the desired one.

Categories

Resources