I want to fetch live gps location using javscript to store it in database. I already have implemented it. when user clicks on button. But it fetches location on second click.
Html code
<form action="user_location" method="post" id="form-{{$user->id}}">
#csrf
<input type="hidden" name="id" value="{{$user->id}}">
<input type="hidden" name="location" id="location-{{$user->id}}">
</form>
<a onclick="getLocation({{$user->id}})" class="btn">{{__('Get Location')}}</a>
Javscript code
function getLocation(user_id) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
geolocation = "Geolocation is not supported by this browser.";
}
if(setlocation){
form = document.getElementById("form-"+user_id);
var b = document.getElementById("location-"+user_id)
b.value = x.textContent;
form.submit();
}
}
function showPosition(position) {
x.innerText = position.coords.latitude + "-" + position.coords.longitude;
setlocation = true;
}
The getCurrentPosition function is asynchronous. That means that when it is called, it will allow the code after it to run before finishing. So that means that setLocation will not be true whenever your code reaches the following if statement:
if(setlocation){ // setlocation is still false
Handle your results of getting the position inside the success callback of getCurrentPosition.
function getLocation(user_id) {
if (!navigator.geolocation) {
return;
}
const form = document.getElementById("form-" + user_id);
const location = document.getElementById("location-" + user_id);
navigator.geolocation.getCurrentPosition(function(position) {
const { coords } = position;
location.value = coords.latitude + "-" + coords.longitude;
form.submit();
});
}
This question already has answers here:
Getting the location from an IP address [closed]
(20 answers)
Closed 2 years ago.
I managed to get the user's latitude and longitude using HTML-based geolocation.
//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get latitude and longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
}
I want to display the city name, it seems the only way to get it is to use a reverse geolocation API. I read Google's documentation for reverse geolocation but I don't know how to get the output on my site.
I don't know how to go use this: "http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true" to display the city name on the page.
How can I achieve this?
You would do something like that using Google API.
Please note you must include the google maps library for this to work. Google geocoder returns a lot of address components so you must make an educated guess as to which one will have the city.
"administrative_area_level_1" is usually what you are looking for but sometimes locality is the city you are after.
Anyhow - more details on google response types can be found here and here.
Below is the code that should do the trick:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Reverse Geocoding</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
</body>
</html>
$.ajax({
url: "https://geolocation-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function(location) {
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
$('#latitude').html(location.latitude);
$('#longitude').html(location.longitude);
$('#ip').html(location.IPv4);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div>Country: <span id="country"></span></div>
<div>State: <span id="state"></span></div>
<div>City: <span id="city"></span></div>
<div>Latitude: <span id="latitude"></span></div>
<div>Longitude: <span id="longitude"></span></div>
<div>IP: <span id="ip"></span></div>
Using html5 geolocation requires user permission. In case you don't want this, go for an external locator like https://geolocation-db.com IPv6 is supported. No restrictions and unlimited requests allowed.
JSON: https://geolocation-db.com/json
JSONP: https://geolocation-db.com/jsonp
Example
For a pure javascript example, without using jQuery, check out this answer.
Another approach to this is to use my service, http://ipinfo.io, which returns the city, region and country name based on the user's current IP address. Here's a simple example:
$.get("http://ipinfo.io", function(response) {
console.log(response.city, response.country);
}, "jsonp");
Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/
You can get the name of the city, country, street name and other geodata using the Google Maps Geocoding API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
<script type="text/javascript">
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
console.log(position.coords.latitude)
console.log(position.coords.longitude)
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON(GEOCODING).done(function(location) {
console.log(location)
})
}
function error(err) {
console.log(err)
}
</script>
</body>
</html>
and to display this data on the page using jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
<p>Country: <span id="country"></span></p>
<p>State: <span id="state"></span></p>
<p>City: <span id="city"></span></p>
<p>Address: <span id="address"></span></p>
<p>Latitude: <span id="latitude"></span></p>
<p>Longitude: <span id="longitude"></span></p>
<script type="text/javascript">
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON(GEOCODING).done(function(location) {
$('#country').html(location.results[0].address_components[5].long_name);
$('#state').html(location.results[0].address_components[4].long_name);
$('#city').html(location.results[0].address_components[2].long_name);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(position.coords.latitude);
$('#longitude').html(position.coords.longitude);
})
}
function error(err) {
console.log(err)
}
</script>
</body>
</html>
Here is updated working version for me which will get City/Town, It looks like some fields are modified in the json response. Referring previous answers for this questions. ( Thanks to Michal & one more reference : Link
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
// Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng);
}
function errorFunction() {
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
console.log(results);
$.each(arrAddress, function(i, address_component) {
if (address_component.types[0] == "locality") {
console.log("City: " + address_component.address_components[0].long_name);
itemLocality = address_component.address_components[0].long_name;
}
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
geolocator.js can do that. (I'm the author).
Getting City Name (Limited Address)
geolocator.locateByIP(options, function (err, location) {
console.log(location.address.city);
});
Getting Full Address Information
Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.
var options = {
enableHighAccuracy: true,
fallbackToIP: true, // fallback to IP if Geolocation fails or rejected
addressLookup: true
};
geolocator.locate(options, function (err, location) {
console.log(location.address.city);
});
This uses Google APIs internally (for address lookup). So before this call, you should configure geolocator with your Google API key.
geolocator.config({
language: "en",
google: {
version: "3",
key: "YOUR-GOOGLE-API-KEY"
}
});
Geolocator supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and a lot more features...
After some searching and piecing together a couple of different solutions along with my own stuff, I came up with this function:
function parse_place(place)
{
var location = [];
for (var ac = 0; ac < place.address_components.length; ac++)
{
var component = place.address_components[ac];
switch(component.types[0])
{
case 'locality':
location['city'] = component.long_name;
break;
case 'administrative_area_level_1':
location['state'] = component.long_name;
break;
case 'country':
location['country'] = component.long_name;
break;
}
};
return location;
}
You can use https://ip-api.io/ to get city Name. It supports IPv6.
As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.
Javascript Code:
$(document).ready(function () {
$('#btnGetIpDetail').click(function () {
if ($('#txtIP').val() == '') {
alert('IP address is reqired');
return false;
}
$.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
function (result) {
alert('City Name: ' + result.city)
console.log(result);
});
});
});
HTML Code
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
<input type="text" id="txtIP" />
<button id="btnGetIpDetail">Get Location of IP</button>
</div>
JSON Output
{
"ip": "64.30.228.118",
"country_code": "US",
"country_name": "United States",
"region_code": "FL",
"region_name": "Florida",
"city": "Fort Lauderdale",
"zip_code": "33309",
"time_zone": "America/New_York",
"latitude": 26.1882,
"longitude": -80.1711,
"metro_code": 528,
"suspicious_factors": {
"is_proxy": false,
"is_tor_node": false,
"is_spam": false,
"is_suspicious": false
}
}
As #PirateApp mentioned in his comment, it's explicitly against Google's Maps API Licensing to use the Maps API as you intend.
You have a number of alternatives, including downloading a Geoip database and querying it locally or using a third party API service, such as my service ipdata.co.
ipdata gives you the geolocation, organisation, currency, timezone, calling code, flag and Tor Exit Node status data from any IPv4 or IPv6 address.
And is scalable with 10 global endpoints each able to handle >10,000 requests per second!
This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.
$.get("https://api.ipdata.co?api-key=test", function(response) {
$("#ip").html("IP: " + response.ip);
$("#city").html(response.city + ", " + response.region);
$("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>ipdata.co - IP geolocation API</h1>
<div id="ip"></div>
<div id="city"></div>
<pre id="response"></pre>
The fiddle; https://jsfiddle.net/ipdata/6wtf0q4g/922/
Here is another go at it .. Adding more to the accepted answer possibly more comprehensive .. of course switch -case will make it look for elegant.
function parseGeoLocationResults(result) {
const parsedResult = {}
const {address_components} = result;
for (var i = 0; i < address_components.length; i++) {
for (var b = 0; b < address_components[i].types.length; b++) {
if (address_components[i].types[b] == "street_number") {
//this is the object you are looking for
parsedResult.street_number = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "route") {
//this is the object you are looking for
parsedResult.street_name = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "sublocality_level_1") {
//this is the object you are looking for
parsedResult.sublocality_level_1 = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "sublocality_level_2") {
//this is the object you are looking for
parsedResult.sublocality_level_2 = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "sublocality_level_3") {
//this is the object you are looking for
parsedResult.sublocality_level_3 = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "neighborhood") {
//this is the object you are looking for
parsedResult.neighborhood = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "locality") {
//this is the object you are looking for
parsedResult.city = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
parsedResult.state = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "postal_code") {
//this is the object you are looking for
parsedResult.zip = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "country") {
//this is the object you are looking for
parsedResult.country = address_components[i].long_name;
break;
}
}
}
return parsedResult;
}
Here's an easy function you can use to get it. I used axios to make the API request, but you can use anything else.
async function getCountry(lat, long) {
const { data: { results } } = await axios.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=${GOOGLE_API_KEY}`);
const { address_components } = results[0];
for (let i = 0; i < address_components.length; i++) {
const { types, long_name } = address_components[i];
if (types.indexOf("country") !== -1) return long_name;
}
}
Alternatively you could use my service, https://astroip.co, it is a new Geolocation API:
$.get("https://api.astroip.co/?api_key=1725e47c-1486-4369-aaff-463cc9764026", function(response) {
console.log(response.geo.city, response.geo.country);
});
AstroIP provides geolocation data together with security datapoints like proxy, TOR nodes and crawlers detection. The API also returns currency, timezones, ASN and company data.
It is a pretty new api with an average response time of 40ms from multiple regions around the world, which positions it in the handful list of super fast Geolocation APIs available.
Big free plan of up to 30,000 requests per month for free is available.
I want to get the the users current location address(city, street etc) on click event.
I have tried html5 geolocation and tried to console the data. on button click i am checking geo location is supported by creating alert box, and its executes succesfully, But its not printing any values in the console.
HTML
<div id="navbar"><span> Geolocation API</span></div>
<div id="wrapper">
<button id="location-button">Get User Location</button>
<div id="output"></div>
My script
<script>
$('#location-button').click(function(){
if (navigator.geolocation) {
alert("it is supported");
navigator.geolocation.getCurrentPosition(function(position){
console.log(position);
$.get( "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ position.coords.latitude + "," + position.coords.longitude +"&sensor=false", function(data) {
console.log(data);
})
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + position.coords.latitude + "," + position.coords.longitude + "&zoom=13&size=800x400&sensor=false";
$('#output').html(img);
});
}
else
{
console.log("geo location is not supported")
}
});
</script>
I want to get the full address of the users location.
You may visit this jsfiddle sample that demonstrates your use case.
Kindly note that it is not recommended to use web service in the client side, as web service requests are recommended to be used for server side requests.
As you can see below, what I used is a Geocoder Service instead of the Web Service Geocoding
geocoder.geocode( { 'location': pos}, function(results, status, infowindow) {
if (status == 'OK') {
console.log(results[0].formatted_address);
infoWindow.setContent('Location found: '+ results[0].formatted_address);
infoWindow.setPosition(pos);
infoWindow.open(map);
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
you simply can't! Geolocation use triangulation or GPS from the mobile and you'll get get longitude and latitude values or even the IP and you'll get nearest distributor device(haven't right word in english).
Obviously for geolocation the user have to authorize it too.
So if you want address the simpliest is to ask by a form. You can use a map related with longit/latitude matching but it'll be a pain and waste to do because you've to use all maps and places on earth related to use it that way.
Have a small javascript piece of code which calls navigator.geolocation.
I have an if statement, which works, to show the latitude and longitude if the user the user allows the call. However, the else section is not running.
If I run the code below I get prompted by the browser to allow; if I allow it then coordinates are shown. However, if I hit block instead nothing happens even though there is an else section.
<body>
<br> <p id="ChangeSring">Test</p>
<script>
var x = document.getElementById("ChangeSring");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(SavePosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
document.cookie = 'location=false;path=/form_handler';
}
function SavePosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
document.cookie = 'location=true;path=/form_handler';
document.cookie = 'latitude='+ position.coords.latitude +';path=/form_handler';
document.cookie = 'longitude='+ position.coords.longitude +';path=/form_handler';
}
</script>
<form action="/form_handler" _lpchecked="1">
Enter value:
<input type="text" name="SomeVar"><br>
<input type="submit" value="search">
</form>
</body>
You cannot use else to check for permissions.
The navigator method getCurrentPosition takes a success and error callbacks.
The error callback will be called if permission is denied.
if (navigator.geolocation) { // this checks if navigator is supported at all
navigator.geolocation.getCurrentPosition(console.log, () => {
console.log('Permission denied')
});
} else {
console.log('Geolocation is not supported by this browser.');
}
getCurrentPosition takes a success and an error function.
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition#Example
function errorGettingPosition(positionError) {
x.innerHTML = "Geolocation is not supported by this browser.";
document.cookie = 'location=false;path=/form_handler';
}
navigator.geolocation.getCurrentPosition(SavePosition, errorGettingPosition)
That if-else statement is checking if navigator.geolocation it's not undefined(and it's not even if you don't want the browser to know your location) follow the other answers to properly handle permission
My MVC Controller is getting hit twice on page load, and I am stumped on how to solve this problem.
I'm using navigator.geolocation.getCurrentPosition in my Layout page, and that passes the latitude and longitude to my controller.
I have RenderAction in a div, just in case the user has JavaScript disabled, as some people still do
:-(
This is what is causing my problem:
The RenderAction is getting rendered 1st and hitting the controller. Then, the AJAX request is firing and hitting the controller.
So my controller is getting hit twice per request.
Is there something I'm missing which will stop that, because at the moment, all I can think of is to remove the render action from the page.
Code:
<div class="dvWeather">
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
</div>
if (navigator.geolocation) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var aj = "gl";
$.ajax({
url: '#Url.Action("PvCurrentWeatherConditions", "Weather")',
type: 'get',
data: {
lat: lat,
lon: lon,
aj: aj
},
success: function (result) {
$('.dvWeather').html(result);
}
});
}
public PartialViewResult PvCurrentWeatherConditions(string lat, string lon, string aj)
{
if (Request.IsAjaxRequest())
{
try
{
//TODO create Viewmodel
GeoCoordinate gc = new GeoCoordinate();
var latitude = gc.Latitude = Convert.ToDouble(lat);
var longitude = gc.Longitude = Convert.ToDouble(lon);
string latlon = latitude + "," + longitude;
var displayCurrentConditions = _igcc.CurrentConditions(latlon);
return PartialView("pvCurrentWeatherConditions");
}
catch (FormatException)
{
//TODO get ip address
return PartialView("pvLocationBasedOnIpAddress");
}
catch (Exception)
{
return PartialView("pvError");
}
}
return PartialView("pvLocationBasedOnIpAddress");
}
Perhaps use another method for checking if the visitor has javascript disabled, like noscript:
<noscript>
<meta http-equiv="refresh" content="[URL]?java=off">
</noscript>
then handle the querystring in a new action.
You don't have to remove the Render action. Just make another (negative) check in the div:
<div class="dvWeather">
<script type="text/javascript>
//if (!navigator.geolocation) { : Edit
if (navigator.geolocation == null) {
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
}
</script>
</div>
Edit:
if (navigator.geolocation != null) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
This way only one call will be made.
Hope it helps.