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
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>
I have a Google Form where I want to get the user geolocation along with the inputs.
Currently, I'm able to get it by making the user click on a url after he submits the answers. This is the code in Google Script that does it:
function doGet() {
return HtmlService.createHtmlOutputFromFile("Index");
}
function getLoc(value) {
var destId = FormApp.getActiveForm().getDestinationId() ;
var ss = SpreadsheetApp.openById(destId) ;
var respSheet = ss.getSheets()[0] ;
var data = respSheet.getDataRange().getValues() ;
var headers = data[0] ;
var numColumns = headers.length ;
var numResponses = data.length;
var c=value[0]; var d=value[1];
var e=c + "," + d ;
if (respSheet.getRange(1, numColumns).getValue()=="GeoAddress") {
respSheet.getRange(numResponses,numColumns-2).setValue(Utilities.formatDate(new Date(), "GMT-3", "dd/MM/yyyy HH:mm:ss"));
respSheet.getRange(numResponses,numColumns-1).setValue(e);
var response = Maps.newGeocoder().reverseGeocode(value[0], value[1]);
f= response.results[0].formatted_address;
respSheet.getRange(numResponses,numColumns).setValue(f);
}
else if (respSheet.getRange(1,numColumns).getValue()!="GeoAddress") {
respSheet.getRange(1,numColumns+1).setValue("GeoStamp");
respSheet.getRange(1,numColumns+2).setValue("GeoCode");
respSheet.getRange(1,numColumns+3).setValue("GeoAddress");
}
}
And the Index.html file:
<!DOCTYPE html>
<html>
<script>
(function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
})()
function showPosition(position){
var a= position.coords.latitude;
var b= position.coords.longitude;
var c=[a,b]
getPos(c)
function getPos(value){
google.script.run.getLoc(value);
}
}
</script>
</html>
Instead of making the user click on a url, I want the geolocation to be automatically inputed into the response sheet as the user submits the form. I'm able to make the getLoc function run on a submit trigger, however the html function doesn't run. I believe it might be because the doGet function is already a trigger, but it requires a browser page to be opened in order to run. If that's the case, the ideal solution would be to redirect the browser to the Google Script url after the user submits it, but I can't seem to find a way to do it. Is this the correct approach and how can I make it work?
Thanks in advance!
Maybe this works: https://www.youtube.com/watch?v=J93uww0vMFY
Tutorial on Geotagging (Geo-stamp and Time-stamp) google forms.
Add info on Latitude, Longitude, and Address (Street name and number, city, state, zip code, and country) of a device submitting google forms. Linking user’s location within google forms.
Google forms integration with google maps.
Links to download the scripts are given below:
Code.gs : https://www.youtube.com/redirect?v=J93uww0vMFY&event=video_description&q=https%3A%2F%2Fdrive.google.com%2Fopen%3Fid%3D1D4vTzUGZAf3_ZDVMeW760i1KoZCn37un&redir_token=VQ2rLeQvyQea-mq9_kGhh_Kxihd8MTU5MTgxOTM2OEAxNTkxNzMyOTY4
Index.html : https://www.youtube.com/redirect?v=J93uww0vMFY&event=video_description&q=https%3A%2F%2Fdrive.google.com%2Fopen%3Fid%3D1mYZGYNrXNOxUD8DlDmRdBajy1nc3FKtw&redir_token=VQ2rLeQvyQea-mq9_kGhh_Kxihd8MTU5MTgxOTM2OEAxNTkxNzMyOTY4
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;
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>
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.