HTML5 Server Geolocation (NOT client location) - javascript

I use the HTML5 implementation of gelocation (navigator.geolocation) to show client location on a google map, using the Google maps API. This is easy.
What I would like, however, is to also put the server location on a map, i.e. 'you are here, your server is here'. I cannot see how to easily do this.
I could just scrape a page like whatsmyip for coordinates, but it seems like this should be built into the API. Am I just missing it?
Thanks,
Colin

The HTML5 geolocation api is implemented by the browser and uses a mix of information potentially including WiFi signals, IP address, or a GPS module. It does not have access to that information for the sever, nor is it common to care about the sever location.
All of which is to say the HTML5 geolocation api does support locating the server and you will need to provide the coordinates by some other means (most likely some form of Geo IP database).

I just scraped using php:
function ip_details($ip) {
//$json = file_get_contents("http://ipinfo.io/{$ip}");
$json = file_get_contents("http://ipinfo.io/");
$details = json_decode($json);
return $details;
}
$details = ip_details("8.8.8.8");
$_SESSION['user']['serverextip'] = $details->ip;
$_SESSION['user']['serverloc'] = $details->loc;

Related

How can I use geolocation in my node.js to get user device lat/long

Good day all, pardon my question logic as I am new here. I am building my first fullstack App using React and Node.I am thinking of three approaches but not sure what will work best.
APPROACH ONE
I want to be able to get user lat/long when they fill a form in the frontend and request access to their geolocation through the geolocation API. For example, when a user submit their region and community name, the backend will call the getCurrentPosition geolocation API. Then the returned lat/long will form part of the data to be sent to the database as shown in the extracted code below. But when I tried this approach, I ran into two challenges. First, an error message that navigator is not defined. Second, I don't know how to retrieved the lat/long returned and declare it as a const to use it in creating the location. See the code below:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
alert("Your browser is out of fashion. There is no geo location!")
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude
console.log(`Your latitude is ${latitude} and your longitude is ${longitude}`)
return (latitude, longitude);
}
function error() {
alert("Can't detect your location. Try again later.")
}
How do I declare the lat/long as a const outside the function. Some like:
const communityName = req.body.communityName;
const latitude = (success).latitude;
const longitude = (success).longitude;
APPROACH 2
I downloaded the geolocation npm package and use it as in code below but get the error that navigator is not defined. If I am to use this approach, how can I define navigator and how can I get to declare the lat/long as a const outside of the function?
const geolocation = require('geolocation');
geolocation.getCurrentPosition(function (err, position) {
if (err) throw err
console.log(position)
})
APPROACH 3
I read about this approach but can't get a working example. It is suggested that I should use the geolocation API to get the user device lat/long and send the coords as part of req.body data to the backend API. If this is a good approach, is there a tutorial I can follow?
Please I am new to Javascript and coding but I have made serious progress but this as got me stocked on my project. No answer is too wrong lease. There is sense in nonsense.
navigator.geolocation
This is an API provided by browsers. It isn't available to Node.js.
I downloaded the geolocation npm package
This wraps navigator.geolocation. It is designed for when you are writing client-code code using Node modules and a compilation step such as provided by Webpack. It doesn't work with Node.js.
It is suggested that I should use the geolocation API to get the user device lat/long and send the coords as part of req.body data to the backend API.
MDN and Google both provide introductions to the fetch API for making HTTP requests from client-side JavaScript.
There is also some React-specific information in the React FAQ.
You can then read the data in a different endpoint with req.body providing you have configured a suitable body-parsing middleware.

Node.js server side solution to find user location

Please educate me for i am hoping this is possible. I am working on a mobile app that is currently using Node.js on its backend server side. Using twitter's api I am currently streaming tweets from from a static location (for example New York City):
twit.stream('statuses/filter',{ 'locations':'-74,40,-73,41'},
function(stream) {
stream.on('data', function(data)
Is there anyway that i can adjust this code where if the user moves, tweets are now automatically streamed from their new location?
In other words if the user is now in Miami Florida, my goal is to have the server now automatically stream tweets from that area; and the same if they were to drive to Gainesville Florida or fly to Atlanta Georgia etc...
I need Nodejs to automatically stream tweets from the user's new location. Is there anyway to do so?
I assume that I have to create a variable var location = latitude, longitude
Where would I go from there?
Here is an example of my code:
var twitter = require('ntwitter');
var twit = new twitter({
consumer_key: credentials.consumer_key,
consumer_secret: credentials.consumer_secret,
access_token_key: credentials.access_token_key,
access_token_secret: credentials.access_token_secret
});
//Streaming from the static location of New York City
twit.stream('statuses/filter',{ 'locations':'-74,40,-73,41'},
function(stream) {
stream.on('data', function(data) {
console.log(data.text);
The most reliable option with the best location granularity would be to pass the geolocation lat/lon over from your mobile app. The only down side to this is that your app (assuming Android or iOS) will ask the user if it's OK to share the geolocation information from your app, but the user is only asked once. You don't provide more details re your mobile app, but if it's written using PhoneGap / Apache Cordova, feel free to ping me if some code snippets would be helpful.
The other option is to pass on the IP and do an IP location lookup with a service. However, this typically can be very unreliable and you can often be off as in the wrong state even.
With both options, keep in mind it's easy to spoof the wrong location.

Get user's location (latitude, longitude) when visited

Whenever a user enters my site, i want to get his longitude, latitude to further use in my google maps. I have tried using HTML5 geolocation script and geocoder gem.
Using Geocoder gem, my hash is empty when trying below code, why is this happening ? Is this because i am running it in localhost ? Please suggest how to get it done if any other way.
I just need latitude and longitude of my user, thats it.
location = request.location
longitude = location.data['longitude']
If you had carefully read documentation of geocoder gem you would notice that:
Note that these methods will usually return nil in your test and
development environments because things like "localhost" and "0.0.0.0"
are not an Internet IP addresses.

How to get the zipcode of a user using AngularJS

I need to populate some data based on the zipcode of the user visiting the site.
Could somebody tell me how to retrieve the zipcode of the location of that user?
I am using AngularJS on my app.
OK. It is a bit involved, but here is how I would do it, if I were you.
First, you would use the geolocation API as follows:
window.navigator.geolocation.getCurrentPosition(function(pos){
console.log(pos);
});
Inside your callback, you will get a position object. It looks like this:
{
"timestamp":1408324851386,
"coords"{
"speed":null,
"heading":null,
"altitudeAccuracy":null,
"accuracy":30,
"altitude":null,
"longitude":-111.8942634,
"latitude":40.7288257
}
}
Then, you can take the latitude and longitude and call your server to translate it into a ZIP code. Getting the lat/long is the hard part. Doing the math to turn that into a zip is easy.
An alternative to calling your own server to translate the lat/long into a zip, you could call Google Maps' reverse lookup API. You give it a lat long, and it gives you an address, complete with a ZIP. See HERE for how to do that.
DISCLAIMER: This won't work in IE8, as the geolocation API wasn't introduced until IE9. It will work in all other browsers (besides Opera Mini, #NBD).
HERE IS A FULL WORKING EXAMPLE
I just tried this out, and it found my house, no problem.
window.navigator.geolocation.getCurrentPosition(function(pos){
console.log(pos);
$http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+pos.coords.latitude+','+pos.coords.longitude+'&sensor=true').then(function(res){
console.log(res.data);
});
})
There doesn't seem to be any built-in method for determining this, you'll have to use a map service or zipcode database.

Getting geolocation from IP address

I need to track user details, for that client's location and IP address is needed.
I got IP address from
$this->input->ip_address();
in codiigniter. Now the problem is how can i make their location in google map by using their respective IP address
just use ipinfo.io at
http://ipinfo.io/
it uses a location api that we can post ip address and it will returns the location details as json:
we can able to display the loacation on map with the langitude and longitude details from json response to google Maps API.
Here is the code i used:
this script creates a Google Map instance with lattitude & longitude from json response:
jQuery(document).ready(function(){
jQuery.get("http://ipinfo.io/202.88.237.138", function (response)
{
var lats = response.loc.split(',')[0];
var lngs = response.loc.split(',')[1];
map = new GMaps({
el: '#map',
lat: lats, //latitude
lng: lngs //longitude
});
}, "jsonp");
});
and the map will displayed on:
<div style="border:1px solid red; height:745px;" id="map"></div>
Google Maps API gmaps.js is needed to run this..
As a viable (although often less accurate) alternative, the HTML5 spec includes Geolocation. As HTML 5 becomes more and more prevalent I think we can expect to see this become standard in the future. It also does not require the use of external web services or libraries. Everything you need to geolocate is built right into the clients browser.
I believe the primary method used is IP address as specified.
The Google Maps API will do the work of finding location using geoip for you. If the user is on a mobile device or has a more accurate way of locating themselves (like a GPS), it'll use that instead.
Here's a good starting point:
https://google-developers.appspot.com/maps/documentation/javascript/examples/map-geolocation
If you absolutely need to fetch location from IP only, there are third-party tools that you can scrape to get this information. You should make sure you have permission beforehand if you're using this in a larger project.
freegeoip.net provides a public HTTP API to search the geolocation of IP addresses. It uses a database of IP addresses that are associated to cities along with other relevant information like time zone, latitude and longitude.
You're allowed up to 15,000 queries per hour.
If you need more than that, you can run the freegeoip as a web server on your own infrastructure. See: freegeoip on github

Categories