-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
131 lines (116 loc) · 7.18 KB
/
index.html
File metadata and controls
131 lines (116 loc) · 7.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="https://web3examples.com/logo.png">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<meta charset="UTF-8">
<link rel="stylesheet" href="leaflet/leaflet.css" />
<script src="leaflet/leaflet.js"></script>
<script src="https://unpkg.com/web3@latest/dist/web3.min.js"></script>
</head>
<body>
<h1>Distance to HHS on ethereum blockchain</h1>
<button onclick="SaveLocation()">Press here to determine location</button><br> <!-- needs user interaction for geolocation to work -->
<div id="map" style="width:100%;height:200px" ></div>
<button onclick="SaveOnBlockchain()">Press here to save on blockchain</button><br> <!-- needs user interaction for geolocation to work -->
<pre id="log" style="width:100%;height:200px"></pre>
<script type="text/javascript">
function log(str,...arguments) {
var logstr=arguments.toString();
document.getElementById("log").innerHTML +=str+" "+logstr+"\n";
}
function EtherscanLink(pref,link) {
return '<a href="https://rinkeby.etherscan.io/'+pref+"/"+link+'" target="_blank" >'+link+'</a>';
}
// https://www.geodatasource.com/developers/javascript
function distance(lat1, lon1, lat2, lon2) {
if ((lat1 == lat2) && (lon1 == lon2)) {
return 0;
}
else {
var radlat1 = Math.PI * lat1/180;
var radlat2 = Math.PI * lat2/180;
var theta = lon1-lon2;
var radtheta = Math.PI * theta/180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = dist * 180/Math.PI;
dist = dist * 60 * 1.1515;
dist = dist * 1.609344 // kilometers
dist = Math.round(dist * 1000) // meters
return dist;
}
}
if ((location.protocol != 'https:') && (location.href != "http://127.0.0.1/location/")) { // make sure we are on https, otherwise geolocation doesn't work
location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}
var map = L.map('map');
var basemap = L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: 'web3examples.com'}); // load OpenStreetMap basemap
basemap.addTo(map);
const lathhs=52.0672; // https://www.google.com/maps/search/?api=1&query=52.0672,4.3245
const lonhhs=4.3245;
var dist=-1;
var accounts=[];
DistanceHHSABI=[{"constant": false,"inputs": [{"name": "distance","type": "uint256"}],"name": "StoreDistanceHHS","outputs": [],"payable": false,"stateMutability": "nonpayable","type": "function"}];
async function SaveOnBlockchain() {
if (dist < 0) { log("No location yet");return;}
if (accounts.length == 0 || accounts[0].length < 10 ) { log("No ethereum address yet");return;}
DistanceHHSaddress="0x609F224c0c9405a1e7FD404114ca8A8606edC3a3"
const DistanceHHSContract = new web3.eth.Contract(DistanceHHSABI, DistanceHHSaddress );
log(`Storing distance to HHS: distance=${dist} (hex:${web3.utils.toHex(dist)}) `);
x=await DistanceHHSContract.methods.StoreDistanceHHS(dist).send({from: accounts[0]}).catch( (reason) => log(`Cannnot do transaction ${reason}`) );;
log(`Transaction hash: ${EtherscanLink("tx",x.transactionHash)}`);
}
async function SaveLocation(){
log("Trying to get location");
if (navigator.permissions) {
var status=await navigator.permissions.query({name:'geolocation'});
log (`Permission ${status.state}`);
console.log(status.state);
}
if (!navigator.geolocation) { log('Geolocation not supported');return;}
const location = await new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition( (x) => resolve(x), (y) => reject(y.message)) ).catch ( (reason) => log(`Geolocation error: ${reason}`) );
if (!location) return;
dist=distance(lathhs,lonhhs,location.coords.latitude,location.coords.longitude);
log(`Coordinates: lat=${location.coords.latitude}, lon=${location.coords.longitude} Distance to HHS=${dist}`);
var url=`https://geodata.nationaalgeoregister.nl/locatieserver/revgeo?lat=${location.coords.latitude}&lon=${location.coords.longitude}`;
var latlng = new L.LatLng(location.coords.latitude, location.coords.longitude);
map.setView(latlng, 15)
var marker = L.marker(latlng).addTo(map);
var response = await fetch (url);
response = await response.json();
log(`Physical location: ${response.response.docs[0].weergavenaam}`);
}
async function asyncloaded() {
console.log(ethereum)
console.log(typeof ethereum)
console.log(web3.version)
if (typeof ethereum !== 'undefined')
await ethereum.enable().catch( (reason) => log('User rejected provider access',reason.message.substring(0,50)) )
if (! (Web3.givenProvider || ethereum) ) { // Checking if web3 is accessible
log("Web3 interface is not found. "+
"Please install <a href='https://metamask.io'>Metamask</a>"+
" or use <a href='https://www.opera.com/crypto'>Opera Crypto (android)");
return; // stop this function
}
web3 = new Web3(Web3.givenProvider || ethereum); // switch to version 1.0 when using metamask; provide web3 functions for Opera
//typeof web3 === 'undefined' || web3 == 'undefined'
log(`web3 is present: ${web3.version}`); // note: use ` (back quote)
const network = await web3.eth.net.getId().catch( (reason) => log(`Cannnot find network ${reason}`) );
if (typeof network === 'undefined' || network != 4)
{ log("Please select Rinkeby test network");return;}
log("Ethereum network: Rinkeby")
accounts=await web3.eth.getAccounts();
log(`Ethereum address: ${EtherscanLink("address",accounts[0])}`);
log(`<a href="listlocation.html?address=${accounts[0]}" target="_blank" >See check-ins of address ${accounts[0]}</a>`);
log('<br>');
log(`<a href="https://web3examples.com/ethereum/faucet/" target="_blank" >Get test ETH</a>`);
log('<br>');
}
window.addEventListener('load', asyncloaded);
</script>
</body>
</html>