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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3452217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:40:02  来源:igfitidea点击:

get current latitude and longitude from gps enabled device

javascriptapimobilegeolocationgps

提问by davidlee

I would like to get the latitude and longitude of current location from gps enabled mobile device right from the web browser. May I know is this possible? how to do it? does it require geolocation api? Some coding example would be helpful. Thanks.

我想从网络浏览器直接从启用 gps 的移动设备获取当前位置的纬度和经度。我可以知道这可能吗?怎么做?它需要地理定位api吗?一些编码示例会有所帮助。谢谢。

回答by Marko

Use the HTML5 Geolocation API, here's the official spec and examples.

使用 HTML5 Geolocation API,这里是官方规范和示例

EDIT

编辑

I've updated my answer to include current browser support.

我已经更新了我的答案以包含当前的浏览器支持。

W3C Geolocation API support

W3C 地理定位 API 支持

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

· ·
Other phones not listed above use Gearsor their own, platform-specific APIs.

· ·
上面未列出的其他手机使用Gears或它们自己的特定于平台的 API。

Ahh, will we ever have just one single API? :)

啊,我们永远只有一个 API 吗?:)

Many thanks to Mark Pilgrim for his awesome post.

非常感谢 Mark Pilgrim 的精彩帖子

回答by Maksym Kozlenko

Here is an actual JavaScript code which uses HTML5 Geolocation API. The following works on both Android browser and iPhone Safari:

这是一个使用 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");

回答by krycek

You don't have to have the newest mobile phone to use GPS and Geolocation API. Almost every mobile browser (without proxy server) can be used to read position from buidin GPS. If You have Java and GPS in Your phone – You can use mobile-gps-web-gate – see at http://code.google.com/p/mobile-gps-web-gate/

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