I am trying to make an application that tracks multiple users - gps

I am trying to make a application that tracks multiple people on Google maps and allows the user to see who he wants to track.
I would like this app to send the long and lat to mysql. I am having trouble trying to get the longitude and latitude of the user to update in mysql. What is the best way to to do this?
All i want to do is track multiple people and plot them on a user map, so if the user wanted to see where his friends where at it would show on his cell phone.

If you are using web, you can get each users location from the browser using geolocation:
http://www.w3schools.com/html/html5_geolocation.asp
Since you don't say what your app is written in though we cannot offer any more specific advice.
You will then need to upload that to your app and store it in the database along with a key identifying each user.
The client would then have to be able to pick which of these users they wish to view, at which point you would draw them on a map using something like Google Maps API:
https://developers.google.com/maps/

<!DOCTYPE html>
<html>
<!--
geoLocMap.html by Bill Weinman
<http://bw.org/contact/>
created 2011-07-07
updated 2011-07-20
Copyright (c) 2011 The BearHeart Group, LLC
This file may be used for personal educational purposes as needed.
Use for other purposes is granted provided that this notice is
retained and any changes made are clearly indicated as such.
-->
<head>
<title>
Geolocation Map Test (1.1.3)
</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100%; width: 100% }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var watchID;
var geo; // for the geolocation object
var map; // for the google map object
var mapMarker; // the google map marker object
// position options
var MAXIMUM_AGE = 200; // miliseconds
var TIMEOUT = 300000;
var HIGHACCURACY = true;
function getGeoLocation() {
try {
if( !! navigator.geolocation ) return navigator.geolocation;
else return undefined;
} catch(e) {
return undefined;
}
}
function show_map(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lon);
if(map) {
map.panTo(latlng);
mapMarker.setPosition(latlng);
} else {
var myOptions = {
zoom: 18,
center: latlng,
// mapTypeID --
// ROADMAP displays the default road map view
// SATELLITE displays Google Earth satellite images
// HYBRID displays a mixture of normal and satellite views
// TERRAIN displays a physical map based on terrain information.
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.setTilt(0); // turns off the annoying default 45-deg view
mapMarker = new google.maps.Marker({
position: latlng,
title:"You are here."
});
mapMarker.setMap(map);
}
}
function geo_error(error) {
stopWatching();
switch(error.code) {
case error.TIMEOUT:
alert('Geolocation Timeout');
break;
case error.POSITION_UNAVAILABLE:
alert('Geolocation Position unavailable');
break;
case error.PERMISSION_DENIED:
alert('Geolocation Permission denied');
break;
default:
alert('Geolocation returned an unknown error code: ' + error.code);
}
}
function stopWatching() {
if(watchID) geo.clearWatch(watchID);
watchID = null;
}
function startWatching() {
watchID = geo.watchPosition(show_map, geo_error, {
enableHighAccuracy: HIGHACCURACY,
maximumAge: MAXIMUM_AGE,
timeout: TIMEOUT
});
}
window.onload = function() {
if((geo = getGeoLocation())) {
startWatching();
} else {
alert('Geolocation`enter code here` not supported.')
}
}
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>

Related

Prevent Popup template to shows multiple feature in ArcGIS 4.16 Angular 10

I have integrated a popup on the map for a specific layer. Some time the poup shows pagination (featureNavigation) multiple data. Sometimes it fails to show the data, or mismatch in the data that actually the service returns.
var popupTrailheads = {
title: "ID: {ID}",
content: this.getcustomcontent.bind(this),
};
// Add layer special layer
this.layer_fifteen = new FeatureLayer({
url: `${this.esriURL}/15`,
visible: true,
outFields: ['*'],
popupTemplate: popupTrailheads,
});
getcustomcontent(feature) {
// The popup content will become here from angular service
return `<div>content</div>`;
}
I have a few options to fix the issue.
1)Popup for this layer enables only at a specific Zoom level. Else the popup won't appear.
2)The click on the map should trigger only for a point. (I believe when click on the layer it triggers multiple points that is the reason it shows multiple feature details.)
Can you please suggest an idea, how to enable a popup in specific zoom level, or select only one feature in one click on the map.
Thanks in advance.
So, there are a number of possible ways to enable the popup under certain conditions, like the zoom level of the view.
In the example that I made for you popup only opens if zoom is greatest than 10.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />
<title>PopupTemplate - Auto Open False</title>
<link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css" />
<script src="https://js.arcgis.com/4.15/"></script>
<style>
html,
body,
#viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
</style>
<script>
var populationChange;
require(["esri/Map", "esri/views/MapView", "esri/layers/Layer"], function (
Map,
MapView,
Layer
) {
var map = new Map({
basemap: "dark-gray"
});
var view = new MapView({
container: "viewDiv",
map: map,
zoom: 7,
center: [-87, 34]
});
var highlightSelect = null;
Layer.fromPortalItem({
portalItem: {
id: "e8f85b4982a24210b9c8aa20ba4e1bf7"
}
}).then(function (layer) {
map.add(layer);
var popupTemplate = {
title: "Population in {NAME}",
outFields: ["*"],
content: [{
type: 'fields',
fieldInfos: [
{
fieldName: "POP2010",
format: {
digitSeparator: true,
places: 0
},
visible: false
},
{
fieldName: "POP10_SQMI",
format: {
digitSeparator: true,
places: 2
}
},
{
fieldName: "POP2013",
format: {
digitSeparator: true,
places: 0
}
},
{
fieldName: "POP13_SQMI",
format: {
digitSeparator: true,
places: 2
}
}
]
}],
};
layer.popupTemplate = popupTemplate;
function populationChange(feature) {
var div = document.createElement("div");
var upArrow =
'<svg width="16" height="16" ><polygon points="14.14 7.07 7.07 0 0 7.07 4.07 7.07 4.07 16 10.07 16 10.07 7.07 14.14 7.07" style="fill:green"/></svg>';
var downArrow =
'<svg width="16" height="16"><polygon points="0 8.93 7.07 16 14.14 8.93 10.07 8.93 10.07 0 4.07 0 4.07 8.93 0 8.93" style="fill:red"/></svg>';
var diff =
feature.graphic.attributes.POP2013 -
feature.graphic.attributes.POP2010;
var pctChange = (diff * 100) / feature.graphic.attributes.POP2010;
var arrow = diff > 0 ? upArrow : downArrow;
div.innerHTML =
"As of 2010, the total population in this area was <b>" +
feature.graphic.attributes.POP2010 +
"</b> and the density was <b>" +
feature.graphic.attributes.POP10_SQMI +
"</b> sq mi. As of 2013, the total population was <b>" +
feature.graphic.attributes.POP2013 +
"</b> and the density was <b>" +
feature.graphic.attributes.POP13_SQMI +
"</b> sq mi. <br/> <br/>" +
"Percent change is " +
arrow +
"<span style='color: " +
(pctChange < 0 ? "red" : "green") +
";'>" +
pctChange.toFixed(3) +
"%</span>";
return div;
}
view.popup.autoOpenEnabled = false; // <- disable view popup auto open
view.on("click", function (event) { // <- listen to view click event
if (event.button === 0) { // <- check that was left button or touch
console.log(view.zoom);
if (view.zoom > 10) { // <- zoom related condition to open popup
view.popup.open({ // <- open popup
location: event.mapPoint, // <- use map point of the click event
fetchFeatures: true // <- fetch the selected features (if any)
});
} else {
window.alert(`Popup display zoom lower than 10 .. Zoom in buddy! .. (Current zoom ${view.zoom})`);
}
}
});
});
});
</script>
</head>
<body>
<div id="viewDiv"></div>
</body>
</html>
Related to only display one result in the popup, you could hide the navigation like this,
view.popup.visibleElements.featureNavigation = false;
Now if what you actually want is to get only one result, then I suggest to use view method hitTest, that only gets the topmost result of the layers. You could do this after inside the click handler and only open if any result of desire layer. For this you need to set featFeatures: false, and set the features with the hit one.
Just as a comment it could result weird or confusing to the user retrieve just one of all possible features. I think probable you may have a problem with the content.

How can I show automatically registered users geolocation in a global map with google maps api as they register?

I'm trying to show all users geolocation from a web site in a map. Through google maps API documentation I've got a way to show my location as user. But, how I make it for show all geolocation from the registered people on the website?
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
Create objects of the google.maps.Marker() type, set a position using the setPosition function of it and add it to your map using the setMap function.
Example (Lat/Lng is the center of Germany - insert your users coordinates there):
var marker=new google.maps.Marker();
// use your registered user coordinates here
marker.setPosition(new google.maps.LatLng(48.14544, 8.19208));
marker.setMap(map);
Additionally you can use boundaries to make your map autozoom to get every marker visible:
var bounds=new google.maps.LatLngBounds();
...
bounds.extend(marker.getPosition());
...
map.fitBounds(bounds);

ArcGIS Online WebMap authentication timeout

I have an ArcGIS Online public account and add WebMap to my website.
My ArcGIS Online WebMap looks like this ESRI's sample: LINK
And I am trying to add my WebMap to my website like this ESRI's reference page. You will see there is a map in the center of page: LINK
My WebMap is displayed on my webpage well. When I access my webpage, my WebMap asks my ID and Password. If I entered it, then it shows my map.
However, my question is, if I moved to different page and then come back to map page, it asks again. Is it possible to set a timeout so I don't have to sign in everytime I access the page?
The reason I asked this question is that to find out if there were a way to reduce my code simple and work on code in front-end.
I've researched OAuth that ESRI provided and I ended up using esri/IdentityManager. There were references to use esri/IdentityManager package; however there were no sample code to using it with personal WebMap which used arcgisUtils.createMap
So here is sample code that I worked:
require([
"dojo/parser",
"dojo/ready",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dojo/dom",
"esri/map",
"esri/urlUtils",
"esri/arcgis/utils",
"esri/dijit/Legend",
"esri/dijit/LayerList",
"esri/graphic",
"esri/symbols/PictureMarkerSymbol",
"esri/symbols/TextSymbol",
"esri/geometry/Point",
"esri/dijit/Scalebar",
"dojo/_base/unload",
"dojo/cookie",
"dojo/json",
"esri/config",
"esri/IdentityManager",
"esri/layers/FeatureLayer",
"dojo/domReady!"
], function (
parser,
ready,
BorderContainer,
ContentPane,
dom,
Map,
urlUtils,
arcgisUtils,
Legend,
LayerList,
Graphic,
PictureMarkerSymbol,
TextSymbol,
Point,
Scalebar,
baseUnload,
cookie,
JSON,
esriConfig,
esriId,
FeatureLayer
) {
var mapOptions = {
basemap: "topo",
autoResize: true, // see http://forums.arcgis.com/threads/90825-Mobile-Sample-Fail
center: [currentPosition.lng, currentPosition.lat],
zoom: 15,
logo: false
};
// cookie/local storage name
var cred = "esri_jsapi_id_manager_data";
// store credentials/serverInfos before the page unloads
baseUnload.addOnUnload(storeCredentials);
// look for credentials in local storage
loadCredentials();
parser.parse();
esriConfig.defaults.io.proxyUrl = "/proxy/";
//Create a map based on an ArcGIS Online web map id
arcgisUtils.createMap('PUT-YOUR-ESRI-KEY', "esriMapCanvas", { mapOptions: mapOptions }).then(function (response) {
var map = response.map;
// add a blue marker
var picSymbol = new PictureMarkerSymbol(
'http://static.arcgis.com/images/Symbols/Shapes/RedPin1LargeB.png', 50, 50);
var geometryPoint = new Point('SET YOUR LAT', 'SET YOUR LONG');
map.graphics.add(new Graphic(geometryPoint, picSymbol));
//add the scalebar
var scalebar = new Scalebar({
map: map,
scalebarUnit: "english"
});
//add the map layers
var mapLayers = new LayerList({
map: map,
layers: arcgisUtils.getLayerList(response)
}, "esriLayerList");
mapLayers.startup();
//add the legend. Note that we use the utility method getLegendLayers to get
//the layers to display in the legend from the createMap response.
var legendLayers = arcgisUtils.getLegendLayers(response);
var legendDijit = new Legend({
map: map,
layerInfos: legendLayers
}, "esriLegend");
legendDijit.startup();
});
function storeCredentials() {
// make sure there are some credentials to persist
if (esriId.credentials.length === 0) {
return;
}
// serialize the ID manager state to a string
var idString = JSON.stringify(esriId.toJson());
// store it client side
if (supports_local_storage()) {
// use local storage
window.localStorage.setItem(cred, idString);
// console.log("wrote to local storage");
}
else {
// use a cookie
cookie(cred, idString, { expires: 1 });
// console.log("wrote a cookie :-/");
}
}
function supports_local_storage() {
try {
return "localStorage" in window && window["localStorage"] !== null;
} catch (e) {
return false;
}
}
function loadCredentials() {
var idJson, idObject;
if (supports_local_storage()) {
// read from local storage
idJson = window.localStorage.getItem(cred);
}
else {
// read from a cookie
idJson = cookie(cred);
}
if (idJson && idJson != "null" && idJson.length > 4) {
idObject = JSON.parse(idJson);
esriId.initialize(idObject);
}
else {
// console.log("didn't find anything to load :(");
}
}
});

Using WebRTC getStat() API

Hey I am trying to implement the getstat API in my WebRTC application. Im finding it hard to get any tutorials at all , at a beginners level.
My Application
I created a 2 person chat-room using the peer js framework. so in my application I am using what can be described a "Sneeker-net" for signaling , ie I am manually sharing a peer id with the person I want a chat with via giving them my id in a email lets say then they call that ID . it uses the stun and turn servers to make our connections its a simple peer to peer chat with Html5 and JavaScript which uses the peerjs API.
here is my HTML 5 AND Javascript code
HTML5 code
<html>
<head>
<title> PeerJS video chat with manual signalling example</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.peerjs.com/0.3/peer.js"></script>
<script type="text/javascript" src="ps-webrtc-peerjs-start.js ></script>
</head>
<body>
<div>
<!-- Video area -->
<div id="video-container">
Your Friend<video id="their-video" autoplay class="their-video"></video>
<video id="my-video" muted="true" autoplay class="my-video"></video> You
</div>
<!-- Steps -->
<div>
<h2> PeerJS Video Chat with Manual Signalling</h2>
<!--Get local audio/video stream-->
<div id="step1">
<p>Please click 'allow' on the top of the screen so we can access your webcam and microphone for calls</p>
<div id="step1-error">
<p>Failed to access the webcam and microphone. Make sure to run this demo on an http server and click allow when asked for permission by the browser.</p>
Try again
</div>
</div>
<!--Get local audio/video stream-->
<!--Make calls to others-->
<div id="step2">
<p>Your id: <span id="my-id">...</span></p>
<p>Share this id with others so they can call you.</p>
<p><span id="subhead">Make a call</span><br>
<input type="text" placeholder="Call user id..." id="callto-id">
Call
</p>
</div>
<!--Call in progress-->
<!--Call in progress-->
<div id="step3">
<p>Currently in call with <span id="their-id">...</span></p>
<p>End call</p>
</div>
</div>
</div>
</body>
</html>
My Javascript file
navigator.getWebcam = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
// PeerJS object ** FOR PRODUCTION, GET YOUR OWN KEY at http://peerjs.com/peerserver **
var peer = new Peer({
key: 'XXXXXXXXXXXXXXXX',
debug: 3,
config: {
'iceServers': [{
url: 'stun:stun.l.google.com:19302'
}, {
url: 'stun:stun1.l.google.com:19302'
}, {
url: 'turn:numb.viagenie.ca',
username: "XXXXXXXXXXXXXXXXXXXXXXXXX",
credential: "XXXXXXXXXXXXXXXXX"
}]
}
});
// On open, set the peer id so when peer is on we display our peer id as text
peer.on('open', function() {
$('#my-id').text(peer.id);
});
peer.on('call', function(call) {
// Answer automatically for demo
call.answer(window.localStream);
step3(call);
});
// Click handlers setup
$(function() {
$('#make-call').click(function() {
//Initiate a call!
var call = peer.call($('#callto-id').val(), window.localStream);
step3(call);
});
$('end-call').click(function() {
window.existingCall.close();
step2();
});
// Retry if getUserMedia fails
$('#step1-retry').click(function() {
$('#step1-error').hide();
step();
});
// Get things started
step1();
});
function step1() {
//Get audio/video stream
navigator.getWebcam({
audio: true,
video: true
}, function(stream) {
// Display the video stream in the video object
$('#my-video').prop('src', URL.createObjectURL(stream));
// Displays error
window.localStream = stream;
step2();
}, function() {
$('#step1-error').show();
});
}
function step2() { //Adjust the UI
$('#step1', '#step3').hide();
$('#step2').show();
}
function step3(call) {
// Hang up on an existing call if present
if (window.existingCall) {
window.existingCall.close();
}
// Wait for stream on the call, then setup peer video
call.on('stream', function(stream) {
$('#their-video').prop('src', URL.createObjectURL(stream));
});
$('#step1', '#step2').hide();
$('#step3').show();
}
Many thanks to anybody who takes time out to help me I am very grateful, as Im only a beginner at WebRTC .
Cheers
Here is my code, which works in both Chrome and Firefox. It traces stats in the browser console. Because Chrome stats are very verbose, I filter them following an arbitrary criteria (statNames.indexOf("transportId") > -1):
function logStats() {
var rtcPeerConn = ...;
try {
// Chrome
rtcPeerConn.getStats(function callback(report) {
var rtcStatsReports = report.result();
for (var i=0; i<rtcStatsReports.length; i++) {
var statNames = rtcStatsReports[i].names();
// filter the ICE stats
if (statNames.indexOf("transportId") > -1) {
var logs = "";
for (var j=0; j<statNames.length; j++) {
var statName = statNames[j];
var statValue = rtcStatsReports[i].stat(statName);
logs = logs + statName + ": " + statValue + ", ";
}
console.log(logs);
}
}
});
} catch (e) {
// Firefox
if (remoteVideoStream) {
var tracks = remoteVideoStream.getTracks();
for (var h=0; h<tracks.length; h++) {
rtcPeerConn.getStats(tracks[h], function callback(report) {
console.log(report);
}, function(error) {});
}
}
}
}
You need the rtcPeerConnection, and Firefox requires the stream in addition.
for twilio SDK look at this post:
Is there an API for the chrome://webrtc-internals/ variables in javascript?
var rtcPeerConn =Twilio.Device.activeConnection();
rtcPeerConn.options.mediaStreamFactory.protocol.pc.getStats(function callback(report) {
var rtcStatsReports = report.result();
for (var i=0; i<rtcStatsReports.length; i++) {
var statNames = rtcStatsReports[i].names();
// filter the ICE stats
if (statNames.indexOf("transportId") > -1) {
var logs = "";
for (var j=0; j<statNames.length; j++) {
var statName = statNames[j];
var statValue = rtcStatsReports[i].stat(statName);
logs = logs + statName + ": " + statValue + ", ";
}
console.log(logs);
}
}
});
I advice you to read Real-Time Communication with WebRTC for O'Reilly
It is very useful book for beginners in addition the book will guide you to build your webchat application ste by step using sokcet.io for signaling
the link in the first comment

Youtube javascript api, pjax, how to reload onYouTubeIframeAPIReady();

I have a problem with the youtube javascript player api.
I call this js code :
function onYouTubeIframeAPIReady() {
var podcast = document.getElementById('podcast')
var player = new YT.Player( document.getElementById('podcast'));
player.addEventListener('onStateChange', function(e) {
if (e.data === 1) {
alert("play");
}
});
};
with this html code :
<iframe id="podcast" type="text/html" width="720" height="405"
src="https://www.youtube.com/embed/XXXXXX?cc_load_policy=1&enablejsapi=1&theme=light"
frameborder="0" allowfullscreen>
The problem is that I use the pjax system, so the global javascript code is not reloaded when I navigate.
So, I reload some part of my javascript code when pjax:success. I tried something like this :
$(document).on('pjax:success', function() {
onYouTubeIframeAPIReady();
}
but it doesn't work. My question is how to reload onYouTubeIframeAPIReady(); when it must to be defined globally as it is said there onYouTubeIframeAPIReady function is not calling
When my player is defined I don't use onYoutubePlayerAPIReady. It's the best solution I find, and it works.
var player = {
playVideo: function(container, videoId) {
if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
window.onYouTubePlayerAPIReady = function() {
player.loadPlayer(container, videoId);
};
$.getScript('//www.youtube.com/player_api');
} else {
player.loadPlayer(container, videoId);
}
},
loadPlayer: function(container, videoId) {
window.myPlayer = new YT.Player(container,
height: 200,
width: 200,
videoId: videoId,
});
}
};
var containerId = 'podcast';
var videoId = '<%= #youtube_id %>';
player.playVideo(containerId, videoId);