How do I pull data from an API in javascript? - javascript

I'm working on a little weather app project, but now that i've changed the code to make the long and lat change depending on you geo location, the button doesn't work. When i click it nothing happens, i can't even tell if the API is pulling the data. Here is my code as well as a codepen I made to fool around with.
http://codepen.io/lettda/pen/yaGaLx
$(document).ready(function(){
$("#reveal").on("click", function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
var long;
var lat;
var api = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&appid=de61ccfbde0405f57d64dbb53323fccf";
$.getJSON(api, function(data){
$(".message").html(JSON.stringify(data))
});
});
};
});
});

open your developer tools (in chrome press F12) and have a look into the console:
pen.js:4 getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://.... for more details.
it's an simple cross origin problem

Related

Getting the user's real position without Client IP on a web page?

I wrote a web page that uses javascript to read the user's location including latitude and longitude and finally post that location to a handler in server (to a RazorPage in asp.net core App).
function getMyLatitude() {
myLat = 0;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
myLat = position.coords.latitude;
})
}
return myLat;
}
This function works correctly.
But some browsers in their desktop version, such as Chrome, have an option by which the user can enter their desired position and from now on, the browser will return the same position as desired by the user.
chrome : developer tools -> settings -> location
Is there a way I can make it so that the user can't manually set their location in the browser, or should I read the user's actual location?

html5 navigator.geolocation.getcurrentposition() returns 0,0

I recently made a web app and part of it looks for the user's location.
function complete(pos) {
var coordinates = pos.coords;
var positions = {lat: coordinates.latitude, lng:
coordinates.longitude};
console.log(positions);
}
function fail(error) {
console.log('failed')
};
var opt = {
enableHighAccuracy: true
};
navigator.geolocation.getCurrentPosition(complete, fail, opt)
But, in some locations like my school, it always returns (0,0) for some reason. It works perfectly fine in other locations, like on private networks.
Can anyone suggest any reasons why or any workaround? Thanks. (I already white listed the site I was using to run this and allowed location_
According to docs navigator.geolocation is not going to be supported in Chrome with http:// (v50.0+). Use https:// instead if that's possible.
That can also cause your issue because you mentioned that only in some places and I guess in some (chrome) browsers it doesn't work.
Note: As of Chrome 50, the Geolocation API will only work on secure
contexts such as HTTPS. If your site is hosted on an non-secure origin
(such as HTTP) the requests to get the users location will no longer
function.

Google HTML 5 Geolocation 'use my location' only working in Firefox

I have a button that is meant to check your location and in return show you the closest locations.
I've got it working perfectly in Firefox, and it wasn't on a live domain before but on a development server and I saw several resources that supported the thought that it had to be on a live domain for html 5 geolocation to work in Chrome.
Now we have moved to the real domain, and still the same results, only Firefox is working and in Chrome and I'm pretty sure Safari it says 'unable to retrieve location' meaning there was an error. I've made sure to check that Chrome isn't blocking the site for requesting my location (no popup comes up to click yes/no) although it is definitely activated in my settings. Same result on different PC's.
Any thoughts what could block this? It's on a live domain.
This is my code:
function geoFindMe() {
var output = $('.location-use');
if (!navigator.geolocation){
$(".location-use").html('Geolocation is not supported by your browser');
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>';
//find nearest restaurant location from these lat n long
NearestLoc( latitude, longitude );
};
function error() {
$(".location-use").html('Unable to retrieve your location');
};
$(".location-use").html('Locating...');
navigator.geolocation.getCurrentPosition(success, error);
}
https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only
This answer is here (thanks user3186314), Chrome requires HTTPS

Same code in Codepen giving different results

I have this pen: https://codepen.io/dteiml/full/PNMwZo with the following javascript code:
$('#getWeather').on('click', function() {
navigator.geolocation.getCurrentPosition(success);
function success(pos){
// get longitude and latitude from the position object passed in
var lng = pos.coords.longitude;
var lat = pos.coords.latitude;
// and presto, we have the device's location!
console.log("test");
$('body').html('You appear to be at longitude: ' + lng + ' and latitude: ' + lat);
}
});
and html code:
<button id="getWeather">
Get my location
</button>
<body>
</body>
that I forked from somebody that works and one that I created myself http://codepen.io/dteiml/full/aNevrE with the same exact code and settings that doesn't work. What might be the problem?
Had you checked the error console, it would have explained exactly what the difference is:
https vs http
pen.js:3 getCurrentPosition() and watchPosition() are deprecated on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See [redacted] for more details.
(Sorry for the redated, I couldn't post the answer exactly as given because of the link.)
You have to use https:// instead of http:// google dont accept request from http protocol.
Switch your codepen to https://codepen.io/dteiml/full/aNevrE and it should work.
Here is the warning:
getCurrentPosition() and watchPosition() are deprecated on insecure
origins. To use this feature, you should consider switching your
application to a secure origin, such as HTTPS.
code

Bing maps api works on pc but not mobile web app

I really hope someone can help with my problem. I have built a mobile web app http://ufa-ld-qa.azurewebsites.net/ (the QA site) with asp.net mvc4 using Bing Maps API for various functionality in the app. I am having problems with the directions module. When I view the site on my pc (Chrome and IE) it works fine and I see no errors but on mobile devices it is not working (but it did work fine yesterday when we launched to QA). I have used HTML5 geolocation (this may be the issue) to get user's location to allow them to get directions to a location. I will post my code below and if anyone could please help me it would be greatly appreciated. We have tested it on about 7 different mobile devices with different OS's and it doesn't work on any. Does anyone know if this is a Bing issue or my code below? Thanks so much in advance.
<script type="text/javascript">
var map = null;
var directionsManager = null;
var userLat = null;
var userLong = null;
var userPosition = null;
var latlng = new Microsoft.Maps.Location(#Model.latitude, #Model.longitude);
navigator.geolocation.getCurrentPosition(locationHandler);
function locationHandler(position)
{
userPosition = new Microsoft.Maps.Location(position.coords.latitude, position.coords.longitude);
}
function GetMap() {
// Initialize the map
map = new Microsoft.Maps.Map(document.getElementById("map"), { credentials: "Au_7giL-8dUbFkJ8zLjcQKy4dV2ftPfpMxQ0_sVBksoj4Y-1nBT00Z1oqUIU894_",
mapTypeId: Microsoft.Maps.MapTypeId.road});
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
}
function directionsModuleLoaded() {
// Initialize the DirectionsManager
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
// Create start and end waypoints
var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: userPosition });
var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: latlng });
directionsManager.addWaypoint(startWaypoint);
directionsManager.addWaypoint(endWaypoint);
// Set request options
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
// Set the render options
directionsManager.setRenderOptions({
itineraryContainer: document.getElementById('directionPanel'),
displayWalkingWarning: false,
walkingPolylineOptions: { strokeColor: new Microsoft.Maps.Color(200, 0, 255, 0) },
});
// Specify a handler for when an error occurs
Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
// Calculate directions, which displays a route on the map
directionsManager.calculateDirections();
}
function displayError(e) {
// Display the error message
alert(e.message);
}
</script>
A couple of things to try. First ensure that your app is allowed to access the users location. Most mobile platforms require you to mark that the app requires access to the GPS in the manifest. Another thing to look into is the possibility that the userLocation isn't populated before your callback for the directions manager is called. It's possible that the GPS takes a little longer on the mobile device to find the users location and as such the directions loaded function is firing before the users location is set, thus passing in a null starting . You might find it useful to have a flag to indicate that the directions manager has loaded and a simple function that runs after setting the flag and also runs after setting the use location that checks that both the directions manager has loaded and the user location has been set and then calls your directions loaded function.
My Windows Phone 8 App is experiencing similar behavior. (Nokia 920)
http://bing.com/maps/default.aspx?cp=47.677797~-122.122013&lvl=12
When the Website preference is set to 'desktop version' the map renders correctly.
When the Website preference is set to 'mobile version' the map renders incorrectly.
Just started happening about a week ago !

Categories

Resources