I am building a web application based on users current location using javascript/jquery. How to get current location of user when he browse my application on all browsers?
You can use the geolocation object
Check out this MSDN Geolocation Article, or Mozilla navigator.geolocation Docs
1. Check browser compatibility
if ("geolocation" in navigator) {
/* geolocation is available */
} else {
/* geolocation IS NOT available */
}
2. Get Current Position
navigator.geolocation.getCurrentPosition(function(position) {
do_something(position.coords.latitude, position.coords.longitude);
});
3. Watch for Changes
var watchID = navigator.geolocation.watchPosition(function(position) {
do_something(position.coords.latitude, position.coords.longitude);
});
Basic Working Example
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;
}
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
Also, have a look at this example on JSFiddle, by MSDN which is slightly more comprehensive.
Note: Geolocation only works on SSL sites with secure context
Browser Support
You also asked for it to work in all browsers. As with most features this isn't really possible. But you can check whether the users browser supports navigator.geolocation, and display an appropriate message if not.
Check out https://caniuse.com/#search=geolocation to see current browser support for geolocation. But in summary, it's supported on:
IE9+
Edge 13+
FF 3.5+
Safari 5.0+
Chrome 5.0+
Opera 11.5, 12.1, 16.6+
iOS Safari 3.2+
Android default browser for OS versions 2.1+
Hope that helps 😊
you can use geolocation API .. for more details you can refer this
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation
You can use the Geolocation.getCurrentPosition API available in all modern browsers. By using this you can get the user's location via the most optimal way for their device, i.e. via GPS or IP.
I think something like below code can help. You can call getLocation() and it will save the location inside _position variable which can be used later.
var _position;
function getLocation(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
var onSuccess = function(position) {
_position = position;
};
function onError(error) {
alert('Error: ' + error.message);
}
Related
I just found that getCurrentPosition() is deprecated from Google Chrome for insecure origins, they are just allowing HTTPS. But I'm trying to run this html file on my machine which to my knowledge is supposed to be secure.
Example from w3school
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<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>
</body>
</html>
but that doesn't show my current location, if that means that chrome see my local machine as an insecure origin, Is there any way to change that?
Yes there is. According to the documentation you can start the browser with a command line flag or use https for the connection.
The command line flag is for debugging and testing purpose and the https connection is for production use:
chrome --unsafely-treat-insecure-origin-as-secure="http://exmaple.com"
Deprecating Powerful Features on Insecure Origins: https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins
When using html5 geolocation, everything works nicely in the computer browser, but after switching to an iphone I get no error when user has phone settings set to not allow browser to use geolocation, is there any way to trigger error in such situation?
navigator.geolocation.getCurrentPosition(handleSuccess, handleError)
I'm using this code to get current position and my handleError is never triggered
Did you try to validate the object navigator.geolocation ?
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
throw "Geolocation is not supported by this browser.";
}
}
function showPosition() {
// my code
}
getLocation();
I am trying to get location of visitors. I am using google map api. In computer it works fine. But in mobile, if gps service is disabled, browser doesn't ask for permission or dipslay result. When gps service is enabled, browser asks for permission or display result. So, is there a way to access gps service is enabled or disabled via javascript.
If you support HTML5, you might find HTML5 Geolocation useful.
This page contains the following example code:
<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>
My code:
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 +
"<br>More or less" + position.accuracy + "meters";
}
Position.accuracy is 96 meters (which is, to me, surprising enough), but the position itself is spot on. Literally, it hits home. And I always thought laptops only geolocate by IP address, which should offer the accuracy of a couple of miles? What's the source of this precise info?
I believe the original source of the information comes from mobile devices like smartphones. Google and other companies have a database of wireless routers with GPS information. This information can be harvested by mobile devices that have transmitted the location of your wireless router to google in the past. IOS does this as well.
For example. If I walk next to some wireless router with my IOS device it will pick up the wireless router (not fully connecting though) and will note the GPS location and then send this to Apple. Now Apple now knows the location of that wireless router. This is the same for Android devices and Google.
see:
See "HOW IS APPLE COLLECTING GEODATA?" in
http://www.wired.com/2011/04/apple-iphone-tracking/
or, http://www.theguardian.com/technology/blog/2011/apr/25/google-router-map-exposed
http://www.w3schools.com/html/html5_geolocation.asp reference about geoLocation and google map API.]
They are using getCurrentPosition() for fetch the current position of the user and the showPosition() returns longitude and latitude to the users.getCurrentPosition() always give you a precise location.
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, ']');
})