It had worked previously in my code, however with the recent changes I made it seems to be broken. I tried looking online for solutions, however this seems specific to me in terms of what I need. All i want is for an "alert();" to be showen if the browser Geolocation Services request is denied. Here is the code without the alert added in. Thank you.
if (navigator.geolocation) {
// Locate position
navigator.geolocation.getCurrentPosition(displayPosition);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
blacklisted_areas = {
'area 51': [1, 2],
'pink unicorn zoo': [1, 2],
};
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
var thediv = document.getElementById('locationinfo');
thediv.innerHTML = '<p>Your longitude is :' + mylong + ' and your latitide is ' + mylat + '</p>';
var blacklisted = false;
for (let x of Object.values(blacklisted_areas)) {
if (mylat === x[0] && mylong === x[1]) {
blacklisted = true;
}
}
if(!blacklisted){
window.location="insertURLHere";
}
}
Just handle error case:
navigator.geolocation.getCurrentPosition(displayPosition, onError);
function onError (error) {
if (error.code == error.PERMISSION_DENIED)
alert("you denied geolocation");
};
Pass a callback for on error.
if (navigator.geolocation) {
// Get user's geo position.
navigator.geolocation.getCurrentPosition(function success(position) {
// Success
}, function error(err) {
// Geolcoation denied.
if (err.code === err.PERMISSION_DENIED) {
// Determine reason for error.
if (err.message.match(/secure/i)) {
console.alert('INSECURE_ORIGIN');
} else {
console.alert('INSECURE_ORIGIN');
}
}
});
}
Related
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
I am attempting to build a weather API using the freeCodeCamp API for the weather project.
What I want to do is use the getLocation function to get the latitude and longitude and then return them as a variables that I can use to then concat to a URL.
By using the URL I can obtain the json information I need to output the Fahrenheit and any other info I need.
Since I require an https connection I am using codepen for testing purposes.
additional info:
Codepen:
https://codepen.io/rogercodes/pen/gXvOoO
freeCodeCamp API:
https://fcc-weather-api.glitch.me/
HTML
<html>
<head>
<!-- <link rel="stylesheet" type="text/css"
href="css/quoteStyles.css"> -->
</head>
<body>
<button onclick="getWeather(finalLat,finalLon)">getWeather</button>
<p>What is</p>
<button onclick="getLocation()">Try It</button>
<p id='geoAPI'>Geo API</p>
<p id="lan">Test Lan: </p>
<p id='geo'>geoLocal</p><script>
</script>
</body>
<script src="javascript/weatherTest.js"></script>
<!-- <script src="JSON/weather.json"></script> -->
Javascript
var api= "https://fcc-weather-api.glitch.me/api/current?";
var googleApi="https://www.googleapis.com/geolocation/v1/geolocate?
key=AIzaSyCOMzDSyP4RkXwp7mSiFiuAZroyrazU5eM";
var lat, lon;
var x= document.getElementById("geoLocal");
var tempX= document.getElementById("temp");
var geoLocal=document.getElementById("geo");
var xLat= document.getElementById("lat");
// Following functions will get the latitude and longitude
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
geoLocal.innerHTML = "Geolocation is not supported by this
browser.";
}
}
var finalLat=finalCoords[0];
var finalLon=finalCoords[1];
function showPosition(position){
geoLocal.innerHTML="Latitude:" + position.coords.latitude +
"<br> Longitude: " + position.coords.longitude;
lat= position.coords.latitude;
lon=position.coords.longitude;
var finalCoords=[lat,lon]
return finalCoords;
}
showPosition(position);
console.log(api,lon);
xLat.innerHTML="testLat: " + finalCoords[0];
finalLat=finalCoords[0];
finalLon=finalCoords[1];
function getWeather(finalLat,finalLon){
var completeApi=api+lon+"&"+lat;
// lon="lon="+ position.coords.longitude;
// lat='lat='+ position.coords.latitude;
xLat.innerHTML="testLatitude: " +completeApi;
return completeApi;
}
getWeather(finalLat,finalLon);
The commented information below is the additional work I am going to be using to complete outputting the weather for any user location.
// var completeApi="getWeather(lat,lon)";
// JSON request for API to get temperature
// var ourRequest= new XMLHttpRequest();
// ourRequest.open('GET',completeApi);
// ourRequest.onload= function() {
// if (ourRequest.status>= 200 && ourRequest.status<400){
// var ourData= JSON.parse(ourRequest.responseText);
// renderHTML(ourData);
// console.log("ourData",ourData);
// } else{
// console.log("Connection Error, Please try again.")
// }
// };
// ourRequest.send();
// console.log(ourRequest)
// var jsonWeather= JSON.stringify(ourData);
// document.body.innerHTML=jsonWeather;
// function renderHTML(data){
// var htmlString="";
// for (i=0;i<data.lenth;i++){
// htmlString=data[i].coord;
// console.log(data[i].coord)
// tempX.textContent= data;
// }
// // htmlString.textContent=data[0];
// tempX.textContent= data;
// // return data;
// }
// console.log(ourRequest)
// var geoLocation= document.getElementById("geoAPI");
// geoLocation.innerHTML=completeApi;
The geolocation API is an asynchronous operation. It would be best to implement this usecase using Promises (if available ) or the callback pattern.
Basically the following asynchronous operations need to happen in order:
Get the current location using geolocation API
Get the weather data using an AJAX request
Make whatever DOM updates necessary to show the results
Sample Implementation using the callback pattern:
// Helper to get the location from the browser
function getLocation(cb) {
cb = (cb && typeof cb === 'function' && cb) || function() {};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(pos) {
cb(null, [pos.coords.latitude, pos.coords.longitude]);
});
} else {
cb(new Error('Browser does not support geolocation'));
}
}
// Helper to make the AJAX call to the API
function getWeather(coords, cb) {
cb = (cb && typeof cb === 'function' && cb) || function() {};
// Build URL
var url = 'https://fcc-weather-api.glitch.me/api/current?lat=' + coords[0] + '&lon=' + coords[1];
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// TODO: Handle error cases
if (this.readyState == 4 && this.status == 200) {
// TODO: Handle possible parse exception
cb(null, JSON.parse(xhttp.responseText));
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
// This gets triggered on clicking the button
function handleClick() {
//1. Get the current location using geolocation API
getLocation(function(err, coords) {
if (err) {
// Handle error, return early
return;
}
// 2. Get the weather data using an AJAX request
getWeather(coords, function(err, data) {
if (err) {
// Handle error, return early
return;
}
// Data is available here. Update DOM/process as needed
// 3. Make whatever DOM updates necessary to show the results
console.log(data);
});
});
}
<button onclick="handleClick()">Get Weather Data</button>
I'm having trouble with a weather API call which returns JSON based on geoLocation. The browser asks the question allow/deny access to location and then I want the API call to happen, preferably on page load. I have put the call behind a button click instead but it still doesn't update the page with the local weather. However, if I step through the code using the debugger it works properly.
Javascript:
$(document).ready(function () {
var curLatitude = 'x';
var curLongditude = 'y';
var weatherApi = 'http://api.openweathermap.org/data/2.5/weather?q=London,GB&APPID=[insert-registered-api-key]';
// check for Geolocation support
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
curLatitude = position.coords.latitude;
curLongditude = position.coords.longitude;
if (curLatitude !== 'x' && curLongditude !== 'y') {
weatherApi = 'http://api.openweathermap.org/data/2.5/weather?lat=' + curLatitude +
'&lon=' + curLongditude + '&APPID=[insert-registered-api-key]';
};
loadWeather(weatherApi);
}, function() {
console.log('FAILED');
} );
} else {
console.log('No geoLoc');
// no geo location support - just load London weather
loadWeather(weatherApi);
};
$('#btnLocal').click(function () {
$(".message").html('clicked');
loadWeather(weatherApi);
});
function loadWeather(weatherApiUri) {
var current = "";
var ok;
var ret = $.getJSON(weatherApiUri, function(jsonres) {
console.log( "JSON Data: loaded" );
current = 'called api';
console.log(current);
$(".message").html(current);
}).done(function() {
console.log( "done" );
}).fail(function() {
console.log( "error" );
}).always(function() {
console.log( "complete" );
});
var weatherReturned = {id:0 , main:"weather", description:"weather detail", icon:"code" };
weatherReturned = ret.responseJSON.weather;
$(".message").html(ret.responseJSON.name + ', ' + weatherReturned[0].description);
};
});
JSON response:
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":500,"main":"Rain","description":"light rain","icon"
:"10d"}],"base":"cmc stations","main":{"temp":290.673,"pressure":1009.48,"humidity":83,"temp_min":290
.673,"temp_max":290.673,"sea_level":1019.21,"grnd_level":1009.48},"wind":{"speed":4.3,"deg":93.0027}
,"rain":{"3h":0.1375},"clouds":{"all":92},"dt":1462884891,"sys":{"message":0.0043,"country":"GB","sunrise"
:1462853704,"sunset":1462909185},"id":2643743,"name":"London","cod":200}
What you can do is to set a timer with call setInterval function.
In timer function you can check a flag you will set after navigator.geolocation check pass.
Only in interval function you will put the logic.
Just don't forget to clear timer to avoid unwanted calls.
Code can be like this:
var timer = setInterval(function(){
if(geoReady){
// clear interval
window.clearInterval(timer);
// do your logic
}, 300
}
if (navigator.geolocation) {
geoReady = true;
}
else {
// clear interval
window.clearInterval(timer);
}
I'm looking for a way to trigger user geolocation navigator function from another function mapInit(). It nearly works, but I can't have a proper callback of getCurrentPosition() to confirm it went well.. it return undefined each times.
My geolocation object will have to achieve other tasks so I don't want it to trigger mapInit(). It should have to get user location, record it and return trueor false.. Any guess?
Thanks :)
// Get user current position, return true or false
//
var geolocation = {
get: function() {
if (alert(navigator.geolocation.getCurrentPosition(this.success, this.error, {
enableHighAccuracy: true,
maximumAge: 5000
})) {
return true;
} else {
return false;
}
},
success: function(position) {
this.last = position; // record last position
return true;
},
error: function() {
alert('code: ' + error.code + 'n' + 'message: ' + error.message + 'n')
return false;
},
last: undefined,
}
// Initialize leaflet map and get user location if coords are undefined
//
var mapInit = function(latitude, longitude) {
if (!latitude && !longitude) { // if no latlng is specified, try to get user coords
if (geolocation.get()) {
latitude = geolocation.last.coords.latitude;
longitude = geolocation.last.coords.longitude;
} else {
alert('oups!');
}
}
var map = L.map('map').setView([latitude, longitude], 15);
L.tileLayer('http://{s}.tile.cloudmade.com/#APIKEY#/68183/256/{z}/{x}/{y}.png', {
minZoom: 13,
maxZoom: 16,
}).addTo(map);
var marker = L.marker([latitude, longitude]).addTo(map);
}
Not sure I understand what you're trying to do but when you call "getCurrentPosition" the first argument you pass is a method that will be called with the Position once it is retrieved. As you said in your comment getCurrentPosition will always return immediately but the callback method will be called if the user position can be retrieved (it may never be called):
navigator.geolocation.getCurrentPosition( function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
//do something like recent the Map
});
You will need to create the Leaflet Map first with some default coordinates and then recenter the map with the coordinates provided to the callback method.
I'm new to Javascript and I'm trying to eventually make something that will get the users location in using the getLocation API with HTML5, and use simpleGeo to get the building of the coordinates.
So far I'm trying to get SimpleGeo working and I have this:
var client = new simplegeo.ContextClient('YUpXKUcaTr2ZE5T5vkhaDRAXWbDbaZts');
function displayData(err, data) {
if (err) {
console.error(err);
} else {
console.log(JSON.stringify(data));
}
}
client.getLocation({enableHighAccuracy: true}, function(err, position) {
if (err) {
// Could not retrieve location information. Check err for more information
} else {
// Latitude and longitude available in position.coords
var lat = position.coords.latitude;
var lon = position.coords.longitude;
$('#header').html('<p>your latitude is: ' + lat + '. And your longitude is: ' + lon + '.</p>');
}
});
client.getNearbyAddress(37.765850, -122.437094), function(err, position) {
if (err) {
$('#header').html('<p>Sorry we couldn't locate an address.</p>)
} else {
$('#header').html('<p>Your Street number is ' + street_number + '</p>');
}
});
However this says unexpected identifier in the JS console in Chrome. Any help would be appreciated. :)
I am actually the Developer Advocate # SimpleGeo. Your function displayData doesn't look like it is doing anything. Also var street_number isn't defined. Are you looking to get the user's address?
Here is an example that returns the user's neighborhood:
<script type="text/javascript">
var client = new simplegeo.ContextClient('YOUR_JSONP_TOKEN');
$(document).ready(function() {
client.getLocation({enableHighAccuracy: true}, function(err, position) {
// get the user's context for the found location
client.getContext(position.coords.latitude, position.coords.longitude,
function(err, data) {
if (err)
(typeof console == "undefined") ? alert(err) : console.error(err);
else {
for (var i = 0, ii = data.features.length; i < ii ; i++) {
// switch on the category
switch(data.features[i]["classifiers"][0]["category"]) {
// Return the Neighborhood as an example
case "Neighborhood":
$("#neighborhood").val(data.features[i]["name"]);
break;
}
}
}
});
});
});
</script>