HTML5 Geolocation API获取地理位置
Geolocation API
纬度:
经度:
精确度:
<!DOCTYPE HTML> <html lang="cn"> <head> <meta charset="UTF-8"> <title>Geolocation API</title> <script type="text/javascript"> var totalDistance = 0.0; var lastLat = null; var lastLong = null; function toRadians(degree) { return degree * Math.PI / 180; } function distance(latitude1, longitude1, latitude2, longitude2) { var R = 6371; var deltaLatitude = toRadians(latitude2 - latitude1); var deltaLongitude = toRadians(longitude2 - longitude1); latitude1 = toRadians(latitude1); latitude2 = toRadians(latitude2); var a = Math.sin(deltaLatitude / 2) * Math.sin(deltaLatitude / 2) + Math.cos(latitude1) * Math.cos(latitude2) * Math.sin(deltaLongitude / 2) * Math.sin(deltaLongitude / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; } function $(id) { return document.getElementById(id); } function updateStatus(message) { document.getElementById('status').innerHTML = message; } function loadDemo() { if (navigator.geolocation) { updateStatus(""); navigator.geolocation.watchPosition(updateLocation, handleLocationError, { maxmumAge : 20000 }); } } window.addEventListener('load', loadDemo, true); function updateLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var accuracy = position.coords.accuracy; var timestamp = position.timestamp; $('latitude').innerHTML = latitude; $('longitude').innerHTML = longitude; $('accuracy').innerHTML = '这个位置的精确度在 ' + accuracy + ' 米。'; $('timestamp').innerHTML = timestamp; if ((lastLat !== null) && (lastLong !== null)) { var currentDistance = distance(latitude, longitude, lastLat, lastLong); $('currDist').innerHTML = '目前的距离:' + currentDistance.toFixed(4)* 1000 + ' m'; totalDistance += currentDistance; alert(currentDistance); $('totalDist').innerHTML = '总距离:' + totalDistance.toFixed(4)*1000 + ' m'; } lastLat = latitude; lastLong = longitude; updateStatus("位置成功更新!"); } function handleLocationError(err) { switch (err.code) { case 1: alert('位置服务被拒绝'); break; case 2: alert('获取不到位置信息'); break; case 3: alert('获取信息超时'); break; default: alert('未知错误!'); } } </script> </head> <body> <div>纬度:<span id="latitude"></span></div> <div>经度:<span id="longitude"></span></div> <div>精确度:<span id="accuracy"></span></div> <div><span id="timestamp"></span></div> <h4 id="currDist"></h4> <h4 id="totalDist"></h4> <div id="status"></div> </body> </html>