Find latitude and longitude of current location - javascript

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);
});

Related

I need to connect google time zone api to this

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)+"&timestamp=<key>";
//x.innerHTML += timeAPI;
$.get({
url:timeAPI,
success:function(data){
console.log(data);
}
});
}
}

My code not working on server but working on localhost

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.

Geolocation result display NaN

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

Leaflet map not returning JSON data from web service

I have a web service that queries a database and returns JSON data. I also have a HTML page which has AJAX and a Leaflet map. I have to make the map display markers based on the JSON that returns from the web service.
I cannot figure out what I am doing wrong, I have followed the class notes. I think the problem is the request is not sending. Here is my code
HTML
<!DOCTYPE html>
<html>
<head>
<title>Points of Interest</title>
<link rel="stylesheet" type="text/css" href="custom.css">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="skeleton.css">
<link rel='stylesheet' type='text/css' href='/wad/leaflet/leaflet.css' />
<script type="text/javascript" src="map.js"></script>
<script type='text/javascript' src='/wad/leaflet/leaflet.js'></script>
</head>
<body onload='init()'>
<img src="heroxd.jpg" alt="">
<div class="container">
<div class="twelve-columns">
<h1>Welcome to Points of Interest!</h1>
<p>Linking users to interesting areas for 25 years</p>
<p>Enter a region below to search for POIs!</p>
<input type="text" id="region" class="margin-top-30" placeholder="Enter Region" name="region" />
<input type="submit" id="submit" />
</div>
<div id="jsonload">
</div>
<div id="map1" style="width:800px; height:600px">
<div id="info"></div>
</div>
</body>
</html>
JS
var map;
var attrib;
function init()
{
document.getElementById("submit").addEventListener("click", poiMarkers);
map = L.map ("map1");
attrib="Map data copyright OpenStreetMap contributors, Open Database Licence";
L.tileLayer
("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
{ attribution: attrib } ).addTo(map);
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition (processPosition, handleError,
{enableHighAccuracy:true, maximumAge: 5000 }
);
}
else
{
alert("Sorry, geolocation not supported in this browser");
}
function processPosition(gpspos)
{
var info = 'Lat: ' + gpspos.coords.latitude + ' lon: ' + gpspos.coords.longitude;
document.getElementById('info').innerHTML = info;
map.setView([gpspos.coords.latitude,gpspos.coords.longitude], 14);
}
function handleError(err)
{
alert('An error occurred: ' + err.code);
}
}
function processPosition(gpspos)
{
var info = 'Lat: ' + gpspos.coords.latitude + ' lon: ' + gpspos.coords.longitude;
document.getElementById('info').innerHTML = info;
map.setView([gpspos.coords.latitude,gpspos.coords.longitude], 14);
}
function handleError(err)
{
alert('An error occurred: ' + err.code);
}
function poiMarkers()
{
var a = document.getElementById('region').value;
var ajaxConnection = new XMLHttpRequest();
ajaxConnection.addEventListener ("load",e =>
{
var allPlaces = JSON.parse(e.target.responseText);
var lat = 0;
var lon = 0;
var poiLocation = "";
allPlaces.forEach( curplace =>
{
lat = `${curPlace.lat}`;
lon = `${curPlace.lon}`;
poiLocation = [lat, lon];
L.marker(poiLocation).addTo(map);
} );
});
// Open the connection to a given remote URL.
ajaxConnection.open("GET" , `https://****return_poi.php?region=${a}`);
// Send the request.
ajaxConnection.send();
}
Try like this:
$.ajax({
url: "https://****return_poi.php?region=${a}",
data: data,
type: "GET",
success: success,
dataType: json
});
Reference: https://api.jquery.com/jquery.get/
or
$.get(URL,data,function(data,status,xhr),dataType)
Reference: https://www.w3schools.com/jquery/ajax_get.asp

send html5 value to php

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

Categories

Resources