Home > Web Front-end > JS Tutorial > body text

How to use JS to get local latitude and longitude

不言
Release: 2018-07-17 16:05:37
Original
3999 people have browsed it

The content of this article is to use js to obtain the local longitude and latitude. Friends in need can refer to

The simplest calling method

window.navigator.geolocation.getCurrentPosition(function (position) {
    console.log(position.coords.latitude)
    console.log(position.coords.longitude)
})
Copy after login

The encapsulated code is as follows:

function getPosition () {
  return new Promise((resolve, reject) => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function (position) {
        let latitude = position.coords.latitude
        let longitude = position.coords.longitude
        let data = {
          latitude: latitude,
          longitude: longitude
        }
        resolve(data)
      }, function () {
        reject(arguments)
      })
    } else {
      reject('你的浏览器不支持当前地理位置信息获取')
    }
  })
}
Copy after login

The calling method is as follows:

      // 获取当前经纬度坐标
      getPosition().then(result => {
        // 返回结果示例:
        // {latitude: 30.318030999999998, longitude: 120.05561639999999}
        // 一般小数点后只取六位,所以用以下代码搞定
        let queryData = {
          longtitude: String(result.longitude).match(/\d+\.\d{0,6}/)[0],
          latitude: String(result.latitude).match(/\d+\.\d{0,6}/)[0],
          channelType: '00'
        }
        console.log(queryData)
        // 以下放置获取坐标后你要执行的代码:
        // ...
      }).catch(err => {
        console.log(err)
      })
Copy after login

Remember, this is an asynchronous operation, so the code that needs to be executed after obtaining the coordinates cannot be written directly after the function, but should be written in then (refer to The location written in the comment)

Related recommendations:

How to get the longitude and latitude through WeChat js

The above is the detailed content of How to use JS to get local latitude and longitude. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template