从启用了GPS的设备中获取当前纬度和经度

9

我想从启用GPS的移动设备上获取当前位置的纬度和经度,直接从Web浏览器中获取。请问这是否可能?如何做到?是否需要使用地理位置API?提供一些编程示例会很有帮助。谢谢。


用户必须自愿提供此信息。请查看移动设备上的Google主页。 - Josh Stodola
哪个设备?哪个API? - Matt Ball
@josh 是的,当然假定用户已经在手机设置中批准共享位置。 - davidlee
请问有没有任何带GPS功能的设备?有什么推荐的API吗? - davidlee
4个回答

17

使用HTML5地理定位API,这里是官方规范和示例

编辑

我更新了我的答案以包括当前浏览器支持情况。

W3C地理定位API支持

Firefox 3.5+
Safari 5.0+
Chrome 5.0+
Opera
iPhone 3.0+
Android 2.0+

除了上述列出的手机,其他手机使用Gears或特定于平台的API。

哎呀,我们什么时候才能只有一个API呢?:)

感谢Mark Pilgrim写的精彩文章post


这是否意味着所有具备 GPS 功能的设备都可以使用 HTML5 地理定位 API?谢谢。 - davidlee
Mark Pilgrim的帖子链接已经无法访问了 :( - David Mårtensson
Google Gears已经被废弃很久了。 - Buhake Sindi
1
@BuhakeSindi 这个问题已经在2.5年前得到了回答。 - Marko
这在移动网络、Chrome(仅限https)或Safari上无法工作。我使用http://ipinfo.io/,它对于连接wifi的设备可以,但返回网络ISP的纬度和经度。 - SimonM

9

以下是一个实际使用HTML5 Geolocation API的JavaScript代码。下面的代码既适用于Android浏览器,也适用于iPhone Safari:

            function onPositionUpdate(position)
            {
                var lat = position.coords.latitude;
                var lng = position.coords.longitude;
                alert("Current position: " + lat + " " + lng);
            }

            if(navigator.geolocation)
                navigator.geolocation.getCurrentPosition(onPositionUpdate);
            else
                alert("navigator.geolocation is not available");

0

您不需要最新的手机即可使用GPS和地理位置API。几乎所有移动浏览器(没有代理服务器)都可以用于从内置GPS读取位置。如果您的手机具有Java和GPS,则可以使用mobile-gps-web-gate - 请参见http://code.google.com/p/mobile-gps-web-gate/


0

对于某些人来说,这可能在未来很有帮助。

<!DOCTYPE html>
<html>
<body>

<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<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) {
 var a = position.coords.latitude + ',' + position.coords.longitude;

 alert(a);
}
</script>
</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接