I want to get the geolocation of a user visiting my website. I love this simple 'https://www.w3schools.com/html/html5_geolocation.asp' code when I use the try it yourself it displayed the lat and long. I tried it on my website, is ok. but another trying given me NaN. from both the w3school site and my site. please, how can I solve the problem?
<html>
<body>
<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>
<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>
The code is correct so I'm only guessing that maybe you're trying your code on a server/domain without https. This is now mandatory in several mainstream browsers, so you can only use the geolocation api if you are under https.
You can read more about it here : Geolocation Without SSL connection
Related
I'm trying to make a webpage with a button. When the button clicked the webpage has to display the user's current location and the user's timezone.
I'm locating users' latitude & longitude by jquery and for the location name I use reverse geocoding of google geocode API and for timezone google timezone API.
Function for the latitude & longitude and function for the reverse geocoding works well. But the function for the timezone isn't working. The unworking function I wrote for this API is the last function in the JS code. I don't understand how to solve this problem.
I need someones' help with this.
HTML Part
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<h1>Hello let's trace your location</h1>
<button onClick="getLocation()">Get Location</button>
<div id="output"></div>
<script language="javascript" type="text/javascript" src="java.js">
</script>
</body>
</html>
JS PART
var x = document.getElementById('output');
function getLocation(){
if (navigator.geolocation){
x.innerHTML = "Supporting";
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
x.innerHTML = "Browser not supporting";
}
}
function showPosition(position){
var locAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+position.coords.latitude.toFixed(6)+","+position.coords.longitude.toFixed(6)+"&key=<key>";
//x.innerHTML += locAPI;
$.get({
url: locAPI,
success: function(data){
console.log(data);
var num = data.results.length - data.results.length;
var add1 = data.results[num].address_components.length - 1;
var add2 = data.results[num].address_components.length - 2;
x.innerHTML = num;
x.innerHTML += add1;
x.innerHTML += add2;
x.innerHTML += data.results[num].address_components[add2].long_name;
x.innerHTML += "<br/>";
x.innerHTML += data.results[num].address_components[add1].long_name;
}
});
}
function showPosition(location){
var timeAPI = "https://maps.googleapis.com/maps/api/timezone/json?location="+location.coords.latitude.toFixed(6)+","+location.coords.longitude.toFixed(6)+"×tamp=<key>";
//x.innerHTML += timeAPI;
$.get({
url:timeAPI,
success:function(data){
console.log(data);
}
});
}
}
Code not working on server want to find geo-location and store into database
code not working on server want to find geo-location and store into a database it working properly on localhost its w3school code.
<!DOCTYPE html>
<html>
<body>
<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) {
window.location = "position/?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
}
</script>
</body>
</html>
There is no geolocation library on the server. navigator.geolocation only exists in the browwer.
I'm currently trying to implement a simple map using javascript, openstreetmaps and leaflet.
My problem comes way before that, when calling javascripts geolocation, and confirming the information on the browser I keep getting an error. My current code is the following:
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css"
integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet.js"
integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log=="
crossorigin=""></script>
<style>
#mymap {
width: 100%;
height: 400px;
background-color: grey;
margin-top: 15px;
}
</style>
<script language="javascript">
function initmap(initialLat, initialLong)
{
if(!initialLat || !initialLat.length){
initialLat = 38.01693;
}
if(!initialLong || !initialLong.length){
initialLong = -8.69475;
}
var mymap = this.mymap = L.map('mymap',{
center: [initialLat, initialLong],
zoom: 15
});
var osmUrl='http://tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
L.tileLayer(osmUrl, osmAttrib).addTo( mymap );
}
function getMylocation()
{
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
mymap.setView(new L.LatLng(lat, long), 15);
}, function (error) {
switch (error.code) {
case error.PERMISSION_DENIED:
output.innerHTML += "<p>User denied the request for Geolocation.</p>";
break;
case error.POSITION_UNAVAILABLE:
output.innerHTML += "<p>Location information is unavailable.</p>";
break;
case error.TIMEOUT:
output.innerHTML += "<p>The request to get user location timed out.</p>";
break;
case error.UNKNOWN_ERROR:
output.innerHTML += "<p>An unknown error occurred.</p>";
break;
}
});
}
}
</script>
</head>
<body onLoad="javascript:initmap();">
<button id="find-near-btn" onClick="getMylocation()">
Find my location
</button>
<div id="mymap"></div>
<div id="output"></div>
</body>
</html>
When calling the getMyLocation() function using the button, I always end up in the
case error.POSITION_UNAVAILABLE:
condition. Any idea on why this might be happening?
Error is called when position information is unavailable. GeoLocation API estimates location on the basis of CELL Towers, Wifi MAC Addresses, GPS (if on mobile). But the information is not available. Your code is correct, try running that on different device.
hi i have this code for geo location finding
<html>
<head>
<title>fs</title>
<p id="demo"></p>
<script type="text/javascript"> function get_stored_data() {
alert(localStorage.value); }
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>
</head>
<body>
<p>The element below will receive content</p>
<div id="div" />
<script type="text/javascript">getLocation()</script>
</body>
</html>
and i want to send the values of the latitude and longitude to php file
that will write it in a text file
I use $_GET or $_POST methods to pass my data to another PHP page
You have to call ajax and send values.
This link may be helpful
http://www.w3schools.com/php/php_ajax_database.asp
I am using this code for finding current location latitude and longitude.
$(document).ready(function() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
else
{
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser.');
}
});
function successFunction(position)
{
var lat = position.coords.latitude;
var long = position.coords.longitude;
alert('Your latitude is :'+lat+' and longitude is '+long);
}
function errorFunction(position)
{
alert('Error!');
}
It's working fine in Chrome but not in Mozilla. There is no alert error message either.
Try this i hope this will help you:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function initGeolocation()
{
if( navigator.geolocation )
{
// Call getCurrentPosition with success and failure callbacks
navigator.geolocation.getCurrentPosition( success, fail );
}
else
{
alert("Sorry, your browser does not support geolocation services.");
}
}
function success(position)
{
document.getElementById('long').value = position.coords.longitude;
document.getElementById('lat').value = position.coords.latitude
}
function fail()
{
// Could not obtain location
}
</script>
</head>
<body onLoad="initGeolocation();">
<FORM NAME="rd" METHOD="POST" ACTION="index.html">
<INPUT TYPE="text" NAME="long" ID="long" VALUE="">
<INPUT TYPE="text" NAME="lat" ID="lat" VALUE="">
</body>
</html>
You can try this code:-
<!DOCTYPE html>
<html>
<body>
<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>
Reference
By using below jQuery code, You can find your current location latitude and longitude without any API key .Let's Try
$(document).ready(function(){
// get users lat/long
var getPosition = {
enableHighAccuracy: false,
timeout: 9000,
maximumAge: 0
};
function success(gotPosition) {
var uLat = gotPosition.coords.latitude;
var uLon = gotPosition.coords.longitude;
console.log(`${uLat}`, `${uLon}`);
};
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
};
navigator.geolocation.getCurrentPosition(success, error, getPosition);
});