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.
Related
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.
Im working on App using React Native using user location, what i wanna do is while app is closed to check if user is at a location that already exists in the database and if he is
Show a notification saying “ are you at John Doe place “
So to get started i need to know what’s needed to check user location in the background, and then compare the user location in the database and get the results if he is at some location that exists in the database show notifications
Any place where i should start ?
You will probably have to have:
Previously requested the appropriate rights to the user (location, notifications,..)
A background task running periodically or a watcher on the user's position
A way to access the user's
location (see navigator.geolocation.getCurrentPosition(...) or navigator.geolocation.watchPosition(...))
You can combine that with network calls and notifications and you should be able to get to the desired behavior.
This example may help you getting started.
You can use the Geolocation API to get user location, if they permit the app to know their location. I'd add it to a snippet here but stackoverflow has disabled use of the Geolocation API.
const successCallback = positionObj => console.log(positionObj);
const errorCallback = positionError => console.error(positionError);
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
Working JSFiddle here.
I am building a card game app on iOS and android which with the following logic:
People download the app from App Store / Google Play
They can play the game offline with other players within the same wifi-network
One client will act as a server, while other players will act as clients
The game is an app with Node.js, SQLite embedded
Each player's move will be saved in the server
When there's internet access, the iOS act as server will send the data to cloud
My approach is
The game will be a HTML5 with Node.js, the player act as a game holder(server) will open a port (like port 80)
Other players will use HTTP get/set to send and receive the JSON package to and from game holder
My questions is
Will it be possible for me to run Node.js on iOS, as a server and open ports to let other players connect in? So that I can use JSON for all the communications between players.
If not, what will be the best way for different device (iOS, android, Windows Phone) communicate?
Any suggestions and help will be appreciated. Thanks.
Michael
My reputation is not enough to comment but I will suggest what to use anyway. If you make a server in Node.js, then the rest of this answer will tell you what to do. Use CFNetwork and CoreFoundation. Assuming you are sending data in string format, this code should help (the code sends a string to a server).
import CoreFoundation
import CFNetwork
var outputStream: NSOutputStream!
var writeStream: Unmanaged<CFWriteStreamRef>?
var addr: CFString = "127.0.0.1"
var port: UInt32 = 80
//the second nil in CFStreamCreatePairWithHost is a read stream. which means it reads data. we don't need it bc we are only sending data
CFStreamCreatePairWithSocketToHost(nil, addr, port, nil, &writeStream)
outputStream = writeStream!.takeRetainedValue()
outputStream.delegate = self
outputStream.open()
outputStream.write("fireGun", maxLength: 8 //(the char count of fireGun")
//close outputStream
outputStream.close()
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;
So to start off, I have a raspberry pi, running a lighttp server on arch. I have a webpage that will have a max of 10 people connected at a time. Each user will be given the tag "Master," or "observer." The webpage will have controls that only the "Master," can use.
Just a heads up: I am just learning most of this so I may be making some mistakes about how to accomplish this.
My original idea is has follows. When a user connects to the database their IP address would be grabbed and inserted into a SQLite database, along with a user tag, and time of connection. From there I would be able to query the database for the users tag when they tried to execute various commands.
Whatever I use needs to be very lightweight and not store cookies on the users device.
Here is the JavaScript I currently have, it probably isn't the most efficient, but I plan on getting it working then making it look nice.
This code is supposed to connect the databases and insert the user.
<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
<script type="application/javascript">
var db = openDatabase('userCon.contbl.sqlite', '1.0', 'contbl', 1024);
db.transaction(function(transaction) {
var ip = myip;
var conStatus = "master"
var date = new Date();
console.log('Inserting into the database ' + ip + ',' + conStatus +',' + date);
transaction.executeSql('INSERT INTO contbl(ipAd, conType, lastActive) VALUES (?,?,?,?)',[ip,conStatus,date], function(transaction, results) {
}, function (transaction, err){
console.log(err.message+":Error"); // here an error
});
});
</script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"> </script>
I am unable to connect to the SQLite database I created on the pi, which after my research may be because SQLite is supposed to be run locally and not on a server.
Is there some sort of work around to point to the SQLite database on the pi, or is there a better resource to use for this type of task?
EDIT:
I guess my original post was not specific enough. The basic idea is I need to be able to pass a tiny bit of information from a webpage, back to the server hosting it. i.e. User connect to the server and sends its IP then the server tags that IP as an Observer of Controller. From there the server will treat each person viewing the webpage differently based on how the user was tagged.
My original plan was to use a really light weight database like SQLite, but as I found out, SQLite is local use only. I need to do this on a sever with lower then 10 connections.
My hope is someone has a suggestion, or an example to solve this problem.
The most common way for javascript running on a web page to talk to a server these days is some kind of RESTful web service.
You'll want to find a server-side programming language that runs on the Pi. Maybe node.js? It's like javascript but on a server, see here: http://weworkweplay.com/play/raspberry-pi-nodejs/
You then write whatever methods you want in the server-side language, methods which talk to the database, then have your client-side javascript call those methods. Google "REST services node.js" and you'll find plenty of how-tos.
If the SQLite database is running on the server, and this code runs in the user's browser, it can't connect to the database. The only interaction between the browser and your server is HTTP, unless there's a gigantic security hole in your server.