Save current geolocation to variable - html

How can I save lat and lng values to variables using HTML5 geolocation API?
This is my code, copied from w3schools. How can I save coordinates to variables like var x= position.coords.latitude; and var y= position.coords.longitude; instead of just showing the values like the code is doing right now? I am beginner with javascript so I don't know how to do this
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<script>
var x=document.getElementById("demo");
window.onload = function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.watchPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br />Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
And in my application I need to send values of those variables to server every minute. Would it be better to do the geolocation with watchposition or execute function that does getcurrentposition every minute?

Adding them to variables is as easy as:
var lat = position.coords.latitude;
var lon = position.coords.longitude;
OR as an object:
var coords = {lat: "", lon: ""};
Then to use the object in your code:
function showPosition(position)
{
coords.lat = position.coords.latitude;
coords.lon = position.coords.longitude;
x.innerHTML="Latitude: " + coords.lat +
"<br />Longitude: " + coords.lon;
}
As for sending the variables to a server this depends on what your serverside technology is but you will find many examples on google.
function sendToServer(){
// here you can reuse the object to send to a server
console.log("lat: " + coords.lat);
console.log("lon: " + coords.lon);
}

Related

Uncaught TypeError: undefined is not a function used google maps with leaflet js

I have two markers at the same position (the longitude and latitude)
So to resolve this , i have tried to use markercluster Option .
I was following this fiddle to implement markercluster feature into my code
http://jsfiddle.net/dP9aG/96/
This is my fiddle
http://jsfiddle.net/dP9aG/101/
But when i tried to use leaflet with my code
i am getting the following error in my console
Uncaught TypeError: undefined is not a function
This is my code
var map;
var markers = new L.MarkerClusterGroup();
initmap();
function initmap() {
map = new L.Map('map');
var googleLayer = new L.Google('ROADMAP');
map.addLayer(googleLayer);
drawTestLine();
};
function drawTestLine() {
var lat = 51;
var long = 7;
for (var i = 0; i < 50; i++) {
var myMarker = new L.Marker(new L.LatLng(lat, long), 3);
myMarker.on('click', function(e) {
popup = new L.Popup();
popup.setLatLng(this.getLatLng());
var popuptxt = "Hello!";
alert("I am the click function");
popup.setContent(popuptxt);
map.openPopup(popup);
});
markers.addLayer(myMarker);
lat = lat + 0.0001;
long = long + 0.0001;
}
map.addLayer(markers);
};
Could you please let me know how to resolve this , thanks
http://jsfiddle.net/dP9aG/101/
You did not include the Google maps script in your header. The example you are referring to is using openstreetmaps and there the map script is loaded in the js.
Here's the updated fiddle. I could get the map loaded fine.
<script src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>
<script src="http://matchingnotes.com/javascripts/leaflet-google.js"></script>

HTML5 geolocation is not accurate

I was using the following code to get my current location. But the longitude and latitude generated was not at all accurate. It was showing a location about 700 Kms away from my location. How can I make it accurate?
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
Or you could try a different geocoding provider.
There are lots to choose from:
https://smartystreets.com
http://geocoder.us
http://geoservices.tamu.edu/Services/Geocode/
Disclaimer: I'm a developer at SmartyStreets.
Probably you are not using GPS. If you aren't, then navigator.geolocation.getCurrentPosition returns a position based on your ISP

HTML5 Geolocation API is not working on JSFiddle

I have below mentioned JSFidle.But it's not working.Can you say why's that ?
Note: I want to run it on JSFiddle.It should show the Latitude and Longitude.
JSFiddle Geolocation
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
Because you have your JavaScript set to run in the load event (the second drop down on the left). The function getLocation only exists within the scope of that load handler, not in the global scope you're trying to call it from.
It works fine if you change it to 'No wrap - in <body>'

Displaying unknown coordiates and present location on same map

I am trying to display latitude and longitude coordinates on a map. This works fine but once this is displayed I also want to display the users current location on the same map while displaying the other position as well. Could someone please tell me how that is done. This is what I use to display the Lat and Longitude.
function showPosition()
{
//var latlon=position.coords.latitude+","+position.coords.longitude;
var lat = document.getElementById("saved_lat").value;
var lon = document.getElementById("saved_lon").value;
var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
+ lat + "," + lon +"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";
}
First, you will need to get the user's current lat/lng position. Then you will need to use the 'markers' parameter in the static map to show two markers, one for the saved position and one for the user's position.
You can get a description on how to use markers here:
https://developers.google.com/maps/documentation/staticmaps/?csw=1#MarkerLocations
Below is a working modification of your code. Here's some tips:
I hardwired the saved_lat/lon values in the statements for demo'ing purposes. You will need to replace these or use your own HTML code.
The user's coordinate are obtained form the HTML geolocation method navigator.geolocation. This method will pass the lat/lon of the user's location to the ShowPosition() function.
I updated your ShowPosition() function:
A. Take the user's lat/lon as parameters
B. Added variable 'markers' to set two markers (saved and user's) in the google static map.
C. Added variable 'zoom' to set the zoom level.
<script>
// Get User's Coordinate from their Browser
window.onload = function () {
// HTML5/W3C Geolocation
if ( navigator.geolocation )
navigator.geolocation.getCurrentPosition( UserLocation );
// Default to Washington, DC
else
ShowPosition( 38.8951, -77.0367 );
}
// Callback function for asynchronous call to HTML5 geolocation
function UserLocation( position )
{
ShowPosition( position.coords.latitude, position.coords.longitude );
}
function ShowPosition( user_lat, user_lon )
{
var lat = document.getElementById("saved_lat").value;
var lon = document.getElementById("saved_lon").value;
var markers = "&markers=color:blue|label:S|" + lat + "," + lon + "|" + user_lat + "," + user_lon;
var zoom="&zoom=11";
var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
+ lat + "," + lon +"&size=400x300&sensor=false" + zoom + markers;
document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";
}
</script>
<body>
<div id="mapholder"></div>
<input type="hidden" id="saved_lat" value="45.65"/>
<input type="hidden" id="saved_lon" value="-122.45"/>
</body>

How to enable geolocation in Chrome

I got the HF HTML5 book , and when i reached to the chapter about geolocation and typed the code in , it doesn't work , i tried enabling the geo-location features in preferences but still no change , any suggestions?
The JS:
window.onload = getMyLocation;
function getMyLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation);
} else {
alert("Oops, no geolocation support");
}
};
function displayLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("location");
div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
};
Problem was solved.
I found out that it's a bug from chrome , every file:// has it , you can't do it without a server like WAMP , or you can use an other browser.
Try binding event handler like this:
window.onload = new function() { getMyLocation() };
Here is the fiddle.