HTML5 Geolocation - javascript

I use this to geolocate the user and I need the values of currentLat and currentLon stored in a var:
<script>
window.onload = function() {
var startPos;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
document.getElementById("currentLat").innerHTML = startPos.coords.latitude;
document.getElementById("currentLon").innerHTML = startPos.coords.longitude;
});
}
};
</script>
I need those values in here:
http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=my_key&radius_units=km&radius=5&lat= XXX &lon= XXX &jsoncallback=?
How do I get the values through jQuery and put them in the URL immediately? What's the quickest way?
Thanks #Manuel but I have used it like this first as I don't need the error function, just to keep it simple so I can understand it but doesn't work?!
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var JSONURL = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=my_key&format=json&privacy_filter=1&media=photos&tag=london&minwidth=700&has_geo=1&accuracy=11&content_type=1&extras=geo,owner_name,url_m&page=1&radius_units=km&radius=5&"+lat+"&lon="+lon+"&jsoncallback=?";
jQuery.getJSON( JSONURL, getJSONimages);
function getJSONimages(data) {
var htmlString = "";
$.each(data.photos.photo, function(i,item){
var itemTitle = item.title;
});
$('#slideshow').html(htmlString);
$('#slideshow').slideshow({
timeout: 3000,
type: 'random',
fadetime: 2000
});
} }
})

in the var url you'll get find the url with the lat an lon filled in
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var url = 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=my_key&radius_units=km&radius=5&lat='+lat+'&lon='+lon+'&jsoncallback=?';
// console.log(url);
}, function(error) {
console.log("Something went wrong: ", error);
});

Related

How to get current location (latitude and longitude) and send it to an reverse geocoding API?

I am trying to get my current latitude and longitude and passing it to a web API called OpenCage Geocoder API. This is what I have done:
// reverse geocoding
function geocode() {
let lat,long;
window.onload = function() {
var startPos;
var geoSuccess = function(position) {
startPos = position;
lat = startPos.coords.latitude;
long = startPos.coords.longitude;
};
navigator.geolocation.getCurrentPosition(geoSuccess);
};
geoResponse = function(reponse)
{
document.getElementById("address").innerHTML = response.results[17].toString();
};
let script = document.createElement('script');
script.src = "https://api.opencagedata.com/geocode/v1/json?q="+ lat +","+ long +"&key=00f711f73483427c8577e646aa2bf4bf&jsonp=geoResponse";
document.body.appendChild(script);
}
I'm new to coding, and I am a bit stuck. Is there any easier method to call this particular API, I'm pretty lost.
Any help would be great thanks!
I have modified and attached the snippet of your code for Reference! In your getResponse you received the param as reponse and in code you have called the response.results[17].toString() Which got undefined!
window.onload = function() {
navigator.geolocation.getCurrentPosition(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var script = document.createElement('script');
script.src = "https://api.opencagedata.com/geocode/v1/json?q="+ lat +","+ long +"&key=00f711f73483427c8577e646aa2bf4bf&jsonp=geoResponse";
document.body.appendChild(script);
});
}
geoResponse = function(reponse){
document.getElementById("address").innerHTML = reponse.results[0].formatted;
}
<div id="address">
</div>

Javascript - Save Geolocation Coordinates

How can i save the coordinates in localstorage so that it shouldn't ask the users every time to allow GPS or Location and a button to clear the localstorage value so it can again ask for coordinates?
FYI:
I am using Praytimes JS to display Muslim prayer times but for each location i have to manually add latitude & longitude of that location.
Below is my code:
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var x = document.getElementById("currentlocation");
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
$('#currentlocation').html("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
$('#currentlocation').html(results[0].formatted_address);
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
$('#currentlocation').html(city.short_name + " " + city.long_name)
} else {
$('#currentlocation').html("No results found");
}
} else {
$('#currentlocation').html("Geocoder failed due to: " + status);
}
});
}
</script>
<p id="currentlocation"></p>
<script type="text/javascript" src="http://praytimes.org/code/v2/js/PrayTimes.js"></script>
<script type="text/javascript">
function loadTable(position) {
prayTimes.setMethod('MWL');
var date = new Date(); // today
var times = prayTimes.getTimes(date, [position.coords.latitude, position.coords.longitude]);
var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha', 'Midnight'];
var html = '<table id="timetable">';
html += '<tr><th colspan="2">'+ date.toLocaleDateString()+ '</th></tr>';
for(var i in list) {
html += '<tr><td>'+ list[i]+ '</td>';
html += '<td>'+ times[list[i].toLowerCase()]+ '</td></tr>';
}
html += '</table>';
document.getElementById('table').innerHTML = html;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(loadTable);
}
</script>
Define an object with the informations of the coordinates:
var coordinatesObject =
{
lat: position.coords.latitude,
lng: position.coords.longitude
}
Save it in the local storage:
localStorage.setItem('coordinates',
JSON.stringify(coordinatesObject));
Get it:
let objFromLocalStorage =
localStorage.getItem('coordinates');
var CACHED_POSITION = "CACHED_POSITION";
var x = document.getElementById("currentlocation");
var geocoder;
(function () {
if (navigator.geolocation) {
try {
var position = JSON.parse(window.localStorage[CACHED_POSITION]);
if (position) {
successFunction(position);
return;
}
} catch (e) {
}
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
})();
//Get the latitude and the longitude;
function successFunction(position) {
window.localStorage[CACHED_POSITION] = JSON.stringify(position);
var lat = position.coords.latitude;
var lng = position.coords.longitude;//Save to cache
codeLatLng(lat, lng);
}

How to use this script to redirect user?

var GOOGLE_API_KEY = "mykey";
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
}
function errorFunction() {
alert ("Geocoder failed");
}
function reverseGeoCoding(lat, lng) {
var geoCodingUrl = "https://maps.googleapis.com/maps/api/geocode/json? latlng=" + lat + "," + lng + "&key=" + GOOGLE_API_KEY
return $.get(geoCodingUrl)
}
reverseGeoCoding(lat, lng)
.then(function(data) {
var address = results[6].formatted_address;
if (address == "Mumbai, India") {
window.location = "url";
}
if(address == "Bangalore, India"){
window.location = "url";
}
if(address == "Jaipur, India") {
window.location = "url";
}
else{
window.location = "url";
}
});
I wanted to utilise this script to redirect users based on the address retrieved by making use of Google's API. However, console error message says variable 'lat' cannot be found?
You should do this:
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
reverseGeoCoding(lat, lng).then(function(data) {
var address = results[6].formatted_address;
if (address == "Mumbai, India") {
window.location = "url";
}
if(address == "Bangalore, India"){
window.location = "url";
}
if(address == "Jaipur, India") {
window.location = "url";
}
else{
window.location = "url";
}
})
}
Or declare it as global variables

How to run success function with JQuery getJSON?

I want to push data to an array, but am unsure how to go about this due to AJAX's asychronisity.
I can't seem to find complete examples online of the way this is done with getJSON.
I've been following the documentation here with no luck/
I have tried:
var jsonLtdLng="https://maps.googleapis.com/maps/api/geocode/json?address=" + addressval;
var latlng;
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
latlng = {lat: lat, lng: lng};
}).done(function() {
markerlocations.push(latlng);
})//END JSON
and:
var jsonLtdLng="https://maps.googleapis.com/maps/api/geocode/json?address=" + addressval;
var latlng;
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
latlng = {lat: lat, lng: lng};
markerlocations.push(latlng);
});
and variations of this with no results.
Would anyone know the correct way of doing this and can point me in the right direction?
You need to push() to the array in the success handler which has access to the data returned from the request. You would also be better to add objects to the array instead of manually hacking around a JSON string. From there you can pass the array to whatever function you need to execute. Try this:
var markerlocations = [];
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat; // note 'lat' here, not 'lng'
var lng = data.results[0].geometry.location.lng;
markerlocations.push({ lat: lat, lng: lng });
doSomethingWithTheArray(markerlocations);
});
function doSomethingWithTheArray(arr) {
for (var i = 0; i < arr.length; i++) {
console.log(arr[i].lat, arr[i].lng);
}
}
Try this. Use foreach to create your array. Then push/append the array as you want.
$.getJSON("url here", function(data) {
$.each(data, function(key, value){
// your custom code here
var latlng = 'code you want';
});
markerlocations.push(latlng);
});
You need to declare an empty array outside getJSON() function. Then it is accessible inside getJSON callback.
var markerlocations = [];
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
markerlocations.push({ lat: lat, lng: lng });
});
function(data)... is the callback function which gets executed once the response is obtained. You don't need another done() method in this case.
var jsonLtdLng="https://maps.googleapis.com/maps/api/geocode/json?address=new york";
var latlng;
var markerlocations = [];
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
latlng = {lat: lat, lng: lng};
markerlocations.push(latlng);
// just for testing
for(var i = 0; i < markerlocations.length; i++){
alert(markerlocations[i].lat + '===' + markerlocations[i].lng);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

how do i convert Lat and Long to uk postcode with Javascript

I'm trying to make use of HTML5 geolocation for a project I'm working on.
It seems pretty straighforward to get the Lat and Long of where a user is, via geolocation.
Problem is, I need to convert this to a UK postcode, and am strugging as I'm trying to learn javascript.
The code I have working is:
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
var Lat = position.coords.latitude;
var Long = position.coords.longitude;
var inputField = document.getElementById("addressInput");
inputField.value = Lat + Long;
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
I've found this site, whihc does exactly the kind of thing I want to achieve:
http://www.latlong.net/Show-Latitude-Longitude.html
Can anyone give me some tips on how to get this working?
Any advice would be great
thanks in advance
=========================
Amended code:
//var long = '50.**************', lat = '0.**************'
var Lat='';
var Long='';
var coordsObj = {coords:{latitude:Lat, longitude:Long}};
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
console.log(position, position.coords)
console.log("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
var Lat = position.coords.latitude;
alert(Lat);
var Long = position.coords.longitude;
alert(Long);
var inputField = document.getElementById("addressInput");
inputField.value = Lat + Long;
return [Lat, Long];
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
function reverseGeoLookup(lon, lat) {
var req = new XMLHttpRequest()
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
req.onreadystatechange = function() {
if(req.readyState == 4) {
var result = JSON.parse(req.response).results
for(var i = 0, length = result.length; i < length; i++) {
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output')
out.innerHTML += component.long_name
}
}
}
}
}
req.send()
}
var latlng = displayPosition(coordsObj)
reverseGeoLookup.apply(this, latlng)
There's now a free UK government alternative to the other options listed here. Go to http://postcodes.io/ to see the details of the API and examples. It also supports reverse lookups which is what you're after
You could use the Google Maps reverse geocoding API. This allows you to map a lat, long pair to a set of addresses. For example:
function reverseGeoLookup(lon, lat) {
//make a ajax request -- in prod just use whatever libraryyou have to provide this
//probably jquery's $.get
var req = new XMLHttpRequest()
//put the longitude and latitude into the API query
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
//this is just the result callback -- it's the function arg to $.get, essentially
req.onreadystatechange = function() {
if(req.readyState == 4) {
//again jquery will parse for you, but we want the results field
var result = JSON.parse(req.response).results
//the maps API returns a list of increasingly general results
//i.e. street, suburb, town, city, region, country
for(var i = 0, length = result.length; i < length; i++) {
//each result has an address with multiple parts (it's all in the reference)
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
//if the address component has postal code then write it out
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output')
out.innerHTML += component.long_name
}
}
}
}
}
//dispatch the XHR... just use jquery
req.send()
}
I put this example into a js fiddle too, here.
Hope this helps.
I've made some changes to kieran's fiddle to more to help fully answer the question of getting a UK postcode from an html5 geolocation.
var x=document.getElementById("output");
getLocation();
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.watchPosition(reverseGeoLookup);
}
else
{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function reverseGeoLookup(position) {
console.log(position);
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var req = new XMLHttpRequest()
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
req.onreadystatechange = function() {
if(req.readyState == 4) {
var result = JSON.parse(req.response).results
for(var i = 0, length = result.length; i < length; i++) {
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
//console.log(component.long_name);
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output');
out.innerHTML = 'Approximate Post Code for your location is ' + component.long_name;
return false;
}
}
}
}
}
req.send()
}
http://jsfiddle.net/ef72Q/28/

Categories