Microsoft Teams Custom Tab Application - geolocation issue - javascript

I created a custom teams application using Microsoft Teams Toolkit for VS Code. I am trying to read the location from the app. I am able to load the coordinates in the Browser and Android version of teams but it fails in the Desktop version of teams with the below error.
Network location provider at 'https://www.googleapis.com/' : No response received.
The function to load the Location-
const getLocation = () => {
let that = this;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
alert('got position');
var positionInfo = "Your current position is (Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude + ")";
alert(positionInfo);
}, (error) => {
alert("Error: " + error.message);
}, { timeout: 30000, enableHighAccuracy: true, maximumAge: 75000 });
} else {
alert("Geolocation is not supported by this browser.");
}
}
It might be a problem with the navigator.geolocation().getCurrentPosition API. Any leads on this will be useful.

I will let this question be here for anyone looking for an answer or if anyone finds an update to this.
I found this official documentation from MSFT that states geolocation API is not fully supported in the teams desktop client currently and they suggest using the getLocation API of TeamsSDK.
https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/device-capabilities/native-device-permissions?tabs=desktop

Related

Best way to get most precise location on mobile with js only

I'm creating a webapp/pwa where I need a precise user location, say under 30-40 meters, I have tried using Radar.io, as well as the geolocation api but still have not been able to get a precise enough location on my iphone on safari. I usually get 60-70 meter accuracy, how would I get more accurate than this? I want the accuracy to be that of the Nike Run Club app for reference.
I have used the Geolocation API many times and it's very precise if you configure it properly.
Here's a snippet I've used in a similar project:
// check if geolocation is supported on this browser
if (navigator.geolocation) {
const timeoutVal = 10 * 1000 * 1000; // set a timeout value for the query
navigator.geolocation.getCurrentPosition(
// what to do if query succeeds
((position) => alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude)),
((error) => {
// what to do if query fails:
const errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]); // print the error
}),
// these 3 parameters are very important, especially the first one
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}

navigator.geolocation.getCurrentPosition(position) getting error "position is not defined" [duplicate]

This question already has an answer here:
Why Geolocation HTML5 getCurrentPosition() is not working on Google Map?
(1 answer)
Closed 4 years ago.
In my application need to get current location, I have tried with below code, I am getting error like position is not defined. The error am getting the API object 'Position' itself is not defined.
try {
if (event.handled !== true) {
event.handled = true;
if (navigator.geolocation) {
var geoOptions = { enableHighAccuracy: true, timeout: 20000 };
navigator.geolocation.getCurrentPosition(function (position) { // geoSuccess
$("#clientPersonalDetailesDiv #longitude").val(position.coords.longitude);
$("#clientPersonalDetailesDiv #latitude").val(position.coords.latitude);
$.hcmobile.hideLoader();
}, function (error) { // geoError
$.hcmobile.hideLoader();
if (error.code == '3') {
$.hcmobile.alertBox("ErrorMessage", "GPS is not available on this device");
}
else {
$.hcmobile.alertBox("ErrorMessage", error.message + 'You must turn on location services to use this feature');
//$.hcmobile.alertBox("ErrorMessage", "You must turn on location services to use this feature");
}
}, geoOptions);
}
}
}
catch (e)
{
}
I am getting error code 1, it says :
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.
I have attached screen shot for more information.
Using this feature only works on secure connections (served over https) as your error already says. Read this for reference.

Bing Maps Geocode Callbacks Don't Get Called

Overall Picture:
I want to add geocoding to my application. I was able to get it working in straight up JavaScript, but the callbacks are not getting triggered after converting to Angular/TypeScript.
Example: if a user enters 1 Microsoft Way, Redmond, WA. The longitude and latitude should be returned: latitude: 47.64006815850735, longitude: -122.12985791265965
Code examples are built off the following resources:
Bing Maps Ajax API - get location from address
https://msdn.microsoft.com/en-us/library/hh868062.aspx
Error Details:
The errors are occurring specifically within the variable name: geocodeRequest. searchModuleLoaded() gets loaded, but my geocodeRequest never triggers geocodeCallback or errCallback. I'm thinking it has something to do with the scope of my methods, but can't seem to isolate what is causing the error. Any ideas on how to get my callbacks to trigger?
Angular/TypeScript (Not Working)
$onInit() {
this.getMap();
}
getMap() {
this.map = new Microsoft.Maps.Map(document.getElementById('myMap'), {credentials: "your key here"});
Microsoft.Maps.loadModule('Microsoft.Maps.Search', { callback: this.searchModuleLoaded });
};
searchModuleLoaded() {
var searchManager = new Microsoft.Maps.Search.SearchManager(this.map);
var geocodeRequest = {
where: "1 Microsoft Way, Redmond, WA",
count: 10,
callback: this.geocodeCallback,
errorCallback: this.errCallback
};
searchManager.geocode(geocodeRequest);
}
geocodeCallback(geocodeResult, userData) {
// this callback never gets triggered
alert("The first geocode result is " + geocodeResult.results[0].location + ".");
}
errCallback(geocodeRequest) {
// this callback never gets triggered
alert("An error occurred.");
}
Working Version (Works, but no Angular/TypeScript)
function GetMap(){
map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials: "key goes here", center: new Microsoft.Maps.Location(47.5, -122.3), zoom: 9 });
Microsoft.Maps.loadModule('Microsoft.Maps.Search', { callback: searchModuleLoaded });
}
function searchModuleLoaded(){
var searchManager = new Microsoft.Maps.Search.SearchManager(map);
var geocodeRequest = {where:"1 Microsoft Way, Redmond, WA", count:10, callback:geocodeCallback, errorCallback:errCallback};
searchManager.geocode(geocodeRequest);
debugger;
}
function geocodeCallback(geocodeResult, userData){
alert("The first geocode result is " + geocodeResult.results[0].location + ".");
}
function errCallback(geocodeRequest){
alert("An error occurred.");
}
After furthing investigation, I was able to resolve my issue.
What was the problem?
The issue was occurring within the searchModuleLoaded. Both callbacks were undefined. One issue is that it was trying to execute searchModuleLoaded before the module had loaded and another issue was caused because it didn't know the context of this.
To fix the issue, I had to modify the callback while loading Microsoft.Maps.Search. The module's callback is now converted to a lambda function, which calls this.searchModuleLoaded(). Once this gets compiled into JavaScript, it sets the this context appropriatly i.e _this = this. My code looks like this now:
getMap() {
this.map = new Microsoft.Maps.Map(document.getElementById('myMap'), {credentials: "put your key here"});
Microsoft.Maps.loadModule('Microsoft.Maps.Search', {
callback: () => {
this.searchModuleLoaded();
}
});
};
searchModuleLoaded() {
var searchManager = new Microsoft.Maps.Search.SearchManager(this.map);
var geocodeRequest = {
where: "1 Microsoft Way, Redmond, WA",
count: 10,
callback: this.geocodeCallback,
errorCallback: this.errCallback
};
searchManager.geocode(geocodeRequest);
};
geocodeCallback(geocodeResult, userData) {
alert("The first geocode result is " + geocodeResult.results[0].location + ".");
};
errCallback(geocodeRequest) {
alert("An error occurred.");
};

Distance tracking and updating google maps in javascript

so i'm currently working on an exercise application for a mobile device that tracks the location of the user while constantly updating the distance they have traveled. I can get the starting location of the user easy enough but its actually tracking them that I have no idea how to even start. I have a button for the user to get the current location called 'location' and i have a button called 'record' that will actually start the tracking process.
I know it has something to do with watchPosition() but im not quite sure how to use it and how to make it work with what i currently have. This is the first time ive done anything that required geoLocation.
Any helped would be much apreciated.
<script>
var c = function(position){
var latitude = position.coords.latitude,
longitude = position.coords.longitude,
acc = accuracy.coords.accuracy,
coords = position+ ', ' + long;
timeStamp = position.timestamp;
document.getElementById('google_map').setAttribute('src', 'https://maps.google.co.uk/?q=' + coords + '&z=50&output=embed');
}
var e = function(error){
switch(error.code){
case 0:
updateStatus("There was an error while retrieving your location: " +
error.message);
break;
case 1:
alert("The user prevented this page from retrieving a location.");
break;
case 2:
updateStatus("The browser was unable to determine your location: " +
error.message);
break;
case 3:
updateStatus("The browser timed out before retrieving the location.");
break;
}
}
document.getElementById('location').onclick = function() {
var watchId = navigator.geolocation.getCurrentPosition(c, e, {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 1000
});
return false;
}
document.getElementById("stop").onclick = function(){
navigator.geolocation.clearWatch(watchId);
}
</script>

How can I detect the visitor's location using JavaScript, and call a JavaScript function on the basis of a certain location? [duplicate]

Closed. This question is not about programming or software development. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 4 months ago.
Improve this question
I'm trying to extend the native geolocation function
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
});
}
so that I can use the visitor's country name (perhaps return an informative array).
So far all I've been able to find are functions that display a google maps interface but none actually gave what I want, except for this library which worked well in this example but for some reason didn't work on my computer. I'm not sure why that went wrong there.
Anyways, do you know how I can simply return an array containing information like country, city, etc. from latitude and longitude values?
You can use my service, http://ipinfo.io, for this. It will give you the client IP, hostname, geolocation information (city, region, country, area code, zip code etc) and network owner. Here's a simple example that logs the city and country:
$.get("https://ipinfo.io", function(response) {
console.log(response.city, response.country);
}, "jsonp");
Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/
The location will generally be less accurate than the native geolocation details, but it doesn't require any user permission.
You don't need to locate the user if you only need their country. You can look their IP address up in any IP-to-location service (like maxmind, ipregistry or ip2location). This will be accurate most of the time.
Here is a client-side example with Ipregistry (disclaimer, I am working for):
fetch('https://api.ipregistry.co/?key=tryout')
.then(function (response) {
return response.json();
})
.then(function (payload) {
console.log(payload.location.country.name + ', ' + payload.location.city);
});
If you really need to get their location, you can get their lat/lng with that method, then query Google's or Yahoo's reverse geocoding service.
You can do this natively wihtout relying on IP services. You can get the user's timezone like this:
Intl.DateTimeFormat().resolvedOptions().timeZone
and then extract the country from that value. Here is a working example on CodePen.
You can use your IP address to get your 'country', 'city', 'isp' etc...
Just use one of the web-services that provide you with a simple api like http://ip-api.com which provide you a JSON service at http://ip-api.com/json. Simple send a Ajax (or Xhr) request and then parse the JSON to get whatever data you need.
var requestUrl = "http://ip-api.com/json";
$.ajax({
url: requestUrl,
type: 'GET',
success: function(json)
{
console.log("My country is: " + json.country);
},
error: function(err)
{
console.log("Request failed, error= " + err);
}
});
See ipdata.co a service I built that is fast and has reliable performance thanks to having 10 global endpoints each able to handle >10,000 requests per second!
This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.
This snippet will return the details of your current ip. To lookup other ip addresses, simply append the ip to the https://api.ipdata.co?api-key=test url eg.
https://api.ipdata.co/1.1.1.1?api-key=test
The API also provides an is_eu field indicating whether the user is in an EU country.
$.get("https://api.ipdata.co?api-key=test", function (response) {
$("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="response"></pre>
Here's the fiddle; https://jsfiddle.net/ipdata/6wtf0q4g/922/
I also wrote this detailed analysis of 8 of the best IP Geolocation APIs.
A very easy to use service is provided by ws.geonames.org. Here's an example URL:
http://ws.geonames.org/countryCode?lat=43.7534932&lng=28.5743187&type=JSON
And here's some (jQuery) code which I've added to your code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$.getJSON('http://ws.geonames.org/countryCode', {
lat: position.coords.latitude,
lng: position.coords.longitude,
type: 'JSON'
}, function(result) {
alert('Country: ' + result.countryName + '\n' + 'Code: ' + result.countryCode);
});
});
}​
Try it on jsfiddle.net ...
A free and easy to use service is provided at Webtechriser (click here to read the article) (called wipmania). This one is a JSONP service and requires plain javascript coding with HTML. It can also be used in JQuery. I modified the code a bit to change the output format and this is what I've used and found to be working: (it's the code of my HTML page)
<html>
<body>
<p id="loc"></p>
<script type="text/javascript">
var a = document.getElementById("loc");
function jsonpCallback(data) {
a.innerHTML = "Latitude: " + data.latitude +
"<br/>Longitude: " + data.longitude +
"<br/>Country: " + data.address.country;
}
</script>
<script src="http://api.wipmania.com/jsonp?callback=jsonpCallback"
type="text/javascript"></script>
</body>
</html>
PLEASE NOTE: This service gets the location of the visitor without prompting the visitor to choose whether to share their location, unlike the HTML 5 geolocation API (the code that you've written). Therefore, privacy is compromised. So, you should make judicial use of this service.
I wanted to localize client side pricing for few countries without using any external api, so I used local Date object to fetch the country using
new Date()).toString().split('(')[1].split(" ")[0]
document.write((new Date()).toString().split('(')[1].split(" ")[0])
Basically this small code snippet extracts the first word from Date object. To check for various time zone, you can change the time of your local machine.
In my case, our service only included three countries, so I was able to get the location using the following code.
const countries = ["India", "Australia", "Singapore"]
const countryTimeZoneCodes = {
"IND": 0,
"IST": 0,
"AUS": 1,
"AES": 1,
"ACS": 1,
"AWS": 1,
"SGT": 2,
"SIN": 2,
"SST": 2
} // Probable three characters from timezone part of Date object
let index = 0
try {
const codeToCheck = (new Date()).toString().split('(')[1].split(" ")[0].toUpperCase().substring(0, 3)
index = countryTimeZoneCodes[codeToCheck]
} catch (e) {
document.write(e)
index = 0
}
document.write(countries[index])
This was just to improve user experience. It's not a full proof solution to detect location. As a fallback for not detecting correctly, I added a dropdown in the menubar for selecting the country.
For developers looking for a full-featured geolocation utility, you can have a look at geolocator.js (I'm the author).
Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.
var options = {
enableHighAccuracy: true,
timeout: 6000,
maximumAge: 0,
desiredAccuracy: 30,
fallbackToIP: true, // if HTML5 geolocation fails or rejected
addressLookup: true, // get detailed address information
timezone: true,
map: "my-map" // this will even create a map for you
};
geolocator.locate(options, function (err, location) {
console.log(err || location);
});
It supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and more...
You can simply import in your app.component.ts or whichever component you want to use
import { HttpClient } from '#angular/common/http';
Then make a simple GET request to http://ip-api.com/json
getIPAddress() {
this.http.get("http://ip-api.com/json").subscribe((res: any) => {
console.log('res ', res);
})
}
You will get the following response by using it:
{
"status": "success",
"country": "country fullname here",
"countryCode": "country shortname here",
"region": "region shortname here",
"regionName": "region fullname here",
"city": "city fullname here",
"zip": "zipcode will be in string",
"lat": "latitude here will be in integer",
"lon": "logitude here will be in integer",
"timezone": "timezone here",
"isp": "internet service provider name here",
"org": "internet service provider organization name here",
"as": "internet service provider name with some code here",
"query": "ip address here"
}
You can use ip-api.io to get visitor's location. It supports IPv6.
As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.
JavaScript Code:
function getIPDetails() {
var ipAddress = document.getElementById("txtIP").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(xhttp.responseText));
}
};
xhttp.open("GET", "http://ip-api.io/json/" + ipAddress, true);
xhttp.send();
}
<input type="text" id="txtIP" placeholder="Enter the ip address" />
<button onclick="getIPDetails()">Get IP Details</button>
jQuery Code:
$(document).ready(function () {
$('#btnGetIpDetail').click(function () {
if ($('#txtIP').val() == '') {
alert('IP address is reqired');
return false;
}
$.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
function (result) {
alert('Country Name: ' + result.country_name)
console.log(result);
});
});
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
<input type="text" id="txtIP" />
<button id="btnGetIpDetail">Get Location of IP</button>
</div>
If you don't want to use an api and only the country is enough for you, you can use topojson and worldatlas.
import { feature } from "https://cdn.skypack.dev/topojson#3.0.2";
import { geoContains, geoCentroid, geoDistance } from "https://cdn.skypack.dev/d3#7.0.0";
async function success(position) {
const topology = await fetch("https://cdn.jsdelivr.net/npm/world-atlas#2/countries-50m.json").then(response => response.json());
const geojson = feature(topology, topology.objects.countries);
const {
longitude,
latitude,
} = position.coords;
const location = geojson.features
.filter(d => geoContains(d, [longitude, latitude]))
.shift();
if (location) {
document.querySelector('#location').innerHTML = `You are in <u>${location.properties.name}</u>`;
}
if (!location) {
const closestCountry = geojson.features
// You could improve the distance calculation so that you get a more accurate result
.map(d => ({ ...d, distance: geoDistance(geoCentroid(d), [longitude, latitude]) }))
.sort((a, b) => a.distance - b.distance)
.splice(0, 5);
if (closestCountry.length > 0) {
const possibleLocations = closestCountry.map(d => d.properties.name);
const suggestLoctions = `${possibleLocations.slice(0, -1).join(', ')} or ${possibleLocations.slice(-1)}`;
document.querySelector('#location').innerHTML = `It's not clear where you are!<section>Looks like you are in ${suggestLoctions}</section>`;
}
if (closestCountry.length === 0) {
error();
}
}
}
function error() {
document.querySelector('#location').innerHTML = 'Sorry, I could not locate you';
};
navigator.geolocation.getCurrentPosition(success, error);
This code takes longitude and latitude and checks if this point is included in one of the geojson's feature (a spatially bounded entity). I created also a working example.

Categories

Resources