W3C Geolocation API not working in Chrome - javascript

The below code works in Firefox but not in Google Chrome:
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<script type="text/javascript">
var successCallback = function(data) {
console.log('latitude: ' + data.coords.latitude + ' longitude: ' + data.coords.longitude);
};
var failureCallback = function() {
console.log('location failure :(');
};
var logLocation = function() {
//determine if the handset has client side geo location capabilities
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(successCallback, failureCallback);
}
else{
alert("Functionality not available");
}
};
logLocation();
setTimeout(logLocation, 5000);
</script>
</head>
<body>
<p>Testing</p>
<body>
</html>
What's going on? I thought Google Chrome was supposed to support the W3C Geolocation API.

Works perfectly for me - with both Chrome 11 and Firefox 4.0.1 on Win 7
Make sure you've not disabled location tracking in Chrome: Options > Under the Hood > Content Settings > Location
Because of security restrictions, resources loaded with the file:/// scheme are not allowed access to location. See HTML 5 Geo Location Prompt in Chrome.

If your domain is insecure (e.g. HTTP rather than HTTPS) then you are not allowed access to location in Chrome. This is since Chrome version 50 (12PM PST April 20 2016).
See https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only for details.

in 2017 :
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.
Geolocation API Removed from Unsecured Origins in Chrome 50

It works fine for me - with both Chrome 11 and Firefox 4.0.1 on Win 7
Make sure you've not disabled location tracking in Chrome: Options > Under the Hood > Content Settings > Location please allow the permission
and after checking the permission please run it
after running either it will be sucesscallback or else it comes to errorcallback
function sucesscallback (position)
{
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 15,
center: userLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapObject = new google.maps.Map(document.getElementById("googleMap"), myOptions);
var marker = new google.maps.Marker({
map: mapObject,
position: userLatLng
});
}
function failureCallback(error) {
switch (error.code) {
case 1:
alert("User denied the request for Geolocation.");
break;
case 2:
alert("Location information is unavailable. Please ensure Location is On");
break;
case 3:
alert("timeout");
break;
case 4:
alert("An unknown error occurred.");
break;
}
}
<div id='googleMap' style='width:300px;height:300px;'>
</div>

The Geolocation API lets you discover, with the user's consent, the user's location. You can use this functionality for things like guiding a user to their destination and geo-tagging user-created content; for example, marking where a photo was taken.
The Geolocation API also lets you see where the user is and keep tabs on them as they move around, always with the user's consent (and only while the page is open). This creates a lot of interesting use cases, such as integrating with backend systems to prepare an order for collection if the user is close by.
You need to be aware of many things when using the Geolocation API. This guide walks you through the common use cases and solutions.
https://developers.google.com/web/fundamentals/native-hardware/user-location/?hl=en

Related

Sorry, we have no imagery here - Google Satellite Map

I am using Google Satellite map on an application. It was working fine and suddenly the map images start not showing. Instead of the terrain images, the map is showing the message "Sorry, we have no imagery here".
It is happening on my office IP and other testers' IPs. If I access from another IP or mobile data it works and shown the satellite images. I am not sure if google blocks IPs in case of continuous access on the maps.
Also I am able to see a lot of errors accessing the images
While clicking on the links for loading images, I am getting an error page like below instead of the map tile image.
Any clues on this issue is appreciated
To avoid showing these errors, in case they are due to the use of a zoom level that is too high for the area you are viewing, you can use the MaxZoomService. Kindly note that the below code snippet doesn't work because apparently access to the service without an API key is not possible.
Copy the code and test it with a working API key.
var map, maxZoomService;
function initialize() {
maxZoomService = new google.maps.MaxZoomService();
var myLatLng = new google.maps.LatLng(0, 0);
var mapOptions = {
zoom: 15,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
google.maps.event.addListenerOnce(map, 'idle', function() {
checkZoom();
});
google.maps.event.addListener(map, 'zoom_changed', function() {
checkZoom();
});
}
function checkZoom() {
let zoom = map.getZoom();
maxZoomService.getMaxZoomAtLatLng(map.getCenter(), function(response) {
if (response.status !== 'OK') {
alert('maxZoomService error: ' + response.status);
document.getElementById('max-zoom').innerHTML = 'n/a';
document.getElementById('max-zoom-service').innerHTML = response.status;
} else {
if (response.zoom < zoom) {
map.setZoom(response.zoom);
document.getElementById('max-zoom').innerHTML = response.zoom;
document.getElementById('max-zoom-service').innerHTML = response.status;
}
}
document.getElementById('curr-zoom').innerHTML = map.getZoom();
});
}
initialize();
#map-canvas {
height: 130px;
}
span {
font-weight: bold;
}
<div id="map-canvas"></div>
Current Zoom Level: <span id="curr-zoom"></span><br>
Max Zoom Level: <span id="max-zoom"></span><br>
Max Zoom Service Status: <span id="max-zoom-service"></span>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
If the zoom level is not the issue, make sure that you are using a valid API key. In any case, it might be worth creating a new key and trying again with that one. If that still doesn't work, I would try to contact Google directly with more information as it might be that your network IP or IP range was banned by Google for some reason.
I know this is an old question but, I recently got this error too. So, the problem, in my case was the version of the API script I was using.
I'm answering this because I didn't found this solution over here, so, just in case someone was getting the same error.
Just adding v=3.35 (version number) to the url and it works.
Example: https://maps.googleapis.com/maps/api/js?v=3.35&key=API_KEY...
They explain here:
https://developers.google.com/maps/documentation/javascript/versions#an-update-affected-my-application
Thank you for all the response and I was able to find and fix the real issue. Adding the details here for reference.
I have contacted Google support with the request details and they were able to figure out the exact problem. The reason is their image servers are blocking the request from this project (hybrid mobile project - Android) since it found out that there are invalid request is also coming from the project. The invalid request is referred to as the requests without proper header information.
Based on that information, I could find out that a caching mechanism in the project was trying to cache the images and that is which sends the invalid requests. Adding proper header to that cache mechanism solved the issue forever.

navigator.geolocation.getCurrentPosition/watchPosition is not working in android 6.0

Here is my javascript code :
function getLocation() {
//navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:30000, enableHighAccuracy:true});
var mobile =jQuery.browser.mobile;
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if(mobile){
watchLocation(function(coords) {
var latlon = coords.latitude + ',' + coords.longitude;
//some stuff
}, function() {
alert("error");
});
} else {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("error");
}
}
}
function watchLocation(successCallback, errorCallback) {
successCallback = successCallback || function(){};
errorCallback = errorCallback || function(){};
// Try HTML5-spec geolocation.
var geolocation = navigator.geolocation;
if (geolocation) {
// We have a real geolocation service.
try {
function handleSuccess(position) {
alert("position:"+position.coords);
successCallback(position.coords);
}
geolocation.watchPosition(handleSuccess, errorCallback, {
enableHighAccuracy: true,
maximumAge: 5000 // 5 sec.
});
} catch (err) {
errorCallback();
}
} else {
errorCallback();
}
}
I have tried both getCurrentPosition and watchPosition.
It's reaching errorCalback() method when control comes to geolocation.watchPosition line.
I am testing in Motorola G 2nd Gen with Android 6 and Google chrome browser and opera mini.
Update 1: When I put alert in error call back function I got error:1; message:Only Secure origins are allowed(see:link).
navigator.geolocation.getCurrentPosition(showPosition, function(e)
{ alert(e); //alerts error:1; message:Only Secure origins are allowed(see: )
console.error(e);
})
Update 2: With the help from g4s8 I am able to findout that the error is because of insecure URL. i.e only accessing with http instead of https.But then also I bypassed that in browser by clicking advanced button.But it will prompt for Do you want to allow location, which I don't want..is there any way to access location without prompting it?
Your page should be served over https to access geolocation API.
See Geolocation API Removed from Unsecured Origins
Starting with Chrome 50, Chrome no longer supports obtaining the user's location using the HTML5 Geolocation API from pages delivered by non-secure connections
...
It is an important issue as it will directly impact any site that requires use of the geolocation API and is not served over https
To fix this serve your page over https or on localhost.
Thank you...Is there any way to bypass it??
You can try to use some geolocation services, e.g.
geoip2, Geolocation request
how to use them? can you show an example?? from those two can i access user location without knowing them?
GeoIP2 detect you location by ip address. You can obtain country (geoip2.country()) and city (geoip2.city) with js lib:
<script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
Here https://dev.maxmind.com/geoip/geoip2/javascript/ you can find full documentation.
Google maps geolocation is google service, so you need to get api key first. Then you can send POST request with json parameters to https://www.googleapis.com/geolocation/v1/geolocate?key=API_KEY and get the response:
{
"location": {
"lat": 51.0,
"lng": -0.1
},
"accuracy": 1200.4
}
where location is the user’s estimated latitude and longitude, in degrees,
and accuracy is the accuracy of the estimated location, in meters.
Full json parameters defenition you can find in "Request body" section here https://developers.google.com/maps/documentation/geolocation/intro#overview
Also you can find useful those answers: getCurrentPosition() and watchPosition() are deprecated on insecure origins
using IP it provides only country and city..??
Yes, only this.
will it provide physical location like how getCurrent Position provides??
No, you can't get physical location, because it can be accessed only via gelocation API, that was restricted in insecure context.
Also you have one more option. You can host only one page (that access geolocation API) on https server, and redirect from this page to your http site with user location in get parameters.
/* https page */
navigator.geolocation.getCurrentPosition(function (result) {
window.location.href = "http://your.site.com/http-page?lat=" + result.latitude + "&long=" + result.longitude;
});

javascript - geolocation not working in codepen

I'm trying to implement a simple weather app in codepen. The app works fine on localhost
It asks for permission to use navigator.geolocation and if accepted it shows the weather,
but on codepen it's not even asking for permission.
here is the link
http://codepen.io/asamolion/pen/BzWLVe
Here is the JS function
function getWeather() {
'use strict';
$('#getWeatherButton').hide();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var url = 'http://api.openweathermap.org/data/2.5/weather?APPID=53ac88144e6ee627ad0ed85277545ff9';
// var url = 'example.js';
var apiCall = url + '&lat=' + position.coords.latitude + '&lon=' + position.coords.longitude;
// window.location.href = apiCall;
$.getJSON(apiCall, function (json) {
setSkycon(parseInt(json.weather[0].id, 10));
$('#location').html(json.name + ', ' + json.sys.country);
var temp = (Math.round((json.main.temp - 273.15) * 100) / 100);
$('#temp').html(temp + '<span id="degree">°</span><span id="FC" onclick="convert()">C</span>');
$('#condition').html(json.weather[0].main);
});
});
}
};
Can anybody tell me why codepen is not asking for permission?
I had this same problem on the same challenge. Simply prepend your codepen with https instead of http and you'll be fine.
Like this:
https://codepen.io/crownedjitter/pen/AXzdvQ
if you want to use this:
navigator.geolocation.getCurrentPosition();
in Chrome.
According to the console in Chrome:
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.
There's more details here: https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins Essentially Chrome only wants to send location information over HTTPS. However, in order to allow developers to test they treat localhost as if it were a secure network. Hope this helps!
Starting with Chrome 50, Chrome stopped supporting geolocation on unsecured protocols.
https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only

Javascript GeoLocation is not working on Chrome

I'm trying to take the geolocation of the User and then do a query.
In Mozilla Firefox it works fine also in Safari.... but in Chrome it doesnt work at all.
window.onload = function(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var latitude = position.coords.latitude,
longitude = position.coords.longitude;
console.log(latitude + " " + longitude);
},handleError);
function handleError(error){
//Handle Errors
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;
}
}
}else{
// container.innerHTML = "Geolocation is not Supported for this browser/OS.";
alert("Geolocation is not Supported for this browser/OS");
}
};
And i get the error 1
User denied the request for Geolocation.
But i haven't denied any request, actually the popup window doesnt come up at all.
I've went to Chrome Settings > Show advanced > Privacy > Content Settings > Location allow for all.
Restarted chrome and nothing happened. I'm sure my code is 100% legit so does anyone know how to deal with it?
Thanks!
Ok this was quite easy... Chrome since 20 of April 2016 has disabled the Geolocation API for insecure websites (without https)... link here
https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only
So dont worry..
The easiest way is to click on the area left to the address bar and change location settings there. It allows to set location options even for file:/// and all other types
If you are using chrome, please have a look at the answer below:
HTML 5 Geo Location Prompt in Chrome

Geolocation doesn't work with cordova

I'm currently working on a mobile application with Intel XDK (In background it's Cordova finally, that's why I put Cordova in title.)
With an Ajax request, I get some adresses and with these adresses I want to calculate the distance between them and the current position of user.
So, I get adresses, I convert them and I make the difference.
But actually, nothing is working !
function codeAddress(id, addresse) {
geocoder.geocode( { 'address': addresse}, function(results, status) {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function(){}, 100);
}
console.log(id);
console.log(addresse);
//document.addEventListener("intel.xdk.device.ready",function(){
if (navigator.geolocation)
{
if (status == google.maps.GeocoderStatus.OK)
{
navigator.geolocation.getCurrentPosition(function(position) {
addressEvent = results[0].geometry.location;
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var position = new google.maps.LatLng(pos.lat, pos.lng)
var resultat = google.maps.geometry.spherical.computeDistanceBetween(addressEvent, position);
console.log(resultat);
console.log(addressEvent);
console.log(pos);
console.log(position);
var convert = Math.floor(resultat);
var finalConvert = convert + " m";
var distance = document.createElement('span');
distance.innerHTML = finalConvert;
distance.className = "geo";
document.getElementsByClassName('meta-info-geo')[id].appendChild(distance);
}, function() {
handleLocationError(true, infoWindow);
});
}
}
//},false);
});
}
In the console.log(id), console.log(addresse), I HAVE results !
Actually i'm getting 4 IDs and 4 adresses.
I checked on all the topics I could find on StackOverFlow, and I had normally to add the line in // with the addEventListener but it changes nothing.
Is there someone who knows how to change that ?
ps : Of course, cordova geoloc is in the build and permissions are granted !
EDIT : I'm targeting Android 4.0 min and iOS 5.1.1. I'm using SDK.
EDIT 2 :
Geolocation frequently does not work the way people expect it to work, for a variety of reasons that have been expressed here and here.
You can experiment with geo by using the "Hello, Cordova" sample app that is in the XDK and also available on GitHub. Try using it on a variety of devices to see how things work. Push the "fine" button to initiate a single geo call for a "fine" location and push the "coarse" button to initiate a single geo call for a "coarse" location. Push the "watch" button to initiate a request for a series of geo data points (set to coarse or fine by pushing one of the single buttons first).
The behavior you get in the Emulate tab will be dramatically different than what you get on a real device. The type of device (Android, iOS, etc.) and the version of that device will influence your results; the manufacturer of the device and your location (inside or outside) will influence your results. Do not assume that making a call to the geo APIs will always give you immediate and reliable data, geolocation hardware does not work that way... In fact, you cannot assume that you can even get a valid result! See the two links I pointed to earlier in the post for some reasons why.

Categories