Reputation: 25
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?
Upvotes: 0
Views: 7725
Reputation: 7137
You can use the geolocation object
Check out this MSDN Geolocation Article, or Mozilla
navigator.geolocation
Docs
if ("geolocation" in navigator) {
/* geolocation is available */
} else {
/* geolocation IS NOT available */
}
navigator.geolocation.getCurrentPosition(function(position) {
do_something(position.coords.latitude, position.coords.longitude);
});
var watchID = navigator.geolocation.watchPosition(function(position) {
do_something(position.coords.latitude, position.coords.longitude);
});
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
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:
Hope that helps 😊
Upvotes: 4
Reputation: 713
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.
Upvotes: 1
Reputation: 1360
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);
}
Upvotes: 0
Reputation: 456
you can use geolocation API .. for more details you can refer this https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation
Upvotes: 1