I am developing one webproject and in that project i have requirement that
there will be one button there named by auto detect and when ever any one
click on that button visitor will get his location popup in this near textbox,i have created it and seen result in console.
autodetect.html:44 {error_message: "This API project is not authorized to use >this API.", results: Array(0), status: "REQUEST_DENIED"}
Following is the code for it:
<!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>Auto detect location</title>
</head>
<body>
<button onClick="getLocation()">Get Location</button>
<!--output will display here-->
<div id="output" style="margin-top: 20px;"></div>
<div id="output1" style="margin-top: 20px;"></div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
var x = document.getElementById('output');
var y = document.getElementById('output1');
x.innerHTML = "Here is output";
function getLocation() {
//alert('hi getLocation working');
if (navigator.geolocation) {
// x.innerHTML = "Supporting..";
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Sorry your browser not supporting autodetect location.";
}
}
function showPosition(position) {
// x.innerHTML = position.coords.latitude;
// y.innerHTML = position.coords.longitude;
var locAPI = "https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyCY2xZxxjq0U6iVzYJetKi9uJZnmIrnPGs&latlng=" + position.coords.latitude + "," + position.coords.longitude + "&sensor=true";
// x.innerHTML = locAPI;
$.get({
url: locAPI,
success: function(data) {
console.log(data);
}
});
}
</script>
</body>
</html>
how we can get code corrected so that we will det displayed this location of the visitos ?
From the error message, it looks like you don't have a project with the api enabled, maybe this could help.Also you shouldn't share your api key publicly.
Related
I have a website in which I want to add a file upload option so how to do it using firebase in HTML
and I also want to collect user details while uploading files like users entering details and storing them in the database. How to do it.
I am a beginner in programming that's why I am asking please help me who knows the answer if possible please provide the code
The code which I have tried :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
Upload Files<br />
<input type="file" id="files" multiple /><br /><br />
<button id="send">Upload</button>
<p id="uploading"></p>
<progress value="0" max="100" id="progress"></progress>
</div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-storage.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "******************",
authDomain: "******************",
projectId: ******************,
storageBucket: ******************,
messagingSenderId: "******************",
appId: "******************",
measurementId: "******************"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<script>
var files = [];
document.getElementById("files").addEventListener("change", function(e) {
files = e.target.files;
for (let i = 0; i < files.length; i++) {
console.log(files[i]);
}
});
document.getElementById("send").addEventListener("click", function() {
//checks if files are selected
if (files.length != 0) {
//Loops through all the selected files
for (let i = 0; i < files.length; i++) {
//create a storage reference
var storage = firebase.storage().ref(files[i].name);
//upload file
var upload = storage.put(files[i]);
//update progress bar
upload.on(
"state_changed",
function progress(snapshot) {
var percentage =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
document.getElementById("progress").value = percentage;
},
function error() {
alert("error uploading file");
},
function complete() {
document.getElementById(
"uploading"
).innerHTML += `${files[i].name} upoaded <br />`;
}
);
}
} else {
alert("No file chosen");
}
});
function getFileUrl(filename) {
//create a storage reference
var storage = firebase.storage().ref(filename);
//get file url
storage
.getDownloadURL()
.then(function(url) {
console.log(url);
})
.catch(function(error) {
console.log("error encountered");
});
}
</script>
</body>
</html>
I want to display reviews on a webpage but have trouble with JSON parsing and formatting. Any help is greatly appreciated. I can handle the HTML and CSS markup, I just need to loop through each new review and get the reviewer, reviewtext, pictureurl, etc.
So far, it's only able to get the amount of reviews. I'm new to JSON and am having trouble parsing the reviews and getting the format right.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<title>Ilan's Test</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div id="results">
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script>
var myurl = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/financial-sanity-now-los-angeles-2/reviews";
$.ajax({
url: myurl,
headers: {
'Authorization':'Bearer API-KEY-GOES-HERE',
},
method: 'GET',
dataType: 'json',
success: function(data){
// Grab the results from the API JSON return
var totalresults = data.total;
// If our results are greater than 0, continue
if (totalresults > 0){
// Display a header on the page with the number of results
$('#results').append('<h5>We discovered ' + totalresults + ' reviews!</h5>');
// Itirate through the JSON array of 'reviews' which was returned by the API
$.each(data.reviews[id], function(id, review) {
// Store each review object in a variable
var id = review.id;
var reviewtext = reviews[id].text;
var reviewrating = reviews[id].rating;
// Append our result into our page
$('$results').append(reviewtext + reviewrating + reviews);
});
} else {
// If our results are 0; no reviews were returned by the JSON so we display on the page no results were found
$('#results').append('<h5>We discovered no results!</h5>');
}
}
});
</script>
</body>
</html>
Minor mistakes with the code, but it's fine; your each function was a bit messy and you accidentally used $results as a reference which should've been #results; but it's all good your getting it!
Check out the code below (note Yelp only allows 3 reviews to be fetched; so when you see 8 total; it won't fetch more than 3);
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<title>Ilan's Test</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div id="results">
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script>
var myurl = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/financial-sanity-now-los-angeles-2/reviews";
$.ajax({
url: myurl,
headers: {
'Authorization':'Bearer API-KEY-GOES-HERE',
},
method: 'GET',
dataType: 'json',
success: function(data){
// Grab the results from the API JSON return
var totalresults = data.total;
// If our results are greater than 0, continue
if (totalresults > 0){ console.log(data);
// Display a header on the page with the number of results
$('#results').append('<h5>We discovered ' + totalresults + ' reviews!</h5>');
// Itirate through the JSON array of 'reviews' which was returned by the API
$.each(data.reviews, function(i, item) {
// Store each review object in a variable
var author = item.user.name;
var reviewtext = item.text;
var reviewrating = item.rating;
// Append our result into our page
$('#results').append('Author: <b>' + author + '</b><br> Review: ' + reviewtext + '<br>Rating: ' + reviewrating + ' <hr>');
});
} else {
// If our results are 0; no reviews were returned by the JSON so we display on the page no results were found
$('#results').append('<h5>We discovered no results!</h5>');
}
}
});
</script>
</body>
</html>
I want to get the users' profile, like user id and email address, i have tried many ways to do it, but still get the error of "TypeError: googleUser.getBasicProfile is not a function"
I follow the instruction of google document, but i still get the error:
and here is all code of it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>googleSignin</title>
<meta name="google-signin-requestvisibleactions" content="https://schema.org/AddAction" />
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/plus.login" />
<meta name="google-signin-client_id" content="589020135825-sbg93psr9i0v8gq6ajm7mv9et38o9ts2.apps.googleusercontent.com">
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark" onclick="onSignIn('googleUser')"></div>
<script>'
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
var user_name = profile.getName();
alter(user_name);
console.log("ID: " + profile.getId());
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
//The ID token you need to pass to your backend:
//var id_token = googleUser.getAuthResponse().id_token;
//console.log("ID Token: " + id_token);
}
function signOut(){
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function() {
console.log('User signed out!');
});
}
function onLoad() {
gapi.load('auth2', function() {
var auth2 = gapi.auth2.init();
auth2.then(function(){
//current values
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
if (!isSignedIn) {
//rendering it
gapi.signin2.render('google-signin-button', {
'onsuccess': 'onSignIn'
});
}
});
});
}
</script>
Sign out
<script src="https://apis.google.com/js/platform.js" async defer></script>
</body>
</html>
Comparing your code to the example you don't need the onclick handler in your button div. The parementer you pass via that is a string giving the error. Let platform.js sort out the calling
You might want to add asunc defer to you script as well
see https://developers.google.com/identity/sign-in/web/
I have created a streaming webcam with html5. At the moment I can take a picture through my web cam, but I would like to know if it is possible to choose media stream device from the list, e.g. I have two web cams I want to choose the webcam to activate. How can I do that with html5 getUserMedia() call?
Thanks!
You can get the list of web camera
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Video Camera List</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js" ></script>
<style type="text/css" media="screen">
video {
border:1px solid gray;
}
</style>
</head>
<body>
<script>
if (!MediaStreamTrack) document.body.innerHTML = '<h1>Incompatible Browser Detected. Try <strong style="color:red;">Chrome Canary</strong> instead.</h1>';
var videoSources = [];
MediaStreamTrack.getSources(function(media_sources) {
console.log(media_sources);
// alert('media_sources : '+media_sources);
media_sources.forEach(function(media_source){
if (media_source.kind === 'video') {
videoSources.push(media_source);
}
});
getMediaSource(videoSources);
});
var get_and_show_media = function(id) {
var constraints = {};
constraints.video = {
optional: [{ sourceId: id}]
};
navigator.webkitGetUserMedia(constraints, function(stream) {
console.log('webkitGetUserMedia');
console.log(constraints);
console.log(stream);
var mediaElement = document.createElement('video');
mediaElement.src = window.URL.createObjectURL(stream);
document.body.appendChild(mediaElement);
mediaElement.controls = true;
mediaElement.play();
}, function (e)
{
// alert('Hii');
document.body.appendChild(document.createElement('hr'));
var strong = document.createElement('strong');
strong.innerHTML = JSON.stringify(e);
alert('strong.innerHTML : '+strong.innerHTML);
document.body.appendChild(strong);
});
};
var getMediaSource = function(media) {
console.log(media);
media.forEach(function(media_source) {
if (!media_source) return;
if (media_source.kind === 'video')
{
// add buttons for each media item
var button = $('<input/>', {id: media_source.id, value:media_source.id, type:'submit'});
$("body").append(button);
// show video on click
$(document).on("click", "#"+media_source.id, function(e){
console.log(e);
console.log(media_source.id);
get_and_show_media(media_source.id);
});
}
});
}
</script>
</body>
</html>
In the latest Chrome Canary (30.0.1587.2) it looks like you can enable device enumeration in chrome://flags (looks like it might already be enabled) and use the MediaStreamTrack.getSources API to select the camera.
See this WebRTC bug and mailing list post for more details.
I'm trying to put a Google map in my page and make it so that when the page loads the map will display exactly the location of the user. In order to do so, I've taken the google maps API code and inserted it into my HTML5 page. At first the browser did ask for permission to share my location but it isn't actually showing this location on the map; I've tried with two or more combinations of functions but it is still not working.... please, I need help! If anyone can tell me what is wrong with the code please do:
<html lang="en" manifest="halma.manifest">
<head>
<meta charset="utf-8">
<title>helmas</title>
<link rel="stylesheet" type="text/css" href="css2.css">
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAycdS3aS7dItIegOaJzT2RBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSiGkO1l1KdZvNzo-8b-o7M21o4UA"></script>
<!--[if IE]>
<script src="excanvas.js"></script>
<![endif]-->
</head>
<<body onload="loadMap()" onunload="GUnload()">
<article>
<div id="map" style="width:100%;height:800px;"></div>
<script>
if (navigator.geolocation) {
// try to get the users location
}
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.watchPosition(showPositionOnMap, errorMessage,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 });
}
else {
alert("Geolocation is not supported by this browser");
}
var map = null;
function loadMap() {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(52.2021, 0.1346 ), 12); // (sets the map centre to Cambridge UK)
map.setUIToDefault();
}
function showPositionOnMap(position) {
var geoCoords = new GLatLng(position.coords.latitude, position.coords.longitude);
map.addOverlay(new GMarker(geoCoords));
}
function errorMessage(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
</script>
Perhaps the sensor parameter in the maps invocation needs to be set to "true" - at the moment you have it set to "false". So your script tag should contain this url
<script src="http://maps.google.com/maps?file=api&v=2&sensor=true&key=ABQIAAAAycdS3aS7dItIegOaJzT2RBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSiGkO1l1KdZvNzo-8b-o7M21o4UA"></script>
For more info:
Google Maps Api sensor location