Uncaught TypeError: Failed to fetch - javascript

Edit:
I fixed it the answer is in the answer section.
I have trying to create a weather application and I have stumbled on a bug. I try to fetch from the API I'm using which is openweathermap.org, I know the address that I'm fetching is correct because when I open it in my browser the .json loads. I'm confused about why it fails to fetch.
Here is my code
<html>
<body>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
const lat = position.coords.latitude
const lon = position.coords.longitude
console.log(lat,lon)
const API = "Im using open"
fetch("api.openweathermap.org/data/2.5/weather?lat="+ lat +"&lon="+ lon +"&appid="+ API)
}
</script>
</body>
</html>

I just realized I didn't have "https://" at the beginning of my fetch.

Related

How to get Geolocation data and send it from browser to express server

I want to get the latitude and longitudes of a location.I am using ejs files.
I found this code on w3shools.But i dont know how to include it in ejs file and return the data back to server.In the backend I am uusing express.Can u please help?Thanks in advance.
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
In your main nodeJS file you need to create a route for receiving the geolocation data:
const express = require("express");
const { json } = require("body-parser")
const app = express();
app.use(json())
//you probably have the lines above in your code
app.get("/geolocation/:latitude/:longitude", (req, res) => {
const latitude = req.params.latitude;
const longitude = req.params.longitude;
res.status(200).json({"Message": "Coordinates received"})
//now that you have these in variables on your server, you can process them or store them in your database as you please
})
On the frontend side, in your showPosition function, you should include a fetch request that is going to send the latitude and longitude to your server. To see more about fetch, click here
I hope I understood the question right and this will be useful
if you want to execute your code from ejs then you need to put it inside <script> tag in .ejs file
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
or store all your JS code to separate page and link at bottom in ejs
yourFile.js:
(function() {
var x = document.findElementById('demo');
...
)}();
Then on your ejs template: //at the bottom of the page
<script src="yourFile.js" type="text/javascript"></script>

How to store location of visitor's profile on mysql database on php using javascript?

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
</script>
</body>
</html>
I want to store this in phpMyAdmin Database.
without showing the user that the location is stored
You just need to send the location to the certain php file (like geo.php) using AJAX or any other request. And in the geo.php you accept the data and write it to the database. Look for Ajax Post Request
Use ajax of jquery to store data when you get position info
Try this code in pc. dont run it on snippet because it needs you permission of location.
HTML:
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
var x = document.getElementById("demo1");
var y = document.getElementById("demo2");
var z = document.getElementById("demo3");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition1);
navigator.geolocation.getCurrentPosition(showPosition2);
navigator.geolocation.getCurrentPosition(showPosition3);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition1(position) {
alert("showPosition1");
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
function showPosition2(position) {
alert("showPosition2");
y.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
function showPosition3(position) {
alert("showPosition3");
z.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>

Why Geolocation HTML5 getCurrentPosition() is not working on Google Map?

This is the error that I am getting while running below javascript file
getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https for more details.
This is my javascript file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA4HSRrQSje--aI6ImtJF30s5ezaUWxsow&libraries=places"></script>
<script>
function getLocation()
{
console.log("In geolocation");
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else
{
print("Browser doesn't support geolocation");
}
function showPosition(position)
{
console.log("in show position");
dest_lat=position.coords.latitude;
dest_long=position.coords.longitude;
url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+ dest_lat + ',' + dest_long + '&sensor=false';
$.get(url, function(data)
{
if (data.status == 'OK')
{
map.setCenter(data.results[0].geometry.location);
console.log("Dragaed lat "+marker.getPosition().lat());
console.log("Dragged lng "+marker.getPosition().lng());
console.log("Address "+data.results[0].formatted_address);
}
});
}
</script>
</head>
<body>
<input type="button" value="LocateMe" onclick="getLocation();"/>
</body>
</html>
You have to put it one a server with https://!
If you are using Visual Studio, you can configure to lunch the site with https:// see: https://dotnetcodr.com/2015/09/18/how-to-enable-ssl-for-a-net-project-in-visual-studio/
Alternativelyyou can test it on jsfiddler, which uses https per default.
Besides that your code has a lot of other errors.
Brackets don't match
map object is not defined in your example
varibles are not declared (they are added to the global namespace which can cause some really nasty problems later on and throws an error when you use "use strict")
Here is a working excample on jsfiddle: https://jsfiddle.net/3gkkvs50/
(stackoverflow doesn't use https for the examples)
HTML:
<input type="button" value="LocateMe" onclick="getLocation();" />
JS:
function getLocation() {
console.log("In geolocation");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
print("Browser doesn't support geolocation");
}
}
function showPosition(position) {
console.log("in show position");
var dest_lat = position.coords.latitude;
var dest_long = position.coords.longitude;
var url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + dest_lat + ',' + dest_long + '&sensor=false';
$.get(url, function(data) {
alert(JSON.stringify(data));
});
}

How to write to file from PHP

Im trying to create a page where you click on a button, you get your co-ordinates and then the data is saved on a .txt file on the server. This is my code
<!DOCTYPE html>
<html>
<head>
<head>
<body>
<input type="hidden" id="Latitude" name="Lat" value="">
<input type="hidden" id="Longitude" name="Lon" value="">
<button onclick="getLocation()">Get Location</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
var lat,lon;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
lat=position.coords.latitude;
lon=position.coords.longitude;
document.getElementById("Latitude").value = lat;
document.getElementById("Longitude").value = lon;
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
<?php
$marker = fopen("markers.txt",a)
$locLat = $_GET['Lat'];
$locLon = $_GET['Lon'];
fwrite($marker,$locLat);
fwrite($marker,$locLon);
?>
</body>
</html>
I can get the user's location, but the PHP code doesn't work.
Thanks
You should correct you code by placing 'a' in double quote and semicolon at the end first line of php code
<?php
$marker = fopen("markers.txt","a");
$locLat = $_GET['Lat'];
$locLon = $_GET['Lon'];
fwrite($marker,$locLat);
fwrite($marker,$locLon);
?>
See this question for how can you include form tag and ajax submit using php here

Why does my variables dont take the value in the function?

I want to display on screen the var longitude en latitude but I think that the function is executing last and I'am stuck with the initial values.
The objective is to print on screen the exact values of the geolocation that the browser returns.
Thanks !!!
<!DOCTYPE html>
<head>
<script>
var longitude = "10";
var latitude = "20";
</script>
</head>
<html>
<body onload="getLocation()">
<script>
var longitude = "30";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
alert('aaab:' +longitude);
});
}else {
alert("Geolocation API is not supported in your browser.");
}
}
</script>
<script>
alert("ccc");
document.write (longitude);
document.write (latitude);
</script>
</body>
</html>
i know that it's working within the function, but there is any way to use those variable outside? I just want to be able to store them in one global variable that cand be called wherever. Thanks
document.write is being executed before your code that updates it is being run. You need to do the document.write in the callback like so:
<!DOCTYPE html>
<head>
<script type='text/javascript'>
var longitude = "10";
var latitude = "20";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
document.write(latitude+" / "+longitude);
});
}else{
alert("Geolocation API is not supported in your browser.");
}
}
</script>
</head>
<body onload="getLocation()">
</body>
</html>
Try this:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation);
}else {
alert("Geolocation API is not supported in your browser.");
}
}
function displayLocation(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
alert('aaab:' +longitude);
}
The Geolocation Callback probably hasn't been called at the time you write your longitude and latitude. Maybe you can use jQuery to write the correct values to the screen...
<script>
var longitude = "30";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
//alert('aaab:' +longitude);
// Use jQuery to write your values to the html
$("#longitude").html(longitude);
$("#latitude").html(latitude);
});
}else {
alert("Geolocation API is not supported in your browser.");
}
}
</script>
<html>
...
<body onload="getLocation()">
<div id="longitude"></div>
<div id="latitude"></div>
</body>
</html>

Categories