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");
Related
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.
I have a slight issue using the following javascript within an ASP loop
<script type="text/javascript">
var geocoder, location1, location2, gDir;
function initialize() {
geocoder = new GClientGeocoder();
gDir = new GDirections();
GEvent.addListener(gDir, "load", function() {
var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
var drivingTime = gDir.getDuration().html
document.getElementById("<%=brokeridnum%>").innerHTML = '<strong>Address 1: </strong>' + location1.address + ' <br /><strong>Address 2: </strong>' + location2.address + '<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles.toFixed(2) + ' miles taking ' + drivingTime;
});
}
</script>
<script type="text/javascript">
function showLocation(startpc, endpc) {
geocoder.getLocations(startpc, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the first address");
}
else
{
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
geocoder.getLocations(endpc, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the second address");
}
else
{
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
gDir.load('from: ' + location1.address + ' to: ' + location2.address);
}
});
}
});
}
</script>
when the loop runs the javascript only displays inside the element once.
the <%=brokeridnum%> inserts a number into the JS and this is working correctly looking at the source from chrome.
the element with the id of brokeridnum is also working.
<script type="text/javascript">
initialize();
showLocation("postcode1","<%=destpc%>");
</script>
<p id="<%=rsbkr("broker_id")%>"></p>
that is how the functions are called
Any help would be greatly appreciated!
Without seeing the entire script I can only guess...
Maybe instead of looping the entire script, try
only looping the function call with a parameter like this:
<% Do . . . %>
<script type="text/javascript">
initialize(<%= brokeridnum %>);
</script>
<% LOOP . . . %>
The function now outside the loop waits for the brokerid parameter...
function initialize(brokerid){
.....
.....
document.getElementById(brokerid).innerHTML = '......
}
Sorry about abbreviating the code a bit, but I hope I helped.
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?
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);
});
}
i'm using phone gap and I got the geolocation working like so:
function onDeviceReady() {
//navigator.geolocation.getCurrentPosition(onSuccess, onError);
var options = { frequency: 3000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
function onSuccess(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + lat + '<br />' +
'Longitude: ' + long + '<br />' +
'<hr />' + element.innerHTML;
}
But I get the wrong latitude and longitude when testing in xCode. Is that normal?
Thanks
I believe you can go to the Debug -> Location option in the iOS simulator to change the GPS co-ordinates.