How do I get the city name out of this? - javascript

I hhave this in the html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Geolocation</title>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script src="funciones.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body>
<button id="startGeo">Click here to check your geolocation abilities</button>
</body>
</html>
and I have this in a function.js file:
$(document).ready(function(){
$("#startGeo").click(checkLocation);
function checkLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getLocation,locationFailed);
//document.write("you have geolocation");
}
else {
document.write("you don't have geolocation");
}
}//ends checkLocation()
function getLocation(position){
var latitud = position.coords.latitude;
var longitud = position.coords.longitude;
var exactitud = position.coords.accuracy;
alert("latitud: " + latitud + " longitud: " + longitud + " exactitud: " + exactitud);
//document.write("we received your location");
}
function locationFailed(){
document.write("we didn't get your location. Please check your settings");
}
});
from this I get the coordinates, but I have no idea at all on how to get the city name... or the state name. I saw a question similar to this answered but they seemed to be using json. I don't want a map, just the info, it can be text or an alert. Please any ideas?

You can use reverse Geocoding API
Sample call:
http://maps.googleapis.com/maps/api/geocode/json?latlng=50.123413,-22.12345&sensor=true
You can replace your getLocation function like that (make appropriate tests before accessing data.results[2]):
function getLocation(position){
var latitud = position.coords.latitude;
var longitud = position.coords.longitude;
var exactitud = position.coords.accuracy;
$.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitud + ',' + longitud + '&sensor=true', function(data) {
alert(data.results[2].address_components[0].long_name);
});
//alert("latitud: " + latitud + " longitud: " + longitud + " exactitud: " + exactitud);
//document.write("we received your location");
}
You can check the following fiddle to see it in action:
https://jsfiddle.net/5tzxks10/

+Nowres Rafed I changed your code a little bit:
function getLocation(position){
var latitud = position.coords.latitude;
var longitud = position.coords.longitude;
var exactitud = position.coords.accuracy;
$.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitud + ',' + longitud, function(data) {
alert(data.results[1].formatted_address);
});
//alert("latitud: " + latitud + " longitud: " + longitud + " exactitud: " + exactitud);
//document.write("we received your location");
it gives more information that way. Thank you so much. What I would like to know (if it's possible) is where can I read or know how to fetch a specific answer, I read that when you get the results, it returns more than one result. I changed the number as you mentioned, testing the different options. But, is there somewhere where I can look for those results? forgive the bother, I'm just new to this.

Related

navigator.geolocation.watchPosition - frequency

I tried this code :
<!DOCTYPE html>
<html>
<head>
<title>Location Location Location</title>
<script type="text/javascript" charset="utf-8">
var watchID = null;
// PhoneGap is ready
//
function f() {
// Update every 1 ms seconds
var options = {enableHighAccuracy: true,timeout: 5000,maximumAge: 0,desiredAccuracy: 0, frequency: 1 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var str = 'Latitude: ' + position.coords.latitude + '<br>' +
'Longitude: ' + position.coords.longitude + '<br>' +
'Timestamp: ' + position.timestamp + '<br>' ;
var url = "load.php";
var params = "data="+str;
xmlhttp.open("GET", url+"?"+params, true);
document.body.innerHTML += str;
document.writeln("line 33");
xmlhttp.send();
//document.writeln("send");
//document.writeln(str);
}
// clear the watch that was started earlier
//
function clearWatch() {
if (watchID != null) {
navigator.geolocation.clearWatch(watchID);
watchID = null;
}
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body>
<p id="geolocation">Watching geolocation...</p>
<button onclick="f();"> Watch</button>
</body>
</html>
you can see that i add
var options = {......, frequency: 1 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
But I am getting new result if and only if I enter to tab and exit and enter agin.
What can I do?
The spec makes no mention of a frequency option which suggests that this parameter is being ignored. W3C Geolocation spec
You code seems to be working fine: http://jsfiddle.net/Mgk9J/1/
I tested it in Android and when I move the cellphone new lines came up. However in chrome desktop it plots new lines when I change tabs even though they're identical to the last ones, according to the spec this isn't the correctly behavior.
It makes a bit of sense for the desktop version do not plot new lines anyway, the computer isn't moving so new success calbacks execution should not be fired.
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="/js/lib/dummy.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
</style>
<script type="text/javascript">//<![CDATA[
window.onload=function(){
var watchID = null;
// PhoneGap is ready
//
function f() {
// Update every 1 ms seconds
var options = {enableHighAccuracy: true,timeout: 5000,maximumAge: 0,desiredAccuracy: 0, frequency: 1 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var str = 'Latitude: ' + position.coords.latitude + '<br>' +
'Longitude: ' + position.coords.longitude + '<br>' +
'Timestamp: ' + position.timestamp + '<br>\r\n' ;
document.getElementById('result').value += str;
}
// clear the watch that was started earlier
//
function clearWatch() {
if (watchID != null) {
navigator.geolocation.clearWatch(watchID);
watchID = null;
}
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
document.getElementById('button').addEventListener('click', f);
}//]]>
</script>
</head>
<body>
<p id="geolocation">Watching geolocation...</p>
<button id="button"> Watch</button>
<textarea id="result" cols="100" rows="10"></textarea>
</body></html>

how to append to div id

i know it is easy and silly question but how can i show the lat and lng append into div id instead of giving me on alert.Can i do something like that !!
document.getElementById("here").innerHTML = ("lat: +lat+"lng: " + lng)
<!DOCTYPE>
<html>
<meta name="viewport" content="width=device-width,
initial-scale=1, maximum-scale=1,user-scalable=no">
<head>
<script>
function geolocation(){
<!--checks if geolocation is available -->
var options = { enableHighAccuracy: true};
watchId = navigator.geolocation.watchPosition(onSuccess, onError, options);
<!-- function run if gets the geolocation back -->
function onSuccess(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
alert("lat: " + lat + "lng: " + lng);
}
<!-- this function run if there is any error in geolocation -->
function onError(error){
alert("message: " + error.message);
}
}
geolocation();
</script>
</head>
<body>
<div id="here"></div>
</body>
You may try something like this: Edit: Updated HTML
<div id="location"></div>
<script>
$( document ).ready(function() {
geolocation();
}
function geolocation(){
<!--checks if geolocation is available -->
var options = { enableHighAccuracy: true};
watchId = navigator.geolocation.watchPosition(onSuccess, onError, options);
<!-- function run if gets the geolocation back -->
function onSuccess(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//alert("lat: " + lat + "lng: " + lng);
document.getElementById("location").innerHTML = "lat: " + lat + "lng: " + lng;
}
<!-- this function run if there is any error in geolocation -->
function onError(error){
alert("message: " + error.message);
}
}
</script>
Ok So, I think what you want is this:
div = document.getElementById('here');
div.appendChild(watchId);
Thats how you append to your particular div.
Yes, it's possible, with the property innerHTML you wrote you should solve your problem.
Yes, you definetely can. However, the string you provided is not quoted correctly. Don' t you get an exception in console?
document.getElementById("here").innerHTML = "lat: " + lat + "lng: " + lng;
Using jQuery you can simply do this:
$("#here").text("lat: " + lat + " lng: " + lng");
Or if you want to keep the content of here and append the information at the end:
$("#here").append("lat: " + lat + " lng: " + lng");

Cordova: HTML5 geolocation - find the nearest place from JavaScript array

I have array of places in JavaScript. I need to get gps geolocation from gps sensor (on mobile phone using Apache Cordova).
If GPS accuracy is better than for example 40 meters, I need to do something (set css display:block, change color, ...).
I have this code:
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/distance.js"></script> <!-- https://github.com/janantala/GPS-distance/blob/master/javascript/distance.js -->
<script type="text/javascript" charset="utf-8">
var interval = 5; // [s]
var timeout = 60; // [s]
/* --------------------------------------------------- */
var latitude = new Array();
var longtitude = new Array();
var nameOfLocation = new Array();
// address 1
// Latitude : 10.20 | Longitude : 30.40
latitude[0] = 10.20;
longtitude[0] = 30.40;
nameOfLocation[0] = "address 1";
// address 2
// Latitude : 40.30 | Longitude : 20.10
latitude[1] = 40.30;
longtitude[1] = 20.10;
nameOfLocation[1] = "address 2";
// ...
/* --------------------------------------------------- */
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
console.log('in onDeviceReady()');
$(document).ready(function(){
setInterval(function(i) {
navigator.geolocation.getCurrentPosition(onSuccess, onError, {
maximumAge: 0,
timeout: (timeout*1000),
enableHighAccuracy: true }
);
}, (interval*1000))
});
}
// onSuccess Geolocation
function onSuccess(position) {
console.log('in onSuccess()');
console.log(position.coords.latitude, "position.coords.latitude");
console.log(position.coords.longitude, "position.coords.longitude");
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Accuracy: ' + position.coords.accuracy + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Heading: ' + position.coords.heading + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + position.timestamp + '<br />';
var place;
var accuracy;
$("#accuracy").html("GPS accuracy " + position.coords.accuracy + " m.");
if (position.coords.accuracy < 40) {
$("#accuracy").css("background-color", "Gray");
for (var i=0; nameOfLocation.length; i++) {
var distance = getDistance(latitude[0], longitude[0], position.coords.latitude, position.coords.longitude);
if (distance <= 25) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "OrangeRed");
} else if (distance <= 20) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "Yellow");
} else if (distance <= 15) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "Green");
}
}
$("#info").html("You are about <strong>" + accuracy + "</strong> meters from location <strong>" + nameOfLocation[i] + "</strong>");
} else {
$("#info").html("");
}
}
// onError Callback receives a PositionError object
function onError(error) {
console.log('in onError()');
console.log(error.code, "error.code");
console.log(error.message, "error.message");
$("#geolocation").html(
'code: ' + error.code + '<br />' +
'message: ' + error.message);
$("#accuracy").css("background-color", "");
}
</script>
</head><body>
<p id="info"></p>
<hr />
<p id="accuracy"></p>
<hr />
<p id="geolocation">GPS ...</p>
</body></html>
I use this JS lib for distance measurement of two GPS locations https://github.com/janantala/GPS-distance/blob/master/javascript/distance.js
I can't use google online gps distance lib. App must work without internet connection.
If I run app it start location gps. After first finding location any next finding take only about 5 seconds and after that stop finding locations (this repeats to infinity). I need permanent searching.
Do you know where is an error?
I'm going to do it well?

Values Not Being Passed Using API & JS

I'm creating a simple application to get the user's coordinates, plug them into the Forecast API, and get back the current weather. Things seem to be working smoothly for the first 2 parts but when it's all put together, the coordinates are not passed properly into the API call even though they are printed just fine. Pretty confused and appreciate any help.
<!DOCTYPE html>
<html>
<body>
<p>Here's the weather:<p>
<p id="weather"><p>
<p>Here's the coordinates:<p>
<p id="coordinates"><p>
<button onclick="b()">Submit</button>
<script>
function b(){
var apiKey = 'b04dbf475994a98f5849aa6856a4596d';
var url = 'https://api.forecast.io/forecast/';
var data;
var lati = 0;
var longi = 0;
navigator.geolocation.getCurrentPosition(getCoordinates);
function getCoordinates(position) {
lati = position.coords.latitude;
longi = position.coords.longitude;
}
$.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data) {
console.log(data);
$('#weather').html(data.currently.temperature);
$('#coordinates').html(lati + "," + longi);
});
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</body>
</html>
Try adding the $.get into your function that collects the geolocation. I suspect that is asynchronous.
function getCoordinates(position) {
lati = position.coords.latitude;
longi = position.coords.longitude;
$.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data) {
console.log(data);
$('#weather').html(data.currently.temperature);
$('#coordinates').html(lati + "," + longi);
});
}

HTML parser in Javascript

Hi i at the momment try to parse some HTML news for our new fan page.
Caus the company do not offer a RSS Feed.
I got a new JS File with that included
function getNews() {
y = 0;
news = new Array(7);
news_content = new Array(5);
for (var i = 0; i < news.length; i++)
{
var table = document.getElementById('news').contentWindow.getElementsByTagName('table')[y];
news_content[0] = table.rows[0].cells[0].getElementsByTagName('img')[0].src;
news_content[1] = table.rows[0].cells[1].getElementsByTagName('span')[0].innerHTML;
news_content[2] = table.rows[0].cells[2].getElementsByTagName('span')[0].innerHTML;
news_content[3] = table.rows[1].cells[0].getElementsByTagName('p')[0].innerHTML;
news_content[4] = table.rows[0].cells[0].getElementsByTagName('a')[0].href;
//alert(news[0] + "\n" + news[1] + "\n" + news[2] + "\n" + news[3] + "\n" + news[4]);
news[i] = news_content[0] + "\n" + news_content[1] + "\n" + news_content[2] + "\n" + news_content[3] + "\n" + news_content[4] + "\n";
y = y + 2;
}
alert (news[0] + "\n" + news[1] + "\n" + news[2] + "\n" + news[3] + "\n" + news[4])
}
and that html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Unbenanntes Dokument</title>
<script src="test.js"></script>
</head>
<body>
Hier klicken
<iframe id="news" src="http://www.aerosoft-shop.com/list_news.php?cat=fs&lang=de">
</body>
</html>
At last if i pase the source code into the html file it works but is there no way to parse from a external page?
If you debug your code with a tool like Firebug, a errormessage would be returned like this:
Permission denied to access property 'getElementsByTagName'
It's indeed not possible in JavaScript to access a IFrame which points to a different domain, not even subdomain of your domain (according to the comment on this answer it is possible).
The question here is, if the site-owner wants you do crawl his site off or at least gave you an okay for it, because its generally not that welcomed to get crawled from other sources (traffic and maybe copyright problems).

Categories

Resources