asked on
ASKER
<script>
var latitude = 0;
var longitude = 0;
function geoFindMe() {
var output = document.getElementById("show");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=20&size=300x300&sensor=false";
output.appendChild(img);
};
function error() {
output.innerHTML = "Unable to retrieve your location";
};
output.innerHTML = "<p>Locating...</p>";
fillLatitudeLongitudeElements();
navigator.geolocation.getCurrentPosition(success, error);
function fillLatitudeLongitudeElements(){
document.getElementById("latitude").value = latitude;
document.getElementById("longitude").value = longitude;
var sql = "INSERT INTO gps(lat, long) VALUES (latitude,longitude)";
}
}
function prompt(window, pref, message, callback) {
let branch = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
if (branch.getPrefType(pref) === branch.PREF_STRING) {
switch (branch.getCharPref(pref)) {
case "always":
return callback(true);
case "never":
return callback(false);
}
}
let done = false;
function remember(value, result) {
return function() {
done = true;
branch.setCharPref(pref, value);
callback(result);
}
}
let self = window.PopupNotifications.show(
window.gBrowser.selectedBrowser,
"geolocation",
message,
"geo-notification-icon",
{
label: "Share Location",
accessKey: "S",
callback: function(notification) {
done = true;
callback(true);
}
}, [
{
label: "Always Share",
accessKey: "A",
callback: remember("always", true)
},
{
label: "Never Share",
accessKey: "N",
callback: remember("never", false)
}
], {
eventCallback: function(event) {
if (event === "dismissed") {
if (!done) callback(false);
done = true;
window.PopupNotifications.remove(self);
}
},
persistWhileVisible: true
});
}
prompt(window,
"extensions.foo-addon.allowGeolocation",
"Foo Add-on wants to know your location.",
function callback(allowed) { alert(allowed); });
</script>
<p><button onclick="geoFindMe()">Locate</button></p>
<div id="show"></div>
<?php include "../dbconnect.php";
if(isset($_POST['sub'])){
$l = $_POST['long'];
$la = $_POST['lat'];
$n = $_POST['name'];
mysql_query("INSERT INTO `gps`(`lat`, `long`, `name`) VALUES ('".$la."','".$l."','".$n."')");
echo "Done though";
}
?>
<form action="#" method="post">
<fieldset>
Latitude3:<br>
<input id="latitude" type="text" name="firstname" value="latitude" readonly><br>
Longitude:<br>
<input id="longitude" type="text" name="lastname" value="longitude" readonly><br><br>
<input type="submit" value="Submit" name="sub">
</fieldset>
</form>
I would like to separate the show output so i can later store the longitude and lattitude into my table in sql
ASKER
ASKER
ASKER
<script>
var latitude = 0;
var longitude = 0;
function geoFindMe() {
var output = document.getElementById("show");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=20&size=300x300&sensor=false";
output.appendChild(img);
};
function error() {
output.innerHTML = "Unable to retrieve your location";
};
output.innerHTML = "<p>Locating...</p>";
fillLatitudeLongitudeElements();
navigator.geolocation.getCurrentPosition(success, error);
function fillLatitudeLongitudeElements(){
document.getElementById("latitude").value = latitude;
document.getElementById("longitude").value = longitude;
}
}
function prompt(window, pref, message, callback) {
let branch = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
if (branch.getPrefType(pref) === branch.PREF_STRING) {
switch (branch.getCharPref(pref)) {
case "always":
return callback(true);
case "never":
return callback(false);
}
}
let done = false;
function remember(value, result) {
return function() {
done = true;
branch.setCharPref(pref, value);
callback(result);
}
}
let self = window.PopupNotifications.show(
window.gBrowser.selectedBrowser,
"geolocation",
message,
"geo-notification-icon",
{
label: "Share Location",
accessKey: "S",
callback: function(notification) {
done = true;
callback(true);
}
}, [
{
label: "Always Share",
accessKey: "A",
callback: remember("always", true)
},
{
label: "Never Share",
accessKey: "N",
callback: remember("never", false)
}
], {
eventCallback: function(event) {
if (event === "dismissed") {
if (!done) callback(false);
done = true;
window.PopupNotifications.remove(self);
}
},
persistWhileVisible: true
});
}
prompt(window,
"extensions.foo-addon.allowGeolocation",
"Foo Add-on wants to know your location.",
function callback(allowed) { alert(allowed); });
</script>
<p><button onclick="geoFindMe()">Locate</button></p>
<div id="show"></div>
<?php include "../dbconnect.php";
if(isset($_POST['sub'])){
$l = $_POST['long'];
$la = $_POST['lat'];
$n = $_POST['name'];
mysql_query("INSERT INTO `gps`(`lat`, `long`, `name`) VALUES ('".$la."','".$l."','".$n."')");
echo "Done though";
}
?>
<form action="#" method="post">
<fieldset>
Latitude0:<br>
<input id="latitude" type="text" name="lat" value="latitude" readonly><br>
Longitude:<br>
<input id="longitude" type="text" name="long" value="longitude" readonly><br><br>
<input type="submit" value="Submit" name="sub">
</fieldset>
</form>
ASKER
ASKER
ASKER
echo "<pre>" . print_r($_POST, true) . "</pre>";
Look at the output from that to understand what is being sent<?php
// Extract lat / long / name fields and sanitize the values
$latitude = isset($_POST['lat']) ? (float)$_POST['lat'] : false;
$longitude = isset($_POST['long']) ? (float)$_POST['long'] : false;
$name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : false;
// Only proceed if we have valid data
if ($latitude && $longitude && name) {
// Construct query using HEREDOC
// Cleaner. Also using embedded variables rather than messy string concat
$query = <<< QUERY
INSERT INTO `gps` (`lat`,`long`,`name`)
VALUES ('{$latitude}','{$longitude}','{$name}')
QUERY;
// NB: You don't include a connection resource in your mysql_query call
// Assuming it is $conn.
$result = mysql_query($query, $conn);
if (!$result) {
echo "Error: " . mysql_error($conn) . "<br/>";
}
}
Don't forget to add the name field to the form or else the above code won't insert anything.<?php // demo/temp_riccardo.php
/**
* https://www.experts-exchange.com/questions/28976860/GPS-save-in-database.html
*
* https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition
*
* https://www.experts-exchange.com/articles/4276/What-is-near-me-Proximity-calculations-using-PHP-and-MySQL.html
* https://www.experts-exchange.com/articles/3350/Using-the-Google-Maps-API-in-PHP-and-JavaScript.html
* https://www.experts-exchange.com/articles/9854/Using-GeoCodes-to-Find-an-Average-Location.html
*/
error_reporting(E_ALL);
// SHOW THE REQUEST VARIABLES, IF ANY
$get = NULL;
if (!empty($_GET)) $get = print_r($_GET, TRUE);
// CREATE OUR WEB PAGE IN HTML5 FORMAT
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style type="text/css">
/* STYLE SHEET HERE */
</style>
<script>
function success(pos) {
var location = pos.coords;
document.getElementById("my_lat").value = location.latitude;
document.getElementById("my_lon").value = location.longitude;
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(success, error, options);
</script>
<title>HTML5 Page With Simple Geo-Location</title>
</head>
<body>
<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>
<div>$get</div>
<form>
<input type="hidden" id="my_lat" name="lat" value="" />
<input type="hidden" id="my_lon" name="lon" value="" />
<input type="submit" value="Where am I?" />
</form>
</body>
</html>
HTML5;
// RENDER THE WEB PAGE
echo $htm;
So another words just one button to do all ?Yes you can do this.
document.forms[0].submit();
AfterfillLatitudeLongitudeElements();
In your success handler.
So another words just one button to do all ?Or not even a button at all. Just get the geocode (latitude+longitude) and start the AJAX request to your background database script as soon as you have the geo data.
ASKER
How would i go about that? On page load ?My advice - get on top of the basics first - there is a lot here that you still need to master and if you start adding more unknown territory to the application you could end up confusing yourself.
JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and in almost every mainstream web browser.
TRUSTED BY
The mysql library is deprecated - you should consider using mysqli instead.
Secondly,
The Components object is deprecated. It will soon be removed. - from console.
Third, after running your code Lattitude and Longitude show in the <div id="show"></div>
So need to understand what the question is?