Get current position with jquery ui map (gmap) - javascript

I'm upgrading an old hybrid application. Now I have the latest versions of jQuery (1.7 -> 2.2.4) and jQuery Mobile (1.1 -> 1.4.5), and I use too Jquery Migrate (1.4.1).
This app contains a page with a map created with jquery-ui-map and I'm testing the app with PhoneGap.
In this page, I have a button and I would like to get current position of user.
I use this code:
$('#button-getcurrentposition').click(function(){
$('#map-canvas').gmap('getCurrentPosition', function(position, status) {
alert("I'm here");
if ( status === 'OK' ) {
var clientPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$('#map-canvas').gmap('option','center', clientPosition);
}
});
});
but the alert "I'm here" never displays and I don't know why, so I can not have the current position of the user.
I have included jquery.ui.map.extensions.js, jquery.ui.map.overlays.js and jquery.ui.map.services.js. I have the same problem with the web app version and the apk or ipa.Is there someone with the same problem? Does anyone know why the alert "I'm here" doesn't display? Is the function "getCurrentPosition" deprecated with the latest version of jquery or cordova? Thank you so much

$('#button-getcurrentposition').click(function(){
$('#map-canvas').gmap('getCurrentPosition', function(status, position) {
alert("I'm here");
if ( status === 'OK' ) {
var clientPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$('#map-canvas').gmap('option','center', clientPosition);
}
}, { timeout: 4000, enableHighAccuracy: true });
});
I believe these after parts are required and you have the variables in the function the wrong way around according to the docs.

Related

bindRows is not a function

I am trying to bind data from NWGW to an existing javascript table for Input value help using getTable().bindRows.
Development tool is WebIDE, All connections are checked. All oData services are OK and providing Live Data, metadata OK.
But I keep getting
Uncaught TypeError: oValueHelpDialog.getTable(...).bindRows is not a
function.
This only happens if the app is running on a small screen device (phone or if I choose phone layout in Chrome Dev Tool).
I don't know if it is because it can get the odata to bind to the table? Does phone handle UI5 differently?
I would appreciate any help. Thanks
-------Update-------
Thank to a nice guy in Answer.SAP. Here is the sample project
Step to reproduce the error:
Import the project to Web IDE
Execute the index.html
Open Chrome Dev Tool
Choose device: iPhone 6/7/8 or whatever phone
Refresh (F5) the app
Click on Value Help Dialog again > lead to a blank table
-------Update END-------
Fragment view
var oValueHelpDialog = new sap.ui.comp.valuehelpdialog.ValueHelpDialog({
title : oController.getStrTextSite(),
supportMultiselect : false,
supportRanges : false,
supportRangesOnly : false,
key : oController.getStrWERKS(),
descriptionKey : oController.getStrNAME1(),
ok: function(oControlEvent) {
oController.setDefaultSiteFromHelp(oControlEvent);
oValueHelpDialog.close();
},
cancel: function(oControlEvent) {
oValueHelpDialog.close();
},
afterClose: function() {
oValueHelpDialog.destroy();
}
});
...
return oValueHelpDialog;
}
Controller
onValueHelpForDefaultSite : function(oEvent) {
var oValueHelpDialog = this.getFragmentForValueHelp();
oValueHelpDialog.open();
...
oValueHelpDialog.getTable().bindRows(
this.getEntitySet(
"ODATA_10_DEFAULT_SITE_SET",
"ODATA_10"
)
);
}
Turns out that in mobile, function bindRows() does not exist so we have to replace it with function bindItems()

Return value from a function on Cordova plugin

[EDIT]
In the end, I gave up on this and just did some fallbacks like this:
Try to get the city, etc with a Geolocator script (https://github.com/onury/geolocator);
if it worked, great. If it returns an error that's NOT part of the HTML5 spec, try again using pure HTML5 Geolocation (diveintohtml5.info/geolocation.html);
If it worked, now I have at least the Latitude/Longitude coords. If it returns an error then most likely there's no GPS on the device.
I'm trying to use a Cordova plugin that checks if the GPS on the device is ON/OFF. The plugin in question is http://plugins.cordova.io/#/package/sk.tamex.locationandsettings.
Never mind the typos on the 'how-to'. Where there's telephonenumber it should be locationandsettings.
Anyways, I have a service to handle all the GPS stuff on my app, and it goes like this:
var isCordovaApp = !!window.cordova;
app.service('gpsSrvc', ['$interval', '$timeout', function($interval, $timeout) {
...some stuff...
if (isCordovaApp) {
var locationAndSettings = cordova.require("cordova/plugin/locationandsettings");
}
// Check for GPS on device
self.isGpsEnabled = function(callback) {
if (isCordovaApp) {
locationAndSettings.isGpsEnabled(function(result) {
if (result == true) {
console.log("GPS location ENABLED");
callback(true);
} else {
console.log("GPS location DISABLED");
callback(false);
}
}, function() {
console.log("Error checking for GPS on device");
return false;
});
} else {
return true ;
}
}
...some other stuff...
}]);
Now, when I run that on the browser, self.isGpsEnabled() returns TRUE, as expected.
When I try to run that on my phone, it displays various errors on the console, like this:
Error in Success callbackId: LocationAndSettings1329123004 : TypeError: undefined is not a function (cordova.js:305)
...and I can't make it work.
I also tried to use locationAndSettings.isGpsEnabled(function(result, callback){}) and the same happens. I just don't know how can I pass the result of locationAndSettings.isGpsEnabled() to self.isGpsEnabled().
Any help would be much appreciated.
In the end, I gave up on this and just did some fallbacks like this:
Try to get the city, etc with a Geolocator script (https://github.com/onury/geolocator);
if it worked, great. If it returns an error that's NOT part of the HTML5 spec, try again using pure HTML5 Geolocation (diveintohtml5.info/geolocation.html);
If it worked, now I have at least the Latitude/Longitude coords. If it returns an error then most likely there's no GPS on the device.

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 !

Geolocation Error Detection

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.

Get GPS location from the web browser

I am developing a mobile based web-site, there I have integrated Google Maps, I need to fill the 'From' field of Google Maps dynamically.
Is it possible to get the GPS location from web browser and fill it up in the 'From' field of a Google Map dynamically?
If you use the Geolocation API, it would be as simple as using the following code.
navigator.geolocation.getCurrentPosition(function(location) {
console.log(location.coords.latitude);
console.log(location.coords.longitude);
console.log(location.coords.accuracy);
});
You may also be able to use Google's Client Location API.
This issue has been discussed in Is it possible to detect a mobile browser's GPS location? and Get position data from mobile browser. You can find more information there.
To give a bit more specific answer. HTML5 allows you to get the geo coordinates, and it does a pretty decent job. Overall the browser support for geolocation is pretty good, all major browsers except ie7 and ie8 (and opera mini). IE9 does the job but is the worst performer. Checkout caniuse.com:
http://caniuse.com/#search=geol
Also you need the approval of your user to access their location, so make sure you check for this and give some decent instructions in case it's turned off. Especially for Iphone turning permissions on for Safari is a bit cumbersome.
Use this, and you will find all informations at http://www.w3schools.com/html/html5_geolocation.asp
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
There is the GeoLocation API, but browser support is rather thin on the ground at present. Most sites that care about such things use a GeoIP database (with the usual provisos about the inaccuracy of such a system). You could also look at third party services requiring user cooperation such as FireEagle.
Observable
/*
function geo_success(position) {
do_something(position.coords.latitude, position.coords.longitude);
}
function geo_error() {
alert("Sorry, no position available.");
}
var geo_options = {
enableHighAccuracy: true,
maximumAge : 30000,
timeout : 27000
};
var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
*/
getLocation(): Observable<Position> {
return Observable.create((observer) => {
const watchID = navigator.geolocation.watchPosition((position: Position) => {
observer.next(position);
});
return () => {
navigator.geolocation.clearWatch(watchID);
};
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
Let's use the latest fat arrow functions:
navigator.geolocation.getCurrentPosition((loc) => {
console.log('The location in lat lon format is: [', loc.coords.latitude, ',', loc.coords.longitude, ']');
})

Categories

Resources