sensing geolocation using google maps - javascript

I am creating a functionality to sense the users geolocation using google api but i am having a problem that although the code seems to be alright the output is not showing i.e i am getting nothing as my location. Here is my code
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>Geolocation</TITLE>
</HEAD>
<BODY>
Get Location
<DIV id = "map">
<IFRAME id = "google_map" width = "400" height = "350" frameborder = "0" scrolling = "no" marginheight = "0" marginwidth = "0" src = "https://maps.google.co.in?output=embed"></IFRAME>
</DIV>
<SCRIPT type = "text/javascript">
var getter = function(pos) {
var user_lattitude = pos.coords.lattitude;
var user_longitude = pos.coords.longitude;
var user_coordinates = user_lattitude + ',' + user_longitude;
document.getElementById('google_map').setAttribute('src' , 'https://maps.google.co.in/?q=' + user_coordinates + '&z=60&output=embed');
}
document.getElementById('get_location').onclick = function() {
navigator.geolocation.getCurrentPosition(getter);
return false;
}
</SCRIPT>
</BODY>
</HTML>

It looks like you've just spelt latitude wrong.
pos.coords.lattitude ;
It should only have 1 t. If you change that your above code will work.

Related

Javascript delay not working. Tried too many things [duplicate]

This question already has answers here:
How do I add a delay in a JavaScript loop?
(32 answers)
Closed 1 year ago.
I am new with JavaScript programming. I am making a program for deaf and blind children community. It is text to display Letters program. It split text and show image on screen.
How it works:
HTML and JavaScript base program. Input sentence taken from user. JavaScript split it and send relevant image name to HTML for display.
Problem:
It shows all images at once without delay. When I use alert() it shows all images are being displayed. 3rd day going on I tried to implement delay timebase substraction or settimeout but not working. Perhaps I am doing something wrong. I need community help to fix this.
Code:
<html lang="en">
<head>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="index.css" />
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<title>Image Changer</title>
</head>
// How to change image SCR through javascript.
<body>
<input id="txt" name="txt" type="textbox" />
<img id="image1" src="./multimedia/alphabets/0.jpg" style="width:100px">
<button onclick="imagechange((document.getElementById('txt').value) , document.getElementById('image1.scr'))">Button</button>
<script type="text/javascript">
function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
alert(txt1);
document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
if(txt1 == " " )
document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
}
}
</script>
</body>
</html>
setTimeout is async so that's probably the reason it did not work. To make it work, you can do something like this
<script type="text/javascript">
function delay(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time);
});
}
async function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
await delay(1000);
document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
if(txt1 == " " ) document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
}
}
</script>
I made a delay promise from the setTimeout and made your imageChange function async so I can await the delay promise during each loop.
I guess this is because DOM manipulation is synchronous and DOM rendering is asynchronous. Actually you can try this:
function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
alert(txt1);
document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
if(txt1 == " " ) document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
console.log(document.getElementById('image1').src);
}
}
You can see the result in the console, image1.src did change but was not rendered.
To make it work, you can use the asynchronous function like this if you are using ES5:
function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
// Use closures to avoid the problems caused by the txt1 variable context
function imageChange(imageName) {
setTimeout(function () {
document.getElementById('image1').src = imagefolderlocation + imageName +".jpg";
if(txt1 === " " ) {
document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
}
}, 1000 * i); // Change image1.src after i seconds
}
imageChange(txt1);
}
}
Btw, you should use <!-- How to change image SCR through javascript. --> in HTML if you want to add comments.

Global variable assigned value in one function is not accessible in another

I am using geolocation to collect coordinates and make an API call to get the weather in Fahrenheit. I'm assigning the global variable tempNum this value within one of my functions that adds the temperature to the page using function getWeatherByCoordinates(latitude, longitude).
Later, I am trying to access this variable and pass the value as an argument into another function typeConversion for which I am attempting to convert the temperature value to Celsius. It is returning NaN and when debugging, I can't figure out why.
Here is my HTML and JS. I feel like since I declared my variable at the global level and set "return varName" in the function that I assigned the value to it, that the value should be accessible throughout my JS; but I may have done something wrong or misunderstood variable scope. Please assist.
var place = document.getElementById("meat");
var header = document.getElementById("header");
var weather = document.getElementById("Weather");
var latitude;
var longitude;
var coordinates = document.getElementById("coordinates");
function success(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
getWeatherByCoordinates(latitude, longitude);
};
//else {
// //Write Code to alternatively show a Zip-Code Search Box;
//};
navigator.geolocation.getCurrentPosition(success);
var city = document.getElementById("city");
var weatherDescription = document.getElementById("weather-description");
var roundTempF;
var roundTempC;
var tempNum;
var tempStringFFull
function getWeatherByCoordinates(latitude, longitude) {
var fullURL = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=75ed54453a6e806917cfa439b3fb1dd9&units=imperial";
$.getJSON(fullURL, function (data) {
var tempString = data.main.temp;
var tempNum = parseInt(tempString);
roundTempF = Math.floor(tempNum);
stringF = roundTempF.toString();
tempStringFFull = stringF + "\xB0" + " F";
weather.innerText = tempStringFFull;
city.innerText = data.name;
weatherDescription.innerText = data.weather[0].description;
if (data.dt > data.sys.sunrise && data.dt < data.sys.sunset) {
$("#whole-page").removeClass("whole");
$("#whole-page").removeClass("night");
$("#whole-page").addClass("day");
}
else {
$("#whole-page").removeClass("whole");
$("#whole-page").removeClass("night");
$("#whole-page").addClass("night");
};
event.preventDefault();
});
return tempNum;
};
function typeConversion(tempNum) {
if (changeTempType.innerText === "Celsius") {
var tempStringC;
var celsiusDecimal = (tempNum - 32) * (5 / 9);
roundTempC = Math.floor(celsiusDecimal);
tempStringC = roundTempC.toString();
tempStringC += "\xB0" + " C";
weather.innerText = tempStringC;
changeTempType.innerText = "Farenheit";
return;
}
else if (changeTempType.innerText === "Farenheit") {
weather.innerText = tempStringFFull;
changeTempType.innerText = "Celsius";
return;
}
else {
weather.innerText = "We are unable to retrieve the weather at this time. Please try again later";
changeTempType.innerText = "Celsius";
return;
};
};
var changeTempType = document.getElementById("change-temp-type");
changeTempType.addEventListener("click", typeConversion, false);
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<title>Weather</title>
</head>
<body id="whole-page" class="whole">
<div class="wrapper">
<h2 id="header">Check the Current Temperaturate by Zip Code</h2>
<label>Farenheit</label>
<input type="radio" name="temp-type" value="C" id="Celsius-radio"/><label>Celsius</label>-->
<button id="change-temp-type">Celsius</button>
<form>
<p>Enter the Zip Code to see the Weather there!</p>
<input id = "Zip-Code" type="text"/>
<input id = "submit-zip" type="button" value="Get Weather!"/>
</form>
<div>
<h3 id="city"></h3>
<h3 id= "Weather" class="temp-text"></h3>
<h4 id="weather-description"></h4>
</div>
</div>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.js"> </script>
<script src="javascript/main.js"></script>
</body>
</html>
You have a couple of issues:
You re-declare var tempNum = in your function, meaning it will be a new variable only accessible inside the function scope (leaving the global one unchanged)
Your code inside of $.getJSON is using an asynchronous callback - that means it will run sometime later than the code below it. When you return tempNum, that code has not run yet.
Your return statement isn't really doing anything... just reassigning the global variable will be sufficient.
UPDATE - issue I missed at first:
You are naming your function parameter in typeConversion "tempNum". Again, that will result in a new variable, only accessible within the scope of that function. If you want to affect the global, then this function does not need any parameters at all, and tempNum will then refer to the global variable as intended.
I've tried to clear up all issues below.
var place = document.getElementById("meat");
var header = document.getElementById("header");
var weather = document.getElementById("Weather");
var latitude;
var longitude;
var coordinates = document.getElementById("coordinates");
function success(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
getWeatherByCoordinates(latitude, longitude);
};
//else {
// //Write Code to alternatively show a Zip-Code Search Box;
//};
navigator.geolocation.getCurrentPosition(success);
var city = document.getElementById("city");
var weatherDescription = document.getElementById("weather-description");
var roundTempF;
var roundTempC;
var tempNum;
var tempStringFFull
function getWeatherByCoordinates(latitude, longitude) {
var fullURL = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=75ed54453a6e806917cfa439b3fb1dd9&units=imperial";
$.getJSON(fullURL, function (data) {
var tempString = data.main.temp;
// removed "var tempNum"...
tempNum = parseInt(tempString);
roundTempF = Math.floor(tempNum);
stringF = roundTempF.toString();
tempStringFFull = stringF + "\xB0" + " F";
weather.innerText = tempStringFFull;
city.innerText = data.name;
weatherDescription.innerText = data.weather[0].description;
if (data.dt > data.sys.sunrise && data.dt < data.sys.sunset) {
$("#whole-page").removeClass("whole");
$("#whole-page").removeClass("night");
$("#whole-page").addClass("day");
}
else {
$("#whole-page").removeClass("whole");
$("#whole-page").removeClass("night");
$("#whole-page").addClass("night");
};
event.preventDefault();
});
//return tempNum;
};
// removed the argument "tempNum", just use the global
function typeConversion() {
if (changeTempType.innerText === "Celsius") {
var tempStringC;
var celsiusDecimal = (tempNum - 32) * (5 / 9);
roundTempC = Math.floor(celsiusDecimal);
tempStringC = roundTempC.toString();
tempStringC += "\xB0" + " C";
weather.innerText = tempStringC;
changeTempType.innerText = "Farenheit";
return;
}
else if (changeTempType.innerText === "Farenheit") {
weather.innerText = tempStringFFull;
changeTempType.innerText = "Celsius";
return;
}
else {
weather.innerText = "We are unable to retrieve the weather at this time. Please try again later";
changeTempType.innerText = "Celsius";
return;
};
};
var changeTempType = document.getElementById("change-temp-type");
changeTempType.addEventListener("click", typeConversion, false);
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<title>Weather</title>
</head>
<body id="whole-page" class="whole">
<div class="wrapper">
<h2 id="header">Check the Current Temperaturate by Zip Code</h2>
<label>Farenheit</label>
<input type="radio" name="temp-type" value="C" id="Celsius-radio"/><label>Celsius</label>-->
<button id="change-temp-type">Celsius</button>
<form>
<p>Enter the Zip Code to see the Weather there!</p>
<input id = "Zip-Code" type="text"/>
<input id = "submit-zip" type="button" value="Get Weather!"/>
</form>
<div>
<h3 id="city"></h3>
<h3 id= "Weather" class="temp-text"></h3>
<h4 id="weather-description"></h4>
</div>
</div>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.js"> </script>
<script src="javascript/main.js"></script>
</body>
</html>
Last note - this will work fine if the function where you need to access tempNum runs later, like in response to a user action. It may still be undefined for a few ms after your page loads, so if you try to use it right at page load time, it may still be undefined. You may want to initialize it to some default value in this case.
Hope this helps.

Scaling image using variables

Im trying to scale an image using variables rather than a set in stone scale. I know using "scale(0.5,0.5)" works but I want to do something like "scale(x,y)" so the scale factor changes depending on what variables x and y are, However when I try doing this, the image will no longer scale like it did when it had a set scale factor. How can I solve this? Thanks for any help. Here's an example of what I mean.
<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="img_pulpit.jpg">
<button onclick="myFunction()">Try it</button>
<script>
var a = document.getElementById("myImg");
var d = 5
var e = 10
var f = d/e
var g = 10
var h = 30
var i = g/h
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale(f, i)";
}
</script>
</body>
</html>
Just use string concatenation ("scale(" + f + ", " + i + ")") or string interpolation (`scale(${f}, ${i})`).
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale(" + f + "," + i + ")";
}
You need to use concat the value of f and i
document.getElementById("myImg").style.WebkitTransform = "scale("+f+","+i+")";
<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="https://lh3.googleusercontent.com/gN6iBKP1b2GTXZZoCxhyXiYIAh8QJ_8xzlhEK6csyDadA4GdkEdIEy9Bc8s5jozt1g=w300">
<button onclick="myFunction()">Try it</button>
<script>
var a = document.getElementById("myImg");
var d = 5
var e = 10
var f = d/e
var g = 10
var h = 30
var i = g/h
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale("+f+","+i+")";
}
</script>
</body>
</html>

how to store variable`s name in another variable

i`m working on school project
how can i access the name of variable and store it to in another variable ex: y[i].
what to write in place of comment below in javascript code.
var p = ["a","b","d"];
var q = ["d","b","c"];
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for (var i=0; i<arrays.length; i++) {
x[i] = arrays[i].indexOf(value);
// y[i] = // store array`s name here
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, [p, q])">Try it</button>
<p id="demo"></p>
</body>
</html>
Here is what you search for : You have to construct a object with your arrays and pass trow all the arrays.
var obj = {
p:["a","b","d"],
q: ["d","b","c"]
};
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for(key in arrays){
x.push(arrays[key].indexOf(value));
y.push(key);
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, obj)">Try it</button>
<p id="demo"></p>
</body>
</html>
Since you ask for what i was talking about. I'll give you the code.
Again, to re-iterate my point, you cannot get the variable name. But if you must have the variable somehow, you can work around by putting all the variables you need access to in an object.
you will not get the variable name of the object, but you can access all the properties names of this object.
Here is the codepen link to see the code running.
html
<p id="test"><p>
js
var variableList = {};
variableList.var1 = 1;
variableList.var2 = -50;
variableList.var3 = [2,4];
variableList.var4 = "4";
variableList.var5 = 5.5;
var ele = document.getElementById("test");
for(var propertyName in variableList) {
ele.innerHTML = ele.innerHTML + "<br>" + propertyName + " : " + variableList[propertyName];
}

how to change the value of input box just for display in html 5 web page

I have a textfield in which i am entering data i want that if user enter 1000 then it show 1,000 in textfield but this same value 1000 is also used in calculations further so how to solve this if user enter 1000 then just for display it show 1,000 and if we use in calcualtion then same var shows 1000 for calculating.
<HTML>
<body>
<input type="text" id="test" value="" />
</body>
<script>
var c=document.getElementById(test);
</script>
</html>
so if c user enter 1000 then it should dispaly 1,000 for dispaly one and if user uses in script
var test=c
then test should show 1000
document.getElementById returns either null or a reference to the unique element, in this case a input element. Input elements have an attribute value which contains their current value (as a string).
So you can use
var test = parseInt(c.value, 10);
to get the current value. This means that if you didn't use any predefined value test will be NaN.
However, this will be evaluated only once. In order to change the value you'll need to add an event listener, which handles changes to the input:
// or c.onkeyup
c.onchange = function(e){
/* ... */
}
Continuing form where Zeta left:
var testValue = parseInt(c.value);
Now let's compose the display as you want it: 1,000
var textDecimal = c.value.substr(c.value.length-3); // last 3 characters returned
var textInteger = c.value.substr(0,c.value.length-3); // characters you want to appear to the right of the coma
var textFinalDisplay = textInteger + ',' + textDecimal
alert(textFinalDisplay);
Now you have the display saved in textFinalDisplay as a string, and the actual value saved as an integer in c.value
<input type="text" id="test" value=""></input>
<button type="button" id="get">Get value</input>
var test = document.getElementById("test"),
button = document.getElementById("get");
function doCommas(evt) {
var n = evt.target.value.replace(/,/g, "");
d = n.indexOf('.'),
e = '',
r = /(\d+)(\d{3})/;
if (d !== -1) {
e = '.' + n.substring(d + 1, n.length);
n = n.substring(0, d);
}
while (r.test(n)) {
n = n.replace(r, '$1' + ',' + '$2');
}
evt.target.value = n + e;
}
function getValue() {
alert("value: " + test.value.replace(/,/g, ""));
}
test.addEventListener("keyup", doCommas, false);
button.addEventListener("click", getValue, false);
on jsfiddle
you can get the actual value from variable x
<html>
<head>
<script type="text/javascript">
function abc(){
var x = document.getElementById('txt').value;
var y = x/1000;
var z = y+","+ x.toString().substring(1);
document.getElementById('txt').value = z;
}
</script>
</head>
<body>
<input type="text" id="txt" value="" onchange = "abc()"/>
</body>
This works with integer numbers on Firefox (Linux). You can access the "non-commaed"-value using the function "intNumValue()":
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
String.prototype.displayIntNum = function()
{
var digits = String(Number(this.intNumValue())).split(""); // strip leading zeros
var displayNum = new Array();
for(var i=0; i<digits.length; i++) {
if(i && !(i%3)) {
displayNum.unshift(",");
}
displayNum.unshift(digits[digits.length-1-i]);
}
return displayNum.join("");
}
String.prototype.intNumValue = function() {
return this.replace(/,/g,"");
}
function inputChanged() {
var e = document.getElementById("numInp");
if(!e.value.intNumValue().replace(/[0-9]/g,"").length) {
e.value = e.value.displayIntNum();
}
return false;
}
function displayValue() {
alert(document.getElementById("numInp").value.intNumValue());
}
</script>
</head>
<body>
<button onclick="displayValue()">Display value</button>
<p>Input integer value:<input id="numInp" type="text" oninput="inputChanged()">
</body>
</html>

Categories

Resources