Geolocation permission - javascript

I am trying to do a simple geolocation html5 :
$(function() {
var currentLatitude ="";
var currentLongitude ="";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
function showPosition(position) {
currentLatitude = position.coords.latitude;
currentLongitude = position.coords.longitude;
}
} else {
// location based on the IP - less accurate
}
And the error is permission for location error even when i had my site(running local) on exceptions .
My second option is by IP (ipinfo.io) :
function showError(error) {
var x = $('#curr_loc_target');
switch(error.code) {
case error.PERMISSION_DENIED:
x.html("User denied the request for Geolocation.");
jQuery.get("http://ipinfo.io/json", function (response)
{
console.log(response) ;
currentLatitude = response.loc.split(',')[0];
currentLongitude = response.loc.split(',')[1];
console.log("lat" + currentLatitude+ "," + "lngs" +currentLongitude) ;
} );
break;
case error.POSITION_UNAVAILABLE:
x.html("Location information is unavailable.");
break;
case error.TIMEOUT:
x.html("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
x.html("An unknown error occurred.");
break;
}
}
And it works but it is not accurate at all .
All i need to do is send lat , lng to my server , if it will be not local it will work ?
or anyone knows a way to solve this error ?

The code working on my site. It seems like you have disabled the geolocation tracking on your browser that send you directly to the error scenario. Please take note that it will require user to explicitly grant you the permission to get the location tracking info.

I've tried to test geolocation, opening the .html file from my local machine, too - and Chrome always gave me the error callback here:
navigator.geolocation.getCurrentPosition(success, error);
inspite of the geolocation tracking was enabled.
Other browsers gave the success callback.
Then I put the page to the hosting, and it returned success in all browsers, including Google Chrome.
May be you had similar reason with the permission for location when your site is running local.

Related

How to fix "REQUEST_DENIED" while getting current location in cordova

I am trying get current location with address by using Cordova geolocation plugin . but i am getting below error message.
{error_message: "You must use an API key to authenticate each reque…, please refer to http://g.co/dev/maps-no-account", results: Array(0), status: "REQUEST_DENIED"}
error_message: "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account"
results: []
status: "REQUEST_DENIED"
for getting current location. below code i am using please correct my code
$scope.init = function () {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
if (navigator.connection.type == Connection.NONE) {
} else {
}
var networkConnection = navigator.connection.type;
if (networkConnection != null) {
navigator.geolocation.getCurrentPosition(success, error);
}
else {
alert('Please check your network connection and try again.');
}
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
getDetails(latitude, longitude);
}
function error(error) {
alert('Please check your network connection and try again.');
}
function getDetails(latitude, longitude) {
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&sensor=false";
$.getJSON(url, function (data) {
console.log(data);
});
}
Please correct my code i expected out put current location with address. Thanks for advance.
You must use an API key
When you signed up for the maps platform, you should have gotten an access key, which you need to pass with every request to authenticate.
Now, as far as i can see, you don't have that token on your URL parameters. ( You may need to send it with the request headers, check the API docs on how it expects it)
EDIT:
This is the format:
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap
Try this:
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "?key= "+"ADD YOUR KEY HERE" + "&sensor=false";
Also, try using template strings rather than having 10s of + in your string

Javascript fetch api return 200 and response but .then cant work

I am trying the openweathermap api on web. The fetch is indeed return 200 ok and responses but the following .then seems to not work or inherited from fetch as I cant manipulate the received data either in console.log, alert or print to html.
It doesnt show any error or warnings. But just [HTTP/1.1 200 OK 637ms].
Please help me on my codes. Very much appreciates. Thank you...
let weatherInfo = document.getElementById("weatherInfo");
//Trigger on click on HTML
function submitFormCheck() {
//Check if text field contain value
//Check if browser support Geolocation
const txtBox = document.getElementById('textBoxx').value;
if (txtBox == "" || txtBox.length == 0 || txtBox == null) {
//Retrieve the location from callback and fetch api
getLocation(function(lat_lng) {
console.log(`longitude: ${ lat_lng.lat } | latitude: ${ lat_lng.lng }`);
const url = 'https://api.openweathermap.org/data/2.5/forecast?lat=' + lat_lng.lat + '&lon=' + lat_lng.lng + '&APPID=075bd82caf51b82c26d704147ba475da&units=metric';
const fetchDetails = {
method: 'GET'
};
fetch(url, fetchDetails)
.then((resp) => resp.json())
.then((data) => {
console.log("testing"); //console.log cant work
alert("testing"); //alert cant work
let i = data.city;
console.log(i.name); // response.data cant print out
})
.catch((error) => console.log(error));
});
} else {
return false;
}
function getLocation(callback) {
if (navigator.geolocation) {
let lat_lng = navigator.geolocation.getCurrentPosition(function(position) {
// get current location by using html 5 geolocation api
let userPosition = {};
userPosition.lat = position.coords.latitude;
userPosition.lng = position.coords.longitude;
callback(userPosition);
}, positionHandlingError);
} else {
alert("Geolocation is not supported by this browser. Please enter the location manually");
}
}
// if failed to get location
function positionHandlingError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
console.log("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
console.log("Location information is unavailable.");
break;
case error.TIMEOUT:
console.log("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
console.log("An unknown error occurred.");
break;
}
}
}
It seems you didn't prevent the default behaviour of form submitting:
function submitFormCheck(e) {
//Prevent form submit
e.preventDefault();
//Check if text field contain value
//Check if browser support Geolocation
const txtBox = document.getElementById('textBoxx').value;
...

get geolocation not working with jquery

I have used below code :
navigator.geolocation.getCurrentPosition(GetCoords, fail);
function GetCoords(position) {
alert("3");
document.getElementById("latitudetag").innerHTML = position.coords.latitude;
document.getElementById("longitudetag").innerHTML = position.coords.longitude;
}
function fail() {
alert("Geolocation is not supported by this browser.");
}
it always redirect me in fail function and I am not able to get lat long of current location.
can anyone help me to resolve it ?

how to bind the following to the local this context variable on button click event?

I seriously need help on this.
How do I print the lat and long using a button click event like:
<button id="geo" onclick="OnGeoClick()"> Get Location </button>
I have the following code:
var getGeo = {
showPosition :
function showPosition(position) {
self = this;
console.log(self)
self.lat = position.coords.latitude;
self.lng = position.coords.longitude;
console.log(self);
},
showError :
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
this.err = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
this.err = "Location information is unavailable.";
break;
case error.TIMEOUT:
this.err = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
this.err = "An unknown error occurred.";
break;
}
},
getLocation :
function getLocation() {
self = this;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(self.showPosition, self.showError, {enableHighAccuracy:true});
console.log(self);
} else {
self.err = "Geolocation is not supported by this browser.";}
}
};
function OnGeoClick() {...local this context binding?...}
such that window does not store lat and long but an accessible variable that can log(result) out;
You can use bind method to keep the context intact.
navigator.geolocation.getCurrentPosition(self.showPosition.bind(self), self.showError, {enableHighAccuracy:true});
And call it like this
function OnGeoClick() {
getGeo.getLocation();
}

Any way to simulate a *synchronous* XDomainRequest (XDR) request

We're making a cross domain call to the google maps geocode API. This was and is working all fine and dandy in modern browsers, but it wasn't working at all in IE8. Looks like it would fail in IE9 as well (partial CORS support). This led to including a XDomainRequest (XDR) to take care of IE8-9. Doing that worked fine in my standalone test to get data back in IE8.
The problem I'm running into now is XDR only works asynchronously so my geocode function returns before my xdr.onload fires.
In my search function, I call the geocode function:
var location = Geocode(city, state);
if (!location) {
alert('Unable to determine the location of the city and state you entered');
StopLoading();
return;
}
//function then uses location.lat and location.lng coordinates
I'm hitting the "Unable to determine location" alert above in IE8.
Here's my geocode function:
Geocode = function (address, state) {
var protocol = location.protocol,
url = '//maps.googleapis.com/maps/api/geocode/json?sensor=false&address=',
param = encodeURIComponent(address + ', ' + state),
json = {};
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
//IEs that do not support cross domain xhr requests
var xdr = new XDomainRequest();
xdr.open('get', protocol + url + param);
xdr.onload = function() {
json = jQuery.parseJSON(xdr.responseText);
};
xdr.send();
} else {
//good browsers
jQuery.ajax({
url: protocol + url + param,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
json = data;
}
});
}
//alert(json);
if (json.status !== 'OK') {
alert('Unable to determine the location of the city and state you entered');
return null;
}
return json.results[0].geometry.location;
};
If I comment out the alert(json) in the geocode function, I get my results in IE8 because that's a blocking operation so the request has time to finish and populates my json object. When it's run uncommented, the json object isn't populated.
Anyone have any ideas how I can get this working in IE?
asynchron is asynchron. If you want to do something after the request is finished u have to put it into the xdr.onload function.
There is no "wait" function in javascript. You could build one and do a setTimeout loop to check the variable all x-miliseconds. But that would not help u in this case (and its very ugly).
In your case you can use the onerror and ontimeout to check if the server had a problem, and the onload to check if the city is in the json.
xdr.onload = function() {
json = jQuery.parseJSON(xdr.responseText);
//check if a city is loaded, go on if true
};
xdr.onerror = function() {
alert('Unable to determine the location of the city and state you entered');
//do whatever u wanna do if something went wrong
xdr.ontimeout = function() {
alert('404 Server');
//do whatever u wanna do if something went wrong
}
i hope this helps you find the way (and by the way, the use of async requests is a much a better way then block the hole javascript/browser ;)
The jQuery doc says:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred)
is deprecated; you must use the success/error/complete callback
options instead of the corresponding methods of the jqXHR object such
as jqXHR.done() or the deprecated jqXHR.success()

Categories