I am having this piece of code that takes the user location every 5 seconds.
<div id="geo" onLoad=""></div>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
//Refresh the data
setTimeout(getLocation, 5000);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var obj = { lat: position.coords.latitude, long: position.coords.longitude };
var myJSON = JSON.stringify(obj);
document.getElementById("geo").innerHTML = myJSON;
}
getLocation()
</script>
And it prints correctly in the HTML file it is placed in.
The problem is that when I try to reach and parse it comes up with the HTML and I cannot get the result I need.
I have tried adding different headers to the file but with no luck. The one thing I can think of is somehow throwing the results in a PHP file and then just echoing the results there as plain text.
Do you think that this is possible or there is a better idea for achieving JSON in plain text and not HTML?
UPDATE
This is what I am getting when I am calling the HTML file
And this is how I want it to be (if i echo it with PHP)
I don't think you need JSON. You output the position coordinates directly:
document.getElementById("geo").innerHTML = 'lat: ' + position.coords.latitude + ', long: ' + position.coords.longitude;
Related
I am trying to send the longitude and latitude of a device to a discord webhook (or any webhook in general), I can not seem to find a way to take the longitude and latitude values to successfully be sent to the webhook.
The problem here is that even after converting the latitude and longitude into variables the webhook refuses to work? I tried a lot of ways, none seemed to send the longitude or latitude or both.
Thank you in advance, please try sending the values to your own webhook, make one on discord (it is 100% free) before putting an answer.
Please note that I am fairly new to javascript, I am more confortable with python and Lua C.
Please if you have an answer try providing a example with it, saves me from a headache.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<button onclick="sendMessage()">Send your location to my webhook</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) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function sendMessage() {
const request = new XMLHttpRequest();
request.open("POST", "PUT YOUR WEBHOOK HERE");
request.setRequestHeader('Content-type', 'application/json');
const params = {
username: "My Webhook Name",
avatar_url: "",
content: "This message should be latitude and longitude. I spent 2 hours trying to figure this out, help."
}
request.send(JSON.stringify(params));
}
</script>
</body>
</html>
Hi I'm currently trying to get GPS coordinates of a user in python. I have tried various methods but they are a little inaccurate for what I want to do.
The most accurate method I have found is the W3 schools method as follows:
<script>
var lat,lon
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position)
{
lat= position.coords.latitude
lon= position.coords.longitude
cords='{"lat":'+lat+',"lon":'+lon+'}'
}
getLocation()
</script>
I want to echo var cords in a PHP file, this way it will allow the source code to be just $cords and I could use the following python function
def grabGPS():
send_url='http://127.0.0.1:8080/urlTest/gps.php'
geoRequest=requests.get(send_url)
geoData=json.loads(geoRequest.text)
lat = geoData['lat']
lon = geoData['lon']
print(lat)
print(lon)
Thanks for any help that can be rendered
I'm trying to get the location of a device at the time of loading a web page and passing that through to two variables in PHP (lat, long) so it can be manipulated further down the script. Currently, I have the data entered manually by tasker through the URL, but I'd like to have it available in a normal web page too without having to put the data into the URL by hand each time.
I was trying to use the getCurrentPosition() JavaScript to do this, but I can't find a way to get it back into the PHP. I have tried to write two separate files but all I seem to get back from the file is the JS script because it has not yet processed the file. So not the actual data itself.
PHP File:
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
ob_start();
$location = file_get_contents('https://myfakeurl.com/getlocation.php', false, stream_context_create($arrContextOptions));
$GPSCoord = explode(",", $location);
$coord['lat'] = trim($GPSCoord[0]);
$coord['long'] = trim($GPSCoord[1]);
echo "Longitude: " . $coord['long'] . "<br>";
echo "Lattitude: " . $coord['lat'] . "<br>";
?>
and JS file:
<p id="coord"></p>
<script>
var x = document.getElementById("coord");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = position.coords.latitude + "," +
position.coords.longitude;
}
getLocation()
</script>
The JS needs to run on the devices too which is part of the problem otherwise you don't get the correct GPS coords
How can I make this work? I feel like this is an Alice in Wonderland rabbit hole...
The js code will not run if you use php's file_get_contents function, because of javascript is client side language. It's necessary to open the page from browser to run javascript. You can place javascript code on loaded webpage, catch location data and send to php with ajax. Try something like this
backend.php
<?php
if(isset($_POST['lng'], $_POST['lat'])) {
echo $_POST['lng'].':'.$_POST['lat'];
}
?>
frontend.html
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="response">
</div>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(sendPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function sendPosition(position) {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://fakeurl/backend.php", false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lng="+position.coords.longitude+"&lat="+position.coords.latitude);
document.getElementById('response').innerHTML = xhttp.responseText;
}
getLocation();
</script>
</body>
</html>
Entry question on what to do / where to look further for this possibly easy facility for a Website
I basically want to show the my current geographic location via a text display, not as a display on Google Maps. Obviously I would like this to update automatically
Does anyone know a program that would facilitate this? Or generally the best way to go about it?
You can use this code to update your page with the current location:
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;
}
<div id="demo"></div>
My MVC Controller is getting hit twice on page load, and I am stumped on how to solve this problem.
I'm using navigator.geolocation.getCurrentPosition in my Layout page, and that passes the latitude and longitude to my controller.
I have RenderAction in a div, just in case the user has JavaScript disabled, as some people still do
:-(
This is what is causing my problem:
The RenderAction is getting rendered 1st and hitting the controller. Then, the AJAX request is firing and hitting the controller.
So my controller is getting hit twice per request.
Is there something I'm missing which will stop that, because at the moment, all I can think of is to remove the render action from the page.
Code:
<div class="dvWeather">
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
</div>
if (navigator.geolocation) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var aj = "gl";
$.ajax({
url: '#Url.Action("PvCurrentWeatherConditions", "Weather")',
type: 'get',
data: {
lat: lat,
lon: lon,
aj: aj
},
success: function (result) {
$('.dvWeather').html(result);
}
});
}
public PartialViewResult PvCurrentWeatherConditions(string lat, string lon, string aj)
{
if (Request.IsAjaxRequest())
{
try
{
//TODO create Viewmodel
GeoCoordinate gc = new GeoCoordinate();
var latitude = gc.Latitude = Convert.ToDouble(lat);
var longitude = gc.Longitude = Convert.ToDouble(lon);
string latlon = latitude + "," + longitude;
var displayCurrentConditions = _igcc.CurrentConditions(latlon);
return PartialView("pvCurrentWeatherConditions");
}
catch (FormatException)
{
//TODO get ip address
return PartialView("pvLocationBasedOnIpAddress");
}
catch (Exception)
{
return PartialView("pvError");
}
}
return PartialView("pvLocationBasedOnIpAddress");
}
Perhaps use another method for checking if the visitor has javascript disabled, like noscript:
<noscript>
<meta http-equiv="refresh" content="[URL]?java=off">
</noscript>
then handle the querystring in a new action.
You don't have to remove the Render action. Just make another (negative) check in the div:
<div class="dvWeather">
<script type="text/javascript>
//if (!navigator.geolocation) { : Edit
if (navigator.geolocation == null) {
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
}
</script>
</div>
Edit:
if (navigator.geolocation != null) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
This way only one call will be made.
Hope it helps.