I have the following full-code working.. the script retrieves the Latitude and Longitude every 3 seconds for a Car in movement, and save the data into a mysql table.
Even with the GPS running on the phone the accuracy is not so good.
I add the Options Var so the i can enableHighAccuracy: true .
but the accuracy still very bad when i draw the map:
is there a way to improve this?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title></title>
<script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js?ver=3.3.1'></script>
</head>
<body style="text-align: center">
<button style="font-size:30px" id="find_btn">Find Me</button>
<div id="result"></div>
<br>
<div id="resp"></div>
<br>
<button style="font-size:30px" id="stop_btn">STOP</button>
<script type="text/javascript">
function SaveLatLng(lat,lng) {
var url = "saveLatLng.php";
$.ajax({
type: "POST",
url: url,
data: {latitude:lat,longitude:lng},
success: function(data) {
$('#resp').html(data);
}
});
};
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
function randomQuote() { //user clicks button
if ("geolocation" in navigator) { //check geolocation available
//try to get user current location using getCurrentPosition() method
navigator.geolocation.getCurrentPosition(function(position){
$("#result").html("Found your location <br />Lat : "+position.coords.latitude+" </br>Lang :"+ position.coords.longitude);
SaveLatLng(position.coords.latitude,position.coords.longitude);
}, error, options);
} else {
console.log("Browser doesn't support geolocation!");
}
};
var interval = null;
$("#find_btn").click(function () {
interval = setInterval(randomQuote, 3000);
});
$("#stop_btn").click(function () {
clearInterval(interval);
});
</script>
</body>
</html>
Use watchPosition instead of getCurrentPosition every 3 secs. The later is optimized to return quickly at the possible expense of accuracy. Also you can check the accuracy (in meters) of the returned value and decide it is too inaccurate and ignore it.
You may also want to consider other position-filtering detailed here Min-distance, min-time etc
Related
My Problem
I have a login page that gives the user the option to "Login With Google".
When the user successfully logs in, I am storing their username and Google ID in the Session.
My problem is, on pages OTHER than the login page, I need to check to see if they are logged in. I am having problems getting this to work. If they are not logged in, I need to know that - putting in a simple global page variable for now would be suffice.
This code handles the login: ( the renderButton function is called immediately on page load )
var googleID; // global variable to hold ID
var token; // will hold token ( once I get this working )
// Render Google Sign-in button
function renderButton() {
gapi.signin2.render('gSignIn', {
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSuccess,
'onfailure': onFailure
});
}
// Sign-in success callback
function onSuccess(googleUser) {
gapi.client.load('oauth2', 'v2', function () {
var request = gapi.client.oauth2.userinfo.get({
'userId': 'me'
});
request.execute(function (resp) {
// GET GOOGLE ID
googleId = resp.id;
});
});
}
// Sign-in failure callback
function onFailure(error) {
alert(error);
}
// Sign out the user
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
loggedIn = false;
});
// Change Link
document.querySelector("#loginNav").innerHTML = "Login";
auth2.disconnect();
}
So this all works great on the login page.
But on my other pages, for instance my index page, how to I check to see if they are logged in?
I am trying this code, but getting NOTHING - no error, no success.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Login</title>
</head>
<body>
<div id="loginStatus">Status</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="https://apis.google.com/js/client:platform.js?onload=init" async defer></script>
<script>
var auth2; // Global
var loggedIn;
function init() {
var appStart = function () {
gapi.load('auth2', initSigninV2);
};
}
/**
* Initializes Signin v2 and sets up listeners.
*/
var initSigninV2 = function () {
auth2 = gapi.auth2.init({
client_id: 'MY-CLIENT--ID-HERE',
scope: 'profile'
});
if (auth2.isSignedIn.get() == true) {
alert("Loggin in!");
loggedIn = "LOGGED IN";
} else {
alert("Not Logged IN!!!");
loggedIn = "NOT LOGGED IN";
}
document.getElementById("loginStatus").innerHTML = loggedIn;
}
</script>
</body>
</html>
Can anyone help me get this working?
Thank you.
I found a solution that worked for me.
Once logged in the first time, I simply saved the user credentials in a local storage variable.
Then on subsequent pages, I check that variable.
It's not fool-proof, but for my basic needs it works.
Hello i started javascript and im making a dynamic ajax GET page, (refreshes page when json data changed etc.).
My problem is i need to refresh page or container div when data is changed
this my code
HTML:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Refresh" content="600">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="container">
<div id="event"></div>
<div id="counter">
<span id="countdown"></span>
</div>
</div>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
JS:
var request = $.ajax({
url: "data.php",
type: "GET",
dataType: "json"
}).done(function (data) {
var write = '<img src="' + data.img + '">';
$("#event").html(write);
$("#event").delay(data.countdown * 1000).fadeOut();
var i = data.countdown;
var fade_out = function () {
$("#counter").fadeOut().empty();
clearInterval(counter);
};
setTimeout(fade_out, data.countdown * 1000);
function count() { $("#countdown").html(i--); }
var counter = setInterval(function () { count(); }, 1000);
});
JSon is like this
{"img":"img\/maltolmeca.jpg","countdown":"60"}
In this day and age, it might be worth you looking into libraries such as Angular, React and Vuejs which handle 'data refreshing' for you.
Anyway, in your done() function you can just call location.reload() which would refresh the page.
...though I imagine that isn't what you are actually trying to achieve. Refreshing the page like that is a bad user experience usually, so let's try a better solution.
One way of 'reloading' a div is to do something like this:
if (data.success){
$("#event").fadeOut(800, function(){
$("#event").html(msg).fadeIn().delay(2000);
});
}
or even
$("#event").load("#event");
I just put this code in to my php folder, its like from stone age but its ok for my project.
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("data.php", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);
There are several ways to load reCAPTCHA using javascript such as below:
<html>
<head>
<title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type='text/javascript'>
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
</script>
</head>
<body>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
</body>
</html>
This code load captcha on pageload. I want load reCAPTCHA just when clicked on "MYBTN". So the code changes into:
<html>
<head>
<title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type='text/javascript'>
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
});
</script>
</head>
<body>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
</body>
</html>
But this code didn't work when I click on "MYBTN" and reCAPTCHA not load.
Help me plz. Thanks.
You just need to call loadCaptcha()
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
loadCaptcha(); // THIS LINE WAS MISSING
});
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit"></script>
Simple situation
Html
<input type="button" id="MYBTN" value="create captcha">
<div id="captcha_container"></div>
JS
var testSitekey = '6LeLzA4UAAAAANNRnB8kePzikGgmZ53aWQiruo7O';
$('#MYBTN').click(function() {
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': testSitekey
});
}, 1000);
});
Online demo (jsfiddle)
You just mentioned onload in your embedded script. Either you just remove onload from your embedded script or just keep your code outside of the onclick event in the function name loadCaptcha.
1. First Solution:
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
}
});
<script src="https://www.google.com/recaptcha/api.js?render=explicit"></script>
2. Second Solution
<script type='text/javascript'>
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
In first Solution your code will work when you click your button. Even you don't have to put then in loadCaptcha function you can directly call grecaptcha.render.
But when you mention onload in your script tag then it will not work according to your click then it will find the callback function you mentioned in the script. And as you wrote the loadCaptcha in onload of script and you wrote this function inside the onClick event. When the script tag executed, the code tried to find the loadCaptcha function which was not initialised till the script tag executed (as it would initialise on click event), So your script was not working.
JS
// Loading captcha with JavaScript on button click
jQuery(document).ready(function ($) {
$('#MYBTN').on('click',function() {
$.getScript( "https://www.google.com/recaptcha/api.js?render=__YOUR_KEY__" )
.done(function( script, textStatus ) {
if(typeof grecaptcha !== "undefined") {
grecaptcha.ready(function () {
grecaptcha.execute('__YOUR_KEY__', {
action: 'homepage'
})
.then(function (token) {
var recaptchaResponse = document.getElementById('captcha_container');
recaptchaResponse.value = token;
});
// Your other code here
// You can control captcha badge here
});
}
});
});
});
HTML
// Required HTML:
<body>
<input type="button" id="MYBTN" value="MYBTN">
<div id="captcha_container"></div>
</body>
I've implemented the captcha to be loaded only after one of the required fields of my form was focus. I also implemented a check variable to see if the captcha's dependencies were inserted before.
Here is is:
jQuery('#MyRequiredInputId').focus(function () {
if(typeof loadedRecaptcha != 'undefined'){
return;
}
jQuery.getScript("https://www.google.com/recaptcha/api.js?render=___YOURKEY__")
.done(function (script, textStatus) {
if (typeof grecaptcha !== "undefined") {
grecaptcha.ready(function () {
var siteKey = '___YOURKEY___';
jQuery('body').append(jQuery('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': siteKey
});
}, 1000);
});
}
loadedRecaptcha = true;
});
});
Note that in my case, I have a <div id= "captcha_container"></div> where I want to display my captcha.
Result:
I got the same issue today when I discovered that there are about 21 requests for Google Recaptcha even without open the login modal, this is indeed too much ):
After trying this method:
HTML
<div class="row">
<div class="col-sm-12 btm10">
<div id="captcha_container"></div>
</div>
</div>
JS
<script>
var Sitekey = '<?php echo config('google_key') ?>';
$('#loginbtn').click(function() {
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': Sitekey
});
}, 1000);
});
</script>
finally, I get the results I want, now the recaptcha only loads when the login modal opens (based onClick function).
Unfortunately, I found that the main Google Recaptcha script still loads in console even while using the delay method mentioned above because the main script is declared on the page head:
<script src="https://www.google.com/recaptcha/api.js"></script>
So, I removed it from the page head then combined some lines of codes together to get it to work and only loads when the modal opens as follow:
Final code:
<div class="row">
<div class="col-sm-12 btm10">
<div id="captcha_container"></div>
</div> //Wherever you want the reCaptcha to appear
</div>
<script>
//Add to the header or the footer it doesn't matter
var Sitekey = '<?php echo config('google_key') ?>';
$('#loginbtn').click(function() {
$.getScript("https://www.google.com/recaptcha/api.js") //The trick is here.
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': Sitekey
});
}, 1000);
});
</script>
You can view it in action here:
https://youtu.be/dAZOSMR8iI8
Thank you
Tell Google you want to render the recaptcha explicitly (when you are ready). https://www.google.com/recaptcha/api.js?render=explicit
After the api script has run grecaptcha is available globally.
<!DOCTYPE html>
<html lang="en">
<head> </head>
<body>
<div id="whereIWantRecaptcha"></div>
<button id="myButton">show Recaptcha</button>
<script
src="https://www.google.com/recaptcha/api.js?render=explicit"
async
defer
></script>
<script>
var button = document.querySelector('#myButton');
button.addEventListener('click', function(){
grecaptcha.render('whereIWantRecaptcha', {
'sitekey' : '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'
});
});
</script>
</body>
</html>
So; I am developing this web application that works based on the location of the user.
The part that finds the coordinates and the part that converts those coordinates into an address both work individually. However the variable from the first function doesn't seem to transfer over to do the second function and I can't figure out why.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script type="text/javascript">
var coordinates;
function getCoordinates(){
var options = {
enableHighAccuracy: true,
timeout: 4500,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Enlem : ' + crd.latitude);
console.log('Boylam: ' + crd.longitude);
console.log('Hata Payı ' + crd.accuracy + ' metre.');
coordinates = new google.maps.LatLng(crd.latitude, crd.longitude);
alert(coordinates);
return coordinates;
};
function error(err) {
console.warn('HATA(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);
}
var ReverseGeocode = function () {
//This is declaring the Global variables
var geocoder, map, marker;
//This is declaring the 'Geocoder' variable
geocoder = new google.maps.Geocoder();
function GeoCode(latlng) {
// This is making the Geocode request
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if(status !== google.maps.GeocoderStatus.OK)
{
alert(status);
}
// This is checking to see if the Geoeode Status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
var address = (results[0].formatted_address);
//This is placing the returned address in the 'Address' field on the HTML form
document.getElementById('Address').value = results[0].formatted_address;
}
});
}
return {
Init: function () {
var latlng = getCoordinates();
alert(latlng);
GeoCode(latlng);
},
};
} ();
</script>
</head>
<body>
<div>
<input name="Address" type="text" id="Address" size="55" />
</div>
<div>
<input type="button" value="Adres Bul" onclick="ReverseGeocode.Init()">
</div>
<div id="map_canvas" style="height: 90%; top: 60px; border: 1px solid black;">
</div>
</body>
</html>
Your main problem: getCoordinates() does not return coordinates. So you cannot use it like this:
var latlng = getCoordinates();
Javascript has asyncronous stuff. That means it takes javascript some time to do it.
The way javascript handles this: You send a request, and you provide a callback (a function). Whenever javascript is ready, your callback will be executed. Positioning is one of those asynchronic things.
Here is a short example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script type="text/javascript">
// this function is triggered when geolocation has found coordinates
function geolocationReturnedCoordinates(coordinates) {
document.getElementById('log').innerHTML =
'lat: ' + coordinates.coords.latitude +
'<br>lng: ' + coordinates.coords.longitude +
'<br>accuracy: ' + coordinates.coords.accuracy;
// Here would be a good place to call Reverse geocoding, since you have the coordinates here.
GeoCode(new google.maps.LatLng(coordinates.coords.latitude, coordinates.coords.longitude));
}
// geocoder
geocoder = new google.maps.Geocoder();
function GeoCode(latlng) {
// This is making the Geocode request
geocoder.geocode({'location': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var address = (results[0].formatted_address);
//This is placing the returned address in the 'Address' field on the HTML form
document.getElementById('Address').value = results[0].formatted_address;
}
});
}
function search_position_and_address() {
// we start the request, to ask the position of the client
// we will pass geolocationReturnedCoordinates as the success callback
navigator.geolocation.getCurrentPosition(geolocationReturnedCoordinates, null, null);
}
</script>
</head>
<body>
<input type="button" value="GO" onclick="search_position_and_address()"> Get position (coordinates) of the client. -- Then look for the address
<div id="log"></div>
<input id="Address" placeholder="Address">
</body>
</html>
It's up to you to put it back in your structure.
I just compiled the shortest code that permitted me to make my point.
Also the names of the functions ... I'm trying to make a point. In real life you would pick a shorter name.
I was used 2.0 version of Contacts API with Gdata library to import customer gmail information. This version not supported anymore and I try to move to V3 but I see the Gdata not supported with v3 and I spend dayes try to modify current code to work with "Contacts API version 3.0" for javascript.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Gmail Login</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
</head>
<body style="margin:0;padding:0;">
<img src="/images/templates.png" style="display:none;"/>
<script type="text/javascript">
google.load("gdata", "2.s");
google.setOnLoadCallback(function (){
if(window.location.hash=="") {
if(!checkLogin()){
logMeIn();
} else {
var feedUrl = "https://www.google.com/m8/feeds/contacts/default/full";
query = new google.gdata.contacts.ContactQuery(feedUrl);
query.setMaxResults(5000);
myService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
myService.getContactFeed(query, function(result) {
document.cookie="g314-scope-0=";
window.opener.parseGmailContacts(result.feed.entry);
close();
}, function(e){
alert(e.cause ? e.cause.statusText : e.message);
});
}
}
});
function logMeIn() {
scope = "https://www.google.com/m8/feeds";
var token = google.accounts.user.login(scope);
}
function logMeOut() {
google.accounts.user.logout();
}
function checkLogin(){
scope = "https://www.google.com/m8/feeds/";
var token = google.accounts.user.checkLogin(scope);
return token;
}
</script>
</body>
</html>
Google Contacts API version 3.0 supported javascript client or gdata library?
var authParams = gapi.auth.getToken() // from Google oAuth
authParams.alt = 'json';
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full',
dataType: 'jsonp',
data: authParams,
success: function(data) { console.log(data); }
});
Basically just plug this in to the authSample.html provided in the google api javascript library -- https://code.google.com/p/google-api-javascript-client/