Geolocation tracking not being asked for permission in chrome on desktop - javascript

I'm running basic code that just outputs the longitude and latitude on the screen or prints an error if something goes wrong.
function getMyLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation, displayError);
}
else {
alert("Oops, no geolaction support");
}
}
function displayLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var h1 = document.getElementById("location");
console.log("hey " + latitude + " " + longitude);
h1.innerHTML += " " + latitude + ", " + longitude;
}
function displayError(error) {
var errorTypes = {
0: "unkown error",
1: "Permission denied by user",
2: "Position is not available",
3: "Request timed out"
};
var errorMessage = errorTypes[error.code];
if(error.code == 0 || error.code == 2) {
errorMessage += " " + error.message;
}
var div = document.getElementById("location");
div.innerHTML = errorMessage;
}
When i run in firefox and internet explorer i get pop-ups asking for permission and the code runs fine. When I use my phone's google chrome browser i get asked for permission and everything works fine. When i try chrome on my desktop I never get asked permission and my error code runs and prints: "Permission denied by user". I've checked in my chrome settings and made sure my hostname is allowed and tried allowing any site to track my physical location but to no avail. What do?

Related

Unable to retrieve geolocation

I am trying to run a Javascript code to retrieve a device's geolocation. When I try to run the code from the localhost (127.0.0.1) the code runs as expected, opening a pop up to ask the user to enable location services. However, when I try to host this code or access it using the local IP address (192.168.x.y), the code fails with an error
Any ideas as to why it works for localhost and not otherwise.
Here's the JS Code
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var 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=13&size=300x300&sensor=false";
output.appendChild(img);
}
function error() {
output.innerHTML = "Unable to retrieve your location";
}
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
Thanks.
Recent versions of Chrome require secure protocols for some features. Fore example a page must be served up httpS for it to be able to obtain the user's geolocation.
The restriction is relaxed for localhost to enable dev/debugging.

Can't get weather API

I am trying to get JSON data from openweathermap.org, but $.getJSON doesn`t work.
If I call API from browser it display JSON data, but it doesnt work in JS file.
$(document).ready(function(){
$("#button").click(function(){
navigator.geolocation.getCurrentPosition(location,error,{timeout:10000});
});
function location(pos){
$("#crd").html("Location: " + pos.coords.latitude + " , " + pos.coords.longitude);
$.getJSON("api.openweathermap.org/data/2.5/weather?lat="+pos.coords.latitude+"&lon="+pos.coords.longitude+"&APPID=key", function(json){
$("#weather").html(JSON.stringify(json));
});
}
function error(err){
var errorCode = "";
switch(err.code) {
case err.PERMISSION_DENIED:
errorCode = "User denied the request for Geolocation.";
break;
case err.POSITION_UNAVAILABLE:
errorCode = "Location information is unavailable.";
break;
case err.TIMEOUT:
errorCode = "The request to get user location timed out.";
break;
case err.UNKNOWN_ERROR:
errorCode = "An unknown error occurred.";
break;
}
$("#crd").html("Error " + err.code + ": " + errorCode);
}
});
One more problem. It worked on localhost when I add http://, but it doesn`t work in codepen. Any idea?
I found solution that in codepen you need to use some cross-origin like https://cors-anywhere.herokuapp.com/
You are missed the sheme: http:// try with this:
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+pos.coords.latitude+"&lon="+pos.coords.longitude+"&APPID=key", function(json){
$("#weather").html(JSON.stringify(json));
});

GeoLocation fetching wrong latitude longitude

I am trying to fetch the current location using the geolocation . A month before it was giving correct location but not am getting different location . I have used the same code as below.
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;
*/ var query = "?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
var stateObj = { query: query };
history.pushState(stateObj, "query added", query);
var flag = true;
/*var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
req.onreadystatechange=function(){if((r.readyState==4)&&(r.status==200)){ console.log('location was sended to server'); }};
req.open("GET","?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude,true);
req.send(null);
*/
}
Another problem is its fetching the latlong based on isp not on IP. So if i use this code using mobile internet ! It gives latlong of another state. Is there any way to make this work again?

Load js function only once onload

I want this JS function to be called only once when the page is loaded .
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;
window.location.href = "? latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
var flag = true;
}
It's going into an infinite loop because you are redirecting the page with
window.location.href = "? latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
every time the page loads. Instead you could do something like this for showPosition():
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
var query = "? latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
var stateObj = { query: query };
history.pushState(stateObj, "query added", query);
var flag = true;
}
This will add the query parameters to the URL without refreshing the page. For more details on history.pushState(), see https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
You can simply use the onload event handler:
<body onload="getLocation()">
This will fire as soon as the page is ready.
Alternatively, you can use jQuery's .ready()like this:
$(document).ready(function(){
getLocation();
});
Your code it's a big closure! It generate new request on this step:
window.location.href = "?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
You can use different ways:
simple parse window.location.href on load and don't ask location if
(window.location.href.indexOf('?')!=-1)
mark client with browser data storage or coockies, and check it before ask location.
use Ajax for send location info to server:
var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
req.onreadystatechange=function(){if((req.readyState==4)&&(req.status==200)){ console.log('location was sended to server'); }};
req.open("GET","?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude,true);
req.send(null);

I can't get location on chrome - javascript

I'm coding a web app which is using by maps. I want to find visitor's location. It is working on firefox but not working on chrome. Chrome says "it is blocked that track your location by this page." How can i fix it for chrome?
function onPositionUpdate(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
alert("Current position: " + lat + " " + lng);
}
if(navigator.geolocation)
navigator.geolocation.getCurrentPosition(onPositionUpdate);
else
alert("navigator.geolocation is not available");
and now I try this:
function get_location() {
if (geo_position_js.init()) {
geo_position_js.getCurrentPosition(show_map, handle_error);
}
}
function show_map(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("lat:" + latitude + " long:" + longitude);
}
function handle_error(err) {
alert(err.code);
if (err.code == 1) {
// user said no!
}
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(show_map, handle_error);
} else {
error('not supported');
}
When I run this with chrome I get "javascript alert 1" error. It is working on firefox.
Edit: I solve this problem by using html5 geolocation http://www.w3schools.com/html/html5_geolocation.asp
Type on address bar: chrome://settings/content
Some features only be accessible on "secure origins" (such as HTTPS) where the full ancestor chain is also secure.
https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins

Categories