在加载网页时获取位置 [英] get location when pages loads

查看:128
本文介绍了在加载网页时获取位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个使用HTML,CSS和Java脚本的网站。我想在页面加载时获取用户的位置。所以他们不需要按下按钮。我希望有人能帮助。

I am Building a website useing HTML, CSS and Java script. I am wanting to get the location of the user when page loads. so they do not need to press a button. I was hoping some one can help.

!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<script>
var x=document.getElementById("demo");
function getLocation(){
 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;    
 }
</script>
</body>
</html>


推荐答案

只需调用 getLocation()

Simply call the getLocation()

<script>
        var x=document.getElementById("demo");
        function getLocation()
         {
        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;  
        }
        getLocation()
        </script>

小提琴: http://jsfiddle.net/ES4TF/

这篇关于在加载网页时获取位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆