store users geolocation in 30 second intervals - javascript

I'm trying to figure out how I can refactor my code so that I can send a user's geolocation to my MySQL database in 30 second intervals.
This code below store's a users geolocation in the table only when the application is loaded or if the application is refreshed but It does not continuously store the geolocation as the person travels. I am looking to send the users geolocation to the server periodically in 30 second bursts.
I am aware of jquery setInterval and have tried to nest it in several places without success as javascript is rusty.
Any steering would be greatly appreciated.
My Table Schema
heatmap.php
<?php require_once("../resources/config.php"); ?>
<!DOCTYPE html>
<html>
<head>
<title>FOX COUNT</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="css/heatmapstyle.css">
<style>
/* NOTE: GOOGLE MAPS NEEDS HTTPS TO WORK. IT WILL NOT WORK WITH HTTP AKA UNSECURE ORIGIN */
#map {
height: 100%;
}
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map">
<!--Google map will be embedded here-->
</div>
<script>
var map, currentPositionMarker, map;
function initializeMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
});
}
function locError(error) {
// tell the user if the current position could not be located
alert("The current position could not be found!");
}
// current position of the user
function setCurrentPosition(pos) {
currentPositionMarker = new google.maps.Marker({
label: {
color: 'black',
fontWeight: 'bold',
text: 'CD',
},
map: map,
position: new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude,
),
title: "Current Position"
});
var a = pos.coords.latitude;
var b = pos.coords.longitude;
console.log(a, b);
// This ajax command stores the lat and lang into the db ONLY when the app loads from fresh or if the app refreshes. It DOES NOT continously store the users geolocation when ever the user marker changes geolocation. !!!
$.ajax({
type: "GET",
url: "personlocator.php",
data: {
a: a,
b: b
}
})
map.panTo(new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
));
} // end of function ///////////////////////////
function watchCurrentPosition(pos) {
var positionTimer = navigator.geolocation.watchPosition(
function(position) {
setMarkerPosition(
currentPositionMarker,
position
);
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setCurrentPosition, watchCurrentPosition, locError);
} else {
// tell the user if a browser doesn't support this amazing API
alert("Your browser does not support the Geolocation API!");
}
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_IS_NESTED_HERE&libraries=visualization&callback=initLocationProcedure">
</script>
<!--javascript and jquery CDN's directly beneath here-->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
</body>
</html>
personlocator.php
if (isset($_GET['a'], $_GET['b'])) {
$latitude = escape_string($_GET['a']);
$longitude = escape_string($_GET['b']);
$updateQuery = $mysqli->query("UPDATE users
SET user_latitude='$latitude'
, user_longitude='$longitude'
WHERE id= '{$id}' ");
mysqli_query($connection,$updateQuery);
confirm($updateQuery);
redirect("personlocator.php");
}

You can nest it like this:
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
// Timer with setInterval
var timer = setInterval( function() {
navigator.geolocation.getCurrentPosition(setCurrentPosition, locError);
}, 30000);
} else {
// tell the user if a browser doesn't support this amazing API
alert("Your browser does not support the Geolocation API!");
}
}

Related

Mapbox GL JS - Reverse Geocoding with coordinates

I have a map done on mapbox gl js.
I'm trying to get a placename / address by reverse geocoding longitude and latitude coordinates.
I can manage to get normal forward geocoding to work but querying the following (for example):
geocoder.query('New York')
But i cant quite figure out how to do this in reverse with coordinates. I've tried the following to no avail:
// geocoder.query(126.981,37.539)
// geocoder.query("126.981,37.539")
// geocoder.query(37.539,126.981)
// geocoder.query("37.539,126.981")
I couldnt find anything in the documents to point me in the right direction as well. Thus any help is greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Set a point after Geocoder result</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.49.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.49.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
.built_address {
position: fixed;
top: 0;
left: 0;
background-color: white;
padding: 10px;
font-size: 12px;
font-family: Arial;
}
</style>
</head>
<body>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.3.0/mapbox-gl-geocoder.min.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.3.0/mapbox-gl-geocoder.css' type='text/css' />
<style>
#geocoder-container > div {
min-width:50%;
margin-left:25%;
}
</style>
<div id='map'></div>
<div class="built_address">LOREM IPSUM</div>
<script>
var built_address = '';
var user_coordinates;
var geocode_results;
mapboxgl.accessToken = 'pk.eyJ1IjoiZmFyaXNrYXNzaW0iLCJhIjoiSk1MaUthdyJ9.vkxtdDbYdLi524WwlKORBw';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/fariskassim/cjmszx78b266o2rlar02ytynj',
center: [127.017768, 37.59837],
zoom: 12
});
var geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken
});
map.addControl(geocoder);
// After the map style has loaded on the page, add a source layer and default
// styling for a single point.
map.on('load', function() {
map.addSource('single-point', {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": []
}
});
map.addLayer({
"id": "point",
"source": "single-point",
"type": "circle",
"paint": {
"circle-radius": 10,
"circle-color": "#007cbf"
}
});
getUserLocation();
});
function getUserLocation() {
// request to allow user position
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) {
// get user current coordinates and center map on coordiates
console.log('L2', position)
//console.log(position.coords.latitude, position.coords.latitude)
user_coordinates = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
// draw user location on mao
map.getSource('single-point').setData({type: "Point", coordinates: [user_coordinates.lng,user_coordinates.lat]});
// geocoder.query(user_coordinates.lat, user_coordinates.lng)
// Listen for the `result` event from the MapboxGeocoder that is triggered when a user
// makes a selection and add a symbol that matches the result.
geocoder.on('result', function(ev) {
map.getSource('single-point').setData(ev.result.geometry);
console.log('ev',ev)
built_address = ev.result.place_name
});
}
} else {
// if device doesnt support location
console.log('device doesnt support location')
}
}; /* END getUserLocation(); */
</script>
</body>
</html>
Try geocoder.mapboxClient.geocodeReverse:
geocoder.mapboxClient
.geocodeReverse({
latitude: user_coordinates.lat,
longitude: user_coordinates.lng
}, function(err, res) {
console.log(err, res)
});
Update
mapbox-gl-geocoder v5.0.0
You have to create a geocoder with reverse geocoding enabled :
let geocoder = new MapboxGeocoder({
accessToken:mapboxgl.accessToken,
mapboxgl:mapboxgl,
reverseGeocode:true
})
Then you will be able to do :
geocoder.query("126.981,37.539")
...
Be aware that the default coordinates format is lat,lng but you can invert it with the options.flipCoordinates

Adding multiple markers with Google Maps API [duplicate]

This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Closed 4 years ago.
I am trying to use Google maps API for a website and I can't seem to get multiple locations to populate like Google has it in their example.
Could anyone please let me know what I need to add to get 11 markers to show up that will give a description of what I want.
I can see that Google has multiple locations giving a quick description of what they are.
PS: I already have a key I just need to know how to include "X" number of markers with a description attached.
Attached is the link to googles example:
Google Maps API
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
function initMap() {
var pyrmont = {lat: -33.867, lng: 151.195};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
</script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
</body>
</html>
You need to try this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

Making a map using google maps in node.js

I am trying to create a map in node.js by calling my javascript file to do it for me.
require('./js/file.js')();
initMap();
This didn't work, as it gave me an error that "google was undefined" in my initMap() function. So, I tried to require the api script itself:
require('https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places')();
require('./public/js/graphs.js')();
initMap();
which also, unsurprisingly, didn't work. How can I fix this? I tried loading in the map api inside the javascript file itself, but that required jquery, which also wasn't defined either, and so on.
You are trying to initialize the Google Maps JS which is designed for Browsers, not for Node, so that's why you get a "undefined" response.
I made this work by using PhantomJS; You create a "html template" where you have your map, initialize the map, then draw whatever you have to draw, and you can save it as PDF/Image with PhantomJS.
There is an example:
The "PhantomJS Script"
var page = require('webpage').create();
var system = require('system');
var args = system.args;
var fs = require('fs');
page.paperSize = {
format: 'A4',
orientation: 'portrait',
margin: '0mm'
};
var path = args[1];
var code = args[2];
page.open(path + '/imageMap.html', function(status) {
page.dpi = 96.0;
status = status.trim();
console.log(status);
if(status === "success") {
var title = page.evaluate(function(code) {
window.generateMap(code);
return true;
}, code);
setTimeout(function(){
page.render(path + '/img/' + code + '.png');
phantom.exit();
}, 1500);
}else{
phantom.exit(1);
}
});
As you can see, i give a 1500ms in the setTimeout, its just to make sure that the map was loaded and finished drawing (maybe there's a better way, but, it works)
And your imageMap.html is whatever you are doing with GMaps, like using the sample file from the docs:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
width: 100%;
height: 100%;
margin:0px;
paddin:0px;
}
#map_canvas{
width:600px;
height: 445px;
}
.gm-style-cc {
display:none;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
</body>
</html>
I hope this helps somebody.
jQuery and other front end libraries don't work the same in nodejs. You'll want to look into a nodejs client for the google maps API.
This one is provided by google.

Opening media from google maps custom marker

So I'm working on a custom google maps tour type application and I'm wondering how to get media to popup when I click a link within a google maps marker. Ideally this is what I would like to happen:
1. User clicks on marker and the normal white box comes up like on real Google Maps.
2. Within that text box I would like to have a button that will launch media that I have stored on a SQL server somewhere. This media could be audio, pictures, or video.
The code I have so far is below. If anyone could let me know how to do this, or point me in the right direction that would be awesome!
Thanks
<!doctype html>
<html>
<head>
<title>HuskyWalk Application Demo</title>
<meta name="viewport" conmtent="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #mapcanvas {
margin: 0;
padding: 0;
height: 98%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
var iteCoords = new google.maps.LatLng(41.806501, -72.252769);
//var mapCoords = new google.maps.LatLng(navigator.getCurrentPosition().coords.latitude, navigator.getCurrentPosition().coords.longitude);
//var mapCoords = new navigator.getCurrentPosition().coords;
function initialize() {
//var position = new navigator.geolocation.getCurrentLocation(showPosition);
var mapOptions = {
zoom: 18,
center: iteCoords,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);
google.maps.event.addListenerOnce(map, "bounds_changed", watchStart);
var marker = createMarker(); //creates marker
}
function watchStart() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function createMarker() {
var marker = new google.maps.Marker({
position: iteCoords,
map: map,
title: 'ITEB',
});
google.maps.event.addListener(marker, "click", onMarker_clicked);
return marker;
}
function onMarker_clicked() {
alert(this.get('id'));
}
</script>
</head>
<body onload="initialize()">
<div id="mapcanvas"></div>
<div>
<p>Maps provided by Google Maps</p>
</div>
</body>
</html>
I know there is going to need to be some stuff in the onMarker_Clicked() method most likely, I'm just not sure what.
You'll want to use an InfoWindow and call its open() method from the click event handler.
See also the section in the google maps developer guide https://developers.google.com/maps/documentation/javascript/overlays#InfoWindows

I can't get the Google's Places Service's output

In my code, first, I am trying to find the user's location by GeoLocation service on the Google Maps.
Second, I am trying to show 'Bars', like places you go to drink alcohol, with the Google's Places Service near users location. It should put markers on 'Bars' near users location.
However this doesn't work, I am encountering a problem. But I don't know what it is. It opens the map without 'Bars' near my location.
My css code:
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
#media print {
html, body {
height: auto;
}
#map_canvas {
height: 650px;
}
}
This is my javascript and my HTML code=
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Map Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<link href="mapcss.css" rel="stylesheet" type="text/css">
<!--
Include the maps javascript with sensor=true because this code is using a
sensor (a GPS locator) to determine the user's location.
See: http://code.google.com/apis/maps/documentation/javascript/basics.html#SpecifyingSensor
-->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var map;
function initialize() {
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
var request = {
location: pos,
radius: 500,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
},
function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(45.4643898,9.1883469),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
A Google Places search can often come up empty, especially considering how sparse the Google Places database is at the current time (or was the last time I tried it). See Google Maps Javascript API V3 : Search Requests for some extra details and suggestions.

Categories