<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <meta name="referrer" content="never"> <title>HTML5 使用地理定位</title> </head> <body> <p id="demo">点击这个按钮,获得您的坐标:</p> <button>试一下</button> </body> </html>
body { color: deeppink; }
var x = document.getElementById("demo"); document.querySelector("button").onclick = function () { 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; }