Geolocation Error Detection - javascript

I'm using Geolocation but I'm having trouble recognizing errors to be able to offer an alternative.
My HTML looks like this:
<button onclick="getLocation()">Get your location now</button>
<div id="google_canvas"></div>
<p id = 'error'></p>
My script looks like this:
function getLocation(){
if(navigator.geolocation)
{
var map;
var mapOptions =
{
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('google_canvas'), mapOptions);
navigator.geolocation.getCurrentPosition(function(position)
{
var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude),latitude=document.getElementById("latitude"),longitude=document.getElementById("longitude");
var infowindow = new google.maps.InfoWindow(
{
map: map,
position: geolocate,
content:
' * output content within map * '
});
map.setCenter(geolocate);
latitude.value = position.coords.latitude;
longitude.value = position.coords.longitude;
});
}
else
{
document.getElementById('error').innerHTML = 'No Geolocation Support';
}
};
google.maps.event.addListener(map, 'idle', function() {
});
My version of IE9 does not support Geolocation (I've tried their test site with their own script), but it gives me no error or warning, plus if I do not allow location in Firefox or Chrome, I don't get any error or alert either.
Can someone help? If it cannot run, i can offer an alternative so I don't think i need to look through error codes so much, but I do need to be able to detect failure so I can offer my alternative, but the error portion in my script will not run, regardless.
My question really is, why won't this else run?
else
{
document.getElementById('error').innerHTML = 'No Geolocation Support';
}
Thanks

For your error message it will appear if your browser does not support geolocation, to enable disable geolocation on browser that supports it you usually need to take look next to the address bar there should be a small icon that you can use to disable/enable geolocation.
In order for you to detect previous decision weather you enabled/disabled geolocation you can use the solution I suggested in this article :
Is there a way of detecting whether a user has already given permission to use navigator.geolocation?
For IE9 it is working fine, the only thing is you should click Allow blocked cnotent at the bottom of the web page.

Related

How to pass a parameter allow= "geolocation" when embedding Google Apps Script in a Google site?

The target is to embed a Google Apps Script gadget into my Google site. The function of this script is to show a google map, determin the location of the client and center the map to the found location.
The relevant command for getting the position is navigator.geolocation.getCurrentPosition.
The issue is that the security layers block the execution of this command when used with Chrome. (It works in Firefox and Safari. Also when I use "test web for your lates code", it works as intended).
Debugging the browser reveals the following error message:
"Geolocation access has been blocked because of a Feature Policy applied to the current document. See (here comes a link) for more detail."
Following the explanations in the offered link, it results in the suggestion to apply a instruction for geolocation in the iframe command like:
<iframe src="https://example.com" allow="geolocation"></iframe>
Now here comes my problem:
Since I can only use the functions in the Google Site editor to embed a GAS gadget, I have no option to modify an iframe instruction with such a parameter. Therefore, I do not know how I can pass this parameter into the web site.
The question is: Is there a method at all? If yes, what is the correct way to do it?
I have investigated a lot and also tried to add parameters to the doGet function in the sense of:
function doGet() {
return HtmlService.createHtmlOutputFromFile('pmtest')
.setSandboxMode(HtmlService.SandboxMode.IFRAME) .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
But this did not make a change.
Here now my code:
code.gs :
function doGet() { return HtmlService.createHtmlOutputFromFile('pmtest') }
html code (pmtest) :
<!DOCTYPE html>
<html>
<script
src="https://maps.googleapis.com/maps/api/js?key=...here is me key ....&libraries=places&callback=initMap">
</script>
<script>
var myCenter=new google.maps.LatLng(51.158742,6.7170850);
function initialize()
{
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
alert('success');
var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
alert('myLatlng : ' + myLatlng);
myCenter = myLatlng;
CenterMap();
marker.setPosition(myCenter);
}, function(error) {
alert('error');
});
}
var mapProp = {
center: myCenter, zoom:18, gestureHandling: 'greedy', tilt: 0, draggableCursor: 'default',
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker = new google.maps.Marker({ position: myCenter});
marker.setMap(map);
function CenterMap(){ map.panTo(myCenter);}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="googleMap" style="width:1200px;height:700px;"></div>
</body>
</html>
In case you want to open the test page, here is the link:
https://sites.google.com/site/pmtest4711/
When the geolocation command could be executed, a message will appear with "success" and a second with the found position. The google map then shows this location (wherever you are.).
Any good hint would be appreciated.

Google map API in my html website

hello I have a problem I wish to integrate ue google map in my site but I do not understand it appears when I update the page but then it disappears. In the console it says "no APIkey" but I did it several times. I followed the site: developers.google
but I do not understand where the error lies. I put the html part if a person understand the error please ! I also follow this topic google api in my website but nothing appears !
<div id="map"></div>
<script>
function initMap() {
var ff = {
lat: 50.638181,
lng: 3.058227
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: ff
});
var marker = new google.maps.Marker({
position: ff,
map: map
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDWdGA-ndsHMtR5-cdZrc5SHtfKKBG5Bfg&callback=initMap">
</script>
Console says:-
https://developers.google.com/maps/documentation/javascript/error-messages#api-not-activated-map-error
so activate your google map API key under project.
Your API key is not activated. Make sure to generate a new one following the guide: https://developers.google.com/maps/documentation/javascript/get-api-key?hl=de

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 !

safari mobile geolocation and map rendering

I’m attempting to get the users location for a mobile web app, if their browser doesn’t support geolocation then send them to a default map center location. This works fine on Firefox, but when I test it on an iPhone it prompts for location usage then the map does not render. I noticed though once I close safari and reopen it the map then begins to render with the geolocation. Is this a bug in safari or something wrong in the way i am initializing my map?
function init() {
var center = new google.maps.LatLng(42.283151,-87.955098);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var loc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 11,
center: loc,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
new google.maps.Marker({
position: point,
map: map
});
});
}
else {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 15,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
}
Are you waiting long enough for the iPhone's GPS to get a fix on your location? This initial activation of location services can take a while to get an accurate location to return to the API, which explains why the subsequent load works as intended.
It might be worth your while to add some code to indicate that the HTML5 geolocation function is running (perhaps displaying a "Loading..." message after you call getCurrentPosition).
An error callback would be worthwhile as well to catch and gracefully handle and errors that occur during getCurrentPosition. You can definitely run into cases where navigator.geolocation is true but it won't trigger the success function you've defined.

Real time GPS Tracker on JUST HTML / JS and Google Maps to be run on a handphone? Is it possible?

I have read up on GPS Real time tracking and found out several things about it, mostly requiring PHP, zope and a database to store the incoming data. Some other methods uses ajax with relations to PHP.
As regards to my question, is it possible to do so with just html and JS, using markers or anything else to populate the Google Map when you move anywhere in the city? Need some help on this, Thanks!
Yes, it is possible. Most browsers in the latest smartphones have implemented the W3C Geolocation API:
The Geolocation API defines a high-level interface to location information associated only with the device hosting the implementation, such as latitude and longitude. The API itself is agnostic of the underlying location information sources. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs, as well as user input. No guarantee is given that the API returns the device's actual location.
The API is designed to enable both "one-shot" position requests and repeated position updates, as well as the ability to explicitly query the cached positions.
Using the Geolocation API to plot a point on Google Maps, will look something like this:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var point = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: point,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Place a marker
new google.maps.Marker({
position: point,
map: map
});
});
}
else {
alert('W3C Geolocation API is not available');
}
The above will only gather the position once, and will not auto update when you start moving. To handle that, you would need to keep a reference to your marker, periodically call the getCurrentPosition() method, and move the marker to the new coordinates. The code might look something like this:
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = null;
function autoUpdate() {
navigator.geolocation.getCurrentPosition(function(position) {
var newPoint = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map
});
}
// Center the map on the new position
map.setCenter(newPoint);
});
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 5000);
}
autoUpdate();
Now if by tracking you mean that you should also store this information on a server (so that someone else could see you moving from a remote location), then you'd have to send the points to a server-side script using AJAX.
In addition, make sure that the Google Maps API Terms of Use allow this usage, before you engage in such a project.
UPDATE: The W3C Geolocation API exposes a watchPosition() method that can be used instead of the setTimeout() mechanism we used in the above example.

Categories

Resources