I'm working on trying to trigger an event (to unhide an alert or image) based on gps coordinates falling within a certain range.
I think I need to do something like: If GPS Lat is > x (set based on location I want them to go to) and < y & GPS Long is > z and < a, then show (use js change css to display: block).
Am I down the right path? I'll post what I have as the basics of getting the GPS coordinates to just appear. I'm learning as I go here, so any help is appreciated for the proper structure. Thank you.
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// device APIs are available
//
function onDeviceReady() {
var options = { timeout: 100000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
UPDATE:
I have gotten to the point where I'm not getting errors, now I'm hoping for some help to get a heading based on my current location and the destination. Any help is greatly appreciated. I'm posting my current code below:
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
var gpscoord = null;
var destLat = 37.200401
var destLon = 93.278610
function onDeviceReady() {
var gpsOptions = { timeout: 5000 };
gpscoord = navigator.geolocation.getCurrentPosition(gpsSuccess, gpsError, gpsOptions);
}
//gpsSuccess
//
function gpsSuccess(position) {
var lat = document.getElementById('latitude');
var lon = document.getElementById('longitude');
lat.innerHTML = 'Latitude:' + position.coords.latitude;
lon.innerHTML = 'Longitude:' + position.coords.longitude;
document.getElementById('gotoLat').innerHTML = 'Destination Latitude: ' + destLat;
document.getElementById('gotoLon').innerHTML = 'Destination Longitude: ' + destLon;
}
function gpsError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
<div class="container">
<br/>
<br/>
<p id="latitude">Watching latitude...</p>
<p id="longitude">Watching longitude...</p>
<br/>
<p id="gotoLat">Destination latitude...</p>
<p id="gotoLon">Destination longitude...</p>
</div>
Yeah that looks fine. The watcher will call onSuccess when the GPS has been successfully polled, and returns data.
I would save the Longitude and Latitude in the global scope, and then you can perform what ever kind of logic you want on it.
Related
<!DOCTYPE html>
<html>
<head>
<title> Location Test </title>
<link rel="shortcut icon" href="#">
</head>
<body>
<h1> Location </h1>
<label id = "Address"> </label>
<br>
<input type="button" value="Log Out" id="LogOut">
<script>
const logoutButton = document.getElementById("LogOut");
function getLocation() {
navigator.geolocation.getCurrentPosition(
function(Position) {
var currentdate = new Date();
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + "Last Sync: " + currentdate.getDate() + "/" +
(currentdate.getMonth() + 1) + "/" +
currentdate.getFullYear() + ". " +
currentdate.getHours() + ":" +
currentdate.getMinutes() + "." +
currentdate.getSeconds() + ". ";
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + "Latitude: " + Position.coords.latitude;
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + " Longitude: " + Position.coords.longitude;
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + " Accuracy: " + Position.coords.accuracy;
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + " Heading towards direction: " + Position.coords.heading;
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + " Speed: " + Position.coords.speed;
var api_key = '206170168bcf4fdf905d85a34f7b3d79';
var latitude = Position.coords.latitude;
var longitude = Position.coords.longitude;
var api_url = 'https://api.opencagedata.com/geocode/v1/json'
var request_url = api_url +
'?' +
'key=' + api_key +
'&q=' + encodeURIComponent(latitude + ',' + longitude) +
'&pretty=1' +
'&no_annotations=1';
var request = new XMLHttpRequest();
request.open('GET', request_url, true);
request.onload = function() {
if (request.status === 200) {
// Success!
var data = JSON.parse(request.responseText);
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + " Address: " + data.results[0].formatted; // print the location
} else if (request.status <= 500) {
// We reached our target server, but it returned an error
console.log("unable to geocode! Response code: " + request.status);
var data = JSON.parse(request.responseText);
console.log('error msg: ' + data.status.message);
} else {
console.log("server error");
}
};
request.onerror = function() {
console.log("unable to connect to server");
};
request.send(); // make the request
},
function(PositionError) {
document.getElementById("Latitude").innerHTML = "Could not get latitude";
document.getElementById("Longitude").innerHTML = "Could not get longitude";
})
}
getLocation();
setInterval(getLocation, 1000 * 60 * 5)
logoutButton.addEventListener("click", (e) => {
e.preventDefault();
window.location.href = "login.html";
})
</script>
</body>
</html>
So basically, what I want to do is create a new line at the end of the function. So each time I use setInterval, it creates a new line in the label. But I'm not sure how to. That way, every time it updates the location after 5 minutes, it prints it on a new line.
You can ignore the rest of what I say, I'm getting the error that my post is mostly code.
Just write a <br> tag. So change
+ " Address: "
to:
+ "<br> Address: "
As trincot stated, the inclusion of the <br> (line break) tag is the way to go as we want to create new lines directly in the address label. However, a code change is required because our newly appended line breaks will get rewritten when we re-call function getLocation().
Appended line breaks will vanish if we reinitialise our label's innerHTML with its previous textContent because textContent selects the message from the target and ignores nested HTML contents.
Thus, the best solution is to formulate the location before its inclusion to the address label.
// Get local date and time.
var currentdate = new Date();
var cd_date = currentdate.toLocaleDateString("en-UK");
var cd_time = currentdate.toLocaleTimeString("en-UK");
// Formulate location string.
var location = `
Last Sync: ${cd_date} - ${cd_time},
Latitude: ${Position.coords.latitude},
Longitude: ${Position.coords.longitude},
Accuracy: ${Position.coords.accuracy},
Heading towards direction: ${Position.coords.heading},
Speed: ${Position.coords.speed},
`.replace(/\s{2}/g, '').trim(); // Remove additional spaces.
...
if (request.status === 200) {
// Success!
var data = JSON.parse(request.responseText);
location += ` Address: "${data.results[0].formatted}".`;
// print the location
var elm_address = document.getElementById("Address");
elm_address.innerHTML += (elm_address.innerHTML.trim().length > 0) ? `<br>${location}` : location;
}
We want to include line breaks when we append additional location to the address label, so I decided to have a conditional statement before appending stage.
elm_address.innerHTML += will append the location after
following condition (elm_address.innerHTML.trim().length > 0).
The condition checks if address label is empty.
? `<br>${location}` : location;
When the condition's result is negative, location is appended without a line break. Otherwise, a line break is included.
I've edited the example for Geolocation in Cordova to do something (in this case an alert) if the user is up a certain latitude there is an alert, if not another alert. But it doesn't work. Can someone Help me?
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// device APIs are available
//
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = {
maximumAge: 15000,
timeout: 30000,
enableHighAccuracy: true
};
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
if (position.coords.latitude > 44.48) {
alert("Hi Wayne");
} else if {
alert("Hi Bill");
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
hello there i have following code from google geoloction api..
this api is fetching an image of the current location of mine..
what i need to do is display these coordinates in google map(not in an image)
code is as follow:
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation) {
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
};
function error() {
output.innerHTML = "Unable to retrieve your location";
};
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
your help will be appreciated !
Here is a Plunker to help you out! Just fill up the needed data on the iframe with yours and it will work. But instead of setting it to the img src you need to append it to the html.
I'm attempting to modify a Google maps API v3 direction script. I thought I had a firm grasp of combining variables etc but then I ran into this problem:
function calcRoute() {
var end = document.getElementById("start").value;
var street = document.getElementById("street").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var zip = document.getElementById("zip").value;
var start = street + ' ' + city + ' ' + state + ' ' + zip;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
If I create an input with an id of start and change
var start = document.getElementById("start").value;
the script works again. however I can't get my combined variable to work:
var start = street + ' ' + city + ' ' + state + ' ' + zip;
if i make a button to alert(start) it returns null... what am I doing wrong?
Update: Also of note,
if I run:
onClick="alert(end)"
while
<input id="end" name="destination" type="hidden" value="test" />
the alert returns "object HTMLInputElement" not "test" as it should.
If you want to alert the value of the "end" input you need to do:
onClick="alert(document.getElementById('end').value)"
As for your start being null problem, I don't believe that one of the variables was null, if I try this:
null + " " + null
I get "null null" (tested both on chrome and firefox).
And so, my question is: where do you try to access the "start" variable from? Is it from inside the function in which it was defined in or outside of it? You can't access that variable from outside the calcRoute function.
So if you are doing something like:
<input type="button" onclick="alert(start)" />
It's bound to fail, instead do something like this:
var start;
function calcRoute() {
var end = document.getElementById("start").value;
var street = document.getElementById("street").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var zip = document.getElementById("zip").value;
start = street + ' ' + city + ' ' + state + ' ' + zip;
.....
I'm not the best with Javascript and I seem to have got stuck.
I have a map in place and I need the Lat/Long for a location (that's fine) but the output comes in an alert box. I just need the values themselves.
E.g document.write(latt); document.write(longg);
At the moment this is the code that outputs the box:
function showPointLatLng(point)
{
alert("Latitude: " + point.lat() + "\nLongitude: " + point.lng());
}
Any help would be great, Thanks!
P.S
I think this is the controller:
function usePointFromPostcode(postcode, callbackFunction) {
localSearch.setSearchCompleteCallback(null,
function() {
if (localSearch.results[0])
{
var resultLat = localSearch.results[0].lat;
var resultLng = localSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
callbackFunction(point);
}else{
alert("Postcode not found!");
}
});
localSearch.execute(postcode + ", UK");
}
Looks like you can swap the showPointLatLng call with:
document.write( point.lat() + "," + point.lng() );
As lat/long come from calls to methods of the existing point object.
If you are asking how to make that work...
function showPointLatLng(point) {
document.write("Latitude: " + point.lat() + "\nLongitude: " + point.lng());
}
// Eg, ...
showPointLatLng({
lat : function(){ return 98; }
lng : function(){ return 42; /*the meaning of life!*/ }
});
Instead of document.write you could do something like this:
var info = document.createElement('div');
info.innerHTML = point.lat() + "," + point.lng();
document.body.appendChild(info);