I was using the following code to get my current location. But the longitude and latitude generated was not at all accurate. It was showing a location about 700 Kms away from my location. How can I make it accurate?
<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>
Or you could try a different geocoding provider.
There are lots to choose from:
https://smartystreets.com
http://geocoder.us
http://geoservices.tamu.edu/Services/Geocode/
Disclaimer: I'm a developer at SmartyStreets.
Probably you are not using GPS. If you aren't, then navigator.geolocation.getCurrentPosition returns a position based on your ISP
I have below mentioned JSFidle.But it's not working.Can you say why's that ?
Note: I want to run it on JSFiddle.It should show the Latitude and Longitude.
JSFiddle Geolocation
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;
}
Because you have your JavaScript set to run in the load event (the second drop down on the left). The function getLocation only exists within the scope of that load handler, not in the global scope you're trying to call it from.
It works fine if you change it to 'No wrap - in <body>'
I'm developing html5 windows phone 8 application and I've run into problem: geolocation doesn't work for me. I have WebBrowser.IsGeolocationEnabled property set to true and in app manifest ID_CAP_LOCATION is also checked. Hovewer even with the geolocation code copy-pasted from various HTML5 learning portals I'm still getting an error telling that site doesn't have geolocation permission.
Thanks for any help
var watchId = navigator.geolocation.watchPosition(scrollMap, handleError);
function scrollMap(position) {
myLoc.setLatLng([position.coords.latitude, position.coords.longitude]);
}
function handleError(error) {
myLoc.setLatLng([0, 0]);
}
I had the same issue, but solved it by totally rewriting my code - simplifying it:
var lng, lat;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else { alert("Geolocation is not supported by this browser."); }
}
function showPosition(position) {
alert("Latitude: " + position.coords.latitude +
"\nLongitude: " + position.coords.longitude);
lng = position.coords.longitude;
lat = position.coords.latitude;
}
I have created a site (can be accessed at http://dev.gkr33.com) which is designed for a smartphone and attempts to use the navigator.geolocation api and grab your position via getCurrentPosition. This seems to work initially, however if you try to refresh the page it always brings back the last GPS position. I have added some debug information on the page which grabs the time of the getCurrentPosition return and after the initial positioning it always returns the same time (down to the millisecond).
This only seems to happen in Chrome Mobile. If I browse into the site via the stock Android browser it works fine every time.
The code is shown below;
<script type="text/javascript">
(function ($) {
$(document).ready(function() {
var options = { enableHighAccuracy: true, maximumAge: 0, timeout: 60000 };
var position;
// empty the current html elements, not strictly necessary but
// I'm clutching at straws
$('#debug-latlng').empty();
$('#debug-time').empty();
$('#debug-address').empty();
// Let's try and find out where we are
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(gotPos, gotErr, options );
} else {
gotErr();
}
// We've got our position, let's show map and update user
function gotPos(position) {
var info;
info = position.coords.latitude+','+position.coords.longitude;
$('#debug-latlng').text(info);
$('#debug-time').text(parseTimestamp(position.timestamp));
// the following json call will translate the longitude and
// latitude into an address (a wrapper for google's geocode call)
$.getJSON('http://dev.gkr33.com/api.php', { req: "getLocationInfo", latlng: $('#debug-latlng').text() }, function(json) {
$('#debug-address').text( json['results'][0]['formatted_address'] );
});
var myLatLng = new google.maps.LatLng( position.coords.latitude, position.coords.longitude );
var mapOptions = {
zoom: 12,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatLng,
title: 'You are here',
animation: google.maps.Animation.DROP
});
marker.setMap(map);
} //gotPos
// Trap a GPS error, log it to console and display on site
function gotErr(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
console.log("Error: " + errors[error.code]);
$('#debug-latlng').text('GPS position not available');
} //gotErr
// Make timestamp human readable
function parseTimestamp(timestamp) {
var d = new Date(timestamp);
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var hour = d.getHours();
var mins = d.getMinutes();
var secs = d.getSeconds();
var msec = d.getMilliseconds();
return day + "." + month + "." + year + " " + hour + ":" + mins + ":" + secs + "," + msec;
} // parseTimestamp
});
}) (jQuery);
</script>
I have played around with various values for the maximumAge and timeout, but nothing seems to affect the same position.coords and position.time values.
I think there maybe an issue with Chrome Mobile, but I don't wanna assume too much at this point in time and just need clarification that I haven't made a mistake of muppet-like proportions in my code.
Many thanks for any help you can provide.
UPDATE: I suppose I should have said that I have tested this on two Android devices; HTC One X+ and a Samsung Galaxy Tab 7.7 with the same result. On both the stock browser works fine, and on both Chrome doesn't refresh the position. Will test on an Apple Device later :)
I never got to the bottom of this issue, but I got a way around the problem by utilising the watchPosition call, and wrapping this in a 5 second wait before clearing the watchID. Check the code below:
var options = { enableHighAccuracy: true, maximumAge: 100, timeout: 50000 };
if( navigator.geolocation) {
var watchID = navigator.geolocation.watchPosition( gotPos, gotErr, options );
var timeout = setTimeout( function() { navigator.geolocation.clearWatch( watchID ); }, 5000 );
} else {
gotErr();
}
I haven't played around with the "options" values or the timeout delay at the moment, but the above code brings back accurate positioning info on every platform I've tried.
Hope this helps someone with the same issue :)
I finally found a working version for firefox, chrome & default navigator in android (4.2 tested only):
function getGeoLocation() {
var options = null;
if (navigator.geolocation) {
if (browserChrome) //set this var looking for Chrome un user-agent header
options={enableHighAccuracy: false, maximumAge: 15000, timeout: 30000};
else
options={maximumAge:Infinity, timeout:0};
navigator.geolocation.getCurrentPosition(getGeoLocationCallback,
getGeoLocationErrorCallback,
options);
}
}
getCurrentLocation() no longer works on insecure origins in Chrome browsers. Switch to a secure original (HTTPS) to enable.
How can I save lat and lng values to variables using HTML5 geolocation API?
This is my code, copied from w3schools. How can I save coordinates to variables like var x= position.coords.latitude; and var y= position.coords.longitude; instead of just showing the values like the code is doing right now? I am beginner with javascript so I don't know how to do this
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<script>
var x=document.getElementById("demo");
window.onload = function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.watchPosition(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>
And in my application I need to send values of those variables to server every minute. Would it be better to do the geolocation with watchposition or execute function that does getcurrentposition every minute?
Adding them to variables is as easy as:
var lat = position.coords.latitude;
var lon = position.coords.longitude;
OR as an object:
var coords = {lat: "", lon: ""};
Then to use the object in your code:
function showPosition(position)
{
coords.lat = position.coords.latitude;
coords.lon = position.coords.longitude;
x.innerHTML="Latitude: " + coords.lat +
"<br />Longitude: " + coords.lon;
}
As for sending the variables to a server this depends on what your serverside technology is but you will find many examples on google.
function sendToServer(){
// here you can reuse the object to send to a server
console.log("lat: " + coords.lat);
console.log("lon: " + coords.lon);
}