HTML5 Geolocation API使您可以与自己喜欢的网站共享位置。Javascript可以捕获您的纬度和经度,并且可以发送到后端Web服务器,并可以进行精美的位置感知操作,例如查找本地商家或在映射上显示您的位置。地理位置坐标指定设备的地理位置。
我们将使用getCurrentPostion()
方法来获取当前位置。要使用HTML5地理位置和Google Maps获取当前位置,您需要为Google Static Maps API设置API键。
转到https://console.developers.google.com并获得Google Map的免费API键。将此键添加到代码中以使用Geolocation。
您可以尝试使用HTML5地理位置和Google Maps来运行以下代码以显示当前位置-
<!DOCTYPE HTML> <html> <head> <script type = "text/javascript"> function showLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var latlongvalue = position.coords.latitude + "," + position.coords.longitude; var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=" +latlongvalue+"&zoom=14&size = 400x300&key = AIzaSyAa8HeLH2lQMbPeOiMlM9D1VxZ7pbGQq8o"; document.getElementById("mapholder").innerHTML = "<img src ='"+img_url+"'>"; } function errorHandler(err) { if(err.code == 1) { alert("Error: Access is denied!"); }else if( err.code == 2) { alert("Error: Position is unavailable!"); } } function getLocation(){ if(navigator.geolocation){ //超时为60000毫秒(60秒) var options = {timeout:60000}; navigator.geolocation.getCurrentPosition (showLocation, errorHandler, options); }else{ alert("Sorry, browser does not support geolocation!"); } } </script> </head> <body> <div id="mapholder"></div> <form> <input type="button" onclick="getLocation();" value="Your Location"/> </form> </body> </html>